brintos

brintos / llvm-project-archived public Read only

0
0
Text · 202.0 KiB · 1f40592 Raw
5578 lines · cpp
1//===--- Expr.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 the Expr class and subclasses.10//11//===----------------------------------------------------------------------===//12 13#include "clang/AST/Expr.h"14#include "clang/AST/APValue.h"15#include "clang/AST/ASTContext.h"16#include "clang/AST/ASTLambda.h"17#include "clang/AST/Attr.h"18#include "clang/AST/ComputeDependence.h"19#include "clang/AST/DeclCXX.h"20#include "clang/AST/DeclObjC.h"21#include "clang/AST/DeclTemplate.h"22#include "clang/AST/DependenceFlags.h"23#include "clang/AST/EvaluatedExprVisitor.h"24#include "clang/AST/ExprCXX.h"25#include "clang/AST/IgnoreExpr.h"26#include "clang/AST/Mangle.h"27#include "clang/AST/RecordLayout.h"28#include "clang/Basic/Builtins.h"29#include "clang/Basic/CharInfo.h"30#include "clang/Basic/SourceManager.h"31#include "clang/Basic/TargetInfo.h"32#include "clang/Lex/Lexer.h"33#include "clang/Lex/LiteralSupport.h"34#include "clang/Lex/Preprocessor.h"35#include "llvm/Support/ErrorHandling.h"36#include "llvm/Support/Format.h"37#include "llvm/Support/raw_ostream.h"38#include <algorithm>39#include <cstring>40#include <optional>41using namespace clang;42 43const Expr *Expr::getBestDynamicClassTypeExpr() const {44  const Expr *E = this;45  while (true) {46    E = E->IgnoreParenBaseCasts();47 48    // Follow the RHS of a comma operator.49    if (auto *BO = dyn_cast<BinaryOperator>(E)) {50      if (BO->getOpcode() == BO_Comma) {51        E = BO->getRHS();52        continue;53      }54    }55 56    // Step into initializer for materialized temporaries.57    if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {58      E = MTE->getSubExpr();59      continue;60    }61 62    break;63  }64 65  return E;66}67 68const CXXRecordDecl *Expr::getBestDynamicClassType() const {69  const Expr *E = getBestDynamicClassTypeExpr();70  QualType DerivedType = E->getType();71  if (const PointerType *PTy = DerivedType->getAs<PointerType>())72    DerivedType = PTy->getPointeeType();73 74  if (DerivedType->isDependentType())75    return nullptr;76 77  return DerivedType->castAsCXXRecordDecl();78}79 80const Expr *Expr::skipRValueSubobjectAdjustments(81    SmallVectorImpl<const Expr *> &CommaLHSs,82    SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {83  const Expr *E = this;84  while (true) {85    E = E->IgnoreParens();86 87    if (const auto *CE = dyn_cast<CastExpr>(E)) {88      if ((CE->getCastKind() == CK_DerivedToBase ||89           CE->getCastKind() == CK_UncheckedDerivedToBase) &&90          E->getType()->isRecordType()) {91        E = CE->getSubExpr();92        const auto *Derived = E->getType()->castAsCXXRecordDecl();93        Adjustments.push_back(SubobjectAdjustment(CE, Derived));94        continue;95      }96 97      if (CE->getCastKind() == CK_NoOp) {98        E = CE->getSubExpr();99        continue;100      }101    } else if (const auto *ME = dyn_cast<MemberExpr>(E)) {102      if (!ME->isArrow()) {103        assert(ME->getBase()->getType()->getAsRecordDecl());104        if (const auto *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {105          if (!Field->isBitField() && !Field->getType()->isReferenceType()) {106            E = ME->getBase();107            Adjustments.push_back(SubobjectAdjustment(Field));108            continue;109          }110        }111      }112    } else if (const auto *BO = dyn_cast<BinaryOperator>(E)) {113      if (BO->getOpcode() == BO_PtrMemD) {114        assert(BO->getRHS()->isPRValue());115        E = BO->getLHS();116        const auto *MPT = BO->getRHS()->getType()->getAs<MemberPointerType>();117        Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));118        continue;119      }120      if (BO->getOpcode() == BO_Comma) {121        CommaLHSs.push_back(BO->getLHS());122        E = BO->getRHS();123        continue;124      }125    }126 127    // Nothing changed.128    break;129  }130  return E;131}132 133bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {134  const Expr *E = IgnoreParens();135 136  // If this value has _Bool type, it is obvious 0/1.137  if (E->getType()->isBooleanType()) return true;138  // If this is a non-scalar-integer type, we don't care enough to try.139  if (!E->getType()->isIntegralOrEnumerationType()) return false;140 141  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {142    switch (UO->getOpcode()) {143    case UO_Plus:144      return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);145    case UO_LNot:146      return true;147    default:148      return false;149    }150  }151 152  // Only look through implicit casts.  If the user writes153  // '(int) (a && b)' treat it as an arbitrary int.154  // FIXME: Should we look through any cast expression in !Semantic mode?155  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))156    return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);157 158  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {159    switch (BO->getOpcode()) {160    default: return false;161    case BO_LT:   // Relational operators.162    case BO_GT:163    case BO_LE:164    case BO_GE:165    case BO_EQ:   // Equality operators.166    case BO_NE:167    case BO_LAnd: // AND operator.168    case BO_LOr:  // Logical OR operator.169      return true;170 171    case BO_And:  // Bitwise AND operator.172    case BO_Xor:  // Bitwise XOR operator.173    case BO_Or:   // Bitwise OR operator.174      // Handle things like (x==2)|(y==12).175      return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&176             BO->getRHS()->isKnownToHaveBooleanValue(Semantic);177 178    case BO_Comma:179    case BO_Assign:180      return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);181    }182  }183 184  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))185    return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&186           CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);187 188  if (isa<ObjCBoolLiteralExpr>(E))189    return true;190 191  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))192    return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);193 194  if (const FieldDecl *FD = E->getSourceBitField())195    if (!Semantic && FD->getType()->isUnsignedIntegerType() &&196        !FD->getBitWidth()->isValueDependent() && FD->getBitWidthValue() == 1)197      return true;198 199  return false;200}201 202bool Expr::isFlexibleArrayMemberLike(203    const ASTContext &Ctx,204    LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,205    bool IgnoreTemplateOrMacroSubstitution) const {206  const Expr *E = IgnoreParens();207  const Decl *D = nullptr;208 209  if (const auto *ME = dyn_cast<MemberExpr>(E))210    D = ME->getMemberDecl();211  else if (const auto *DRE = dyn_cast<DeclRefExpr>(E))212    D = DRE->getDecl();213  else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))214    D = IRE->getDecl();215 216  return Decl::isFlexibleArrayMemberLike(Ctx, D, E->getType(),217                                         StrictFlexArraysLevel,218                                         IgnoreTemplateOrMacroSubstitution);219}220 221const ValueDecl *222Expr::getAsBuiltinConstantDeclRef(const ASTContext &Context) const {223  Expr::EvalResult Eval;224 225  if (EvaluateAsConstantExpr(Eval, Context)) {226    APValue &Value = Eval.Val;227 228    if (Value.isMemberPointer())229      return Value.getMemberPointerDecl();230 231    if (Value.isLValue() && Value.getLValueOffset().isZero())232      return Value.getLValueBase().dyn_cast<const ValueDecl *>();233  }234 235  return nullptr;236}237 238// Amusing macro metaprogramming hack: check whether a class provides239// a more specific implementation of getExprLoc().240//241// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.242namespace {243  /// This implementation is used when a class provides a custom244  /// implementation of getExprLoc.245  template <class E, class T>246  SourceLocation getExprLocImpl(const Expr *expr,247                                SourceLocation (T::*v)() const) {248    return static_cast<const E*>(expr)->getExprLoc();249  }250 251  /// This implementation is used when a class doesn't provide252  /// a custom implementation of getExprLoc.  Overload resolution253  /// should pick it over the implementation above because it's254  /// more specialized according to function template partial ordering.255  template <class E>256  SourceLocation getExprLocImpl(const Expr *expr,257                                SourceLocation (Expr::*v)() const) {258    return static_cast<const E *>(expr)->getBeginLoc();259  }260}261 262QualType Expr::getEnumCoercedType(const ASTContext &Ctx) const {263  if (isa<EnumType>(getType()))264    return getType();265  if (const auto *ECD = getEnumConstantDecl()) {266    const auto *ED = cast<EnumDecl>(ECD->getDeclContext());267    if (ED->isCompleteDefinition())268      return Ctx.getCanonicalTagType(ED);269  }270  return getType();271}272 273SourceLocation Expr::getExprLoc() const {274  switch (getStmtClass()) {275  case Stmt::NoStmtClass: llvm_unreachable("statement without class");276#define ABSTRACT_STMT(type)277#define STMT(type, base) \278  case Stmt::type##Class: break;279#define EXPR(type, base) \280  case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);281#include "clang/AST/StmtNodes.inc"282  }283  llvm_unreachable("unknown expression kind");284}285 286//===----------------------------------------------------------------------===//287// Primary Expressions.288//===----------------------------------------------------------------------===//289 290static void AssertResultStorageKind(ConstantResultStorageKind Kind) {291  assert((Kind == ConstantResultStorageKind::APValue ||292          Kind == ConstantResultStorageKind::Int64 ||293          Kind == ConstantResultStorageKind::None) &&294         "Invalid StorageKind Value");295  (void)Kind;296}297 298ConstantResultStorageKind ConstantExpr::getStorageKind(const APValue &Value) {299  switch (Value.getKind()) {300  case APValue::None:301  case APValue::Indeterminate:302    return ConstantResultStorageKind::None;303  case APValue::Int:304    if (!Value.getInt().needsCleanup())305      return ConstantResultStorageKind::Int64;306    [[fallthrough]];307  default:308    return ConstantResultStorageKind::APValue;309  }310}311 312ConstantResultStorageKind313ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {314  if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)315    return ConstantResultStorageKind::Int64;316  return ConstantResultStorageKind::APValue;317}318 319ConstantExpr::ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,320                           bool IsImmediateInvocation)321    : FullExpr(ConstantExprClass, SubExpr) {322  ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);323  ConstantExprBits.APValueKind = APValue::None;324  ConstantExprBits.IsUnsigned = false;325  ConstantExprBits.BitWidth = 0;326  ConstantExprBits.HasCleanup = false;327  ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;328 329  if (StorageKind == ConstantResultStorageKind::APValue)330    ::new (getTrailingObjects<APValue>()) APValue();331}332 333ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,334                                   ConstantResultStorageKind StorageKind,335                                   bool IsImmediateInvocation) {336  assert(!isa<ConstantExpr>(E));337  AssertResultStorageKind(StorageKind);338 339  unsigned Size = totalSizeToAlloc<APValue, uint64_t>(340      StorageKind == ConstantResultStorageKind::APValue,341      StorageKind == ConstantResultStorageKind::Int64);342  void *Mem = Context.Allocate(Size, alignof(ConstantExpr));343  return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);344}345 346ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,347                                   const APValue &Result) {348  ConstantResultStorageKind StorageKind = getStorageKind(Result);349  ConstantExpr *Self = Create(Context, E, StorageKind);350  Self->SetResult(Result, Context);351  return Self;352}353 354ConstantExpr::ConstantExpr(EmptyShell Empty,355                           ConstantResultStorageKind StorageKind)356    : FullExpr(ConstantExprClass, Empty) {357  ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);358 359  if (StorageKind == ConstantResultStorageKind::APValue)360    ::new (getTrailingObjects<APValue>()) APValue();361}362 363ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,364                                        ConstantResultStorageKind StorageKind) {365  AssertResultStorageKind(StorageKind);366 367  unsigned Size = totalSizeToAlloc<APValue, uint64_t>(368      StorageKind == ConstantResultStorageKind::APValue,369      StorageKind == ConstantResultStorageKind::Int64);370  void *Mem = Context.Allocate(Size, alignof(ConstantExpr));371  return new (Mem) ConstantExpr(EmptyShell(), StorageKind);372}373 374void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {375  assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&376         "Invalid storage for this value kind");377  ConstantExprBits.APValueKind = Value.getKind();378  switch (getResultStorageKind()) {379  case ConstantResultStorageKind::None:380    return;381  case ConstantResultStorageKind::Int64:382    Int64Result() = *Value.getInt().getRawData();383    ConstantExprBits.BitWidth = Value.getInt().getBitWidth();384    ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();385    return;386  case ConstantResultStorageKind::APValue:387    if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {388      ConstantExprBits.HasCleanup = true;389      Context.addDestruction(&APValueResult());390    }391    APValueResult() = std::move(Value);392    return;393  }394  llvm_unreachable("Invalid ResultKind Bits");395}396 397llvm::APSInt ConstantExpr::getResultAsAPSInt() const {398  switch (getResultStorageKind()) {399  case ConstantResultStorageKind::APValue:400    return APValueResult().getInt();401  case ConstantResultStorageKind::Int64:402    return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),403                        ConstantExprBits.IsUnsigned);404  default:405    llvm_unreachable("invalid Accessor");406  }407}408 409APValue ConstantExpr::getAPValueResult() const {410 411  switch (getResultStorageKind()) {412  case ConstantResultStorageKind::APValue:413    return APValueResult();414  case ConstantResultStorageKind::Int64:415    return APValue(416        llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),417                     ConstantExprBits.IsUnsigned));418  case ConstantResultStorageKind::None:419    if (ConstantExprBits.APValueKind == APValue::Indeterminate)420      return APValue::IndeterminateValue();421    return APValue();422  }423  llvm_unreachable("invalid ResultKind");424}425 426DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,427                         bool RefersToEnclosingVariableOrCapture, QualType T,428                         ExprValueKind VK, SourceLocation L,429                         const DeclarationNameLoc &LocInfo,430                         NonOdrUseReason NOUR)431    : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {432  DeclRefExprBits.HasQualifier = false;433  DeclRefExprBits.HasTemplateKWAndArgsInfo = false;434  DeclRefExprBits.HasFoundDecl = false;435  DeclRefExprBits.HadMultipleCandidates = false;436  DeclRefExprBits.RefersToEnclosingVariableOrCapture =437      RefersToEnclosingVariableOrCapture;438  DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;439  DeclRefExprBits.NonOdrUseReason = NOUR;440  DeclRefExprBits.IsImmediateEscalating = false;441  DeclRefExprBits.Loc = L;442  setDependence(computeDependence(this, Ctx));443}444 445DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,446                         NestedNameSpecifierLoc QualifierLoc,447                         SourceLocation TemplateKWLoc, ValueDecl *D,448                         bool RefersToEnclosingVariableOrCapture,449                         const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,450                         const TemplateArgumentListInfo *TemplateArgs,451                         QualType T, ExprValueKind VK, NonOdrUseReason NOUR)452    : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),453      DNLoc(NameInfo.getInfo()) {454  DeclRefExprBits.Loc = NameInfo.getLoc();455  DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;456  if (QualifierLoc)457    new (getTrailingObjects<NestedNameSpecifierLoc>())458        NestedNameSpecifierLoc(QualifierLoc);459  DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;460  if (FoundD)461    *getTrailingObjects<NamedDecl *>() = FoundD;462  DeclRefExprBits.HasTemplateKWAndArgsInfo463    = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;464  DeclRefExprBits.RefersToEnclosingVariableOrCapture =465      RefersToEnclosingVariableOrCapture;466  DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;467  DeclRefExprBits.NonOdrUseReason = NOUR;468  if (TemplateArgs) {469    auto Deps = TemplateArgumentDependence::None;470    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(471        TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),472        Deps);473    assert(!(Deps & TemplateArgumentDependence::Dependent) &&474           "built a DeclRefExpr with dependent template args");475  } else if (TemplateKWLoc.isValid()) {476    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(477        TemplateKWLoc);478  }479  DeclRefExprBits.IsImmediateEscalating = false;480  DeclRefExprBits.HadMultipleCandidates = 0;481  setDependence(computeDependence(this, Ctx));482}483 484DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,485                                 NestedNameSpecifierLoc QualifierLoc,486                                 SourceLocation TemplateKWLoc, ValueDecl *D,487                                 bool RefersToEnclosingVariableOrCapture,488                                 SourceLocation NameLoc, QualType T,489                                 ExprValueKind VK, NamedDecl *FoundD,490                                 const TemplateArgumentListInfo *TemplateArgs,491                                 NonOdrUseReason NOUR) {492  return Create(Context, QualifierLoc, TemplateKWLoc, D,493                RefersToEnclosingVariableOrCapture,494                DeclarationNameInfo(D->getDeclName(), NameLoc),495                T, VK, FoundD, TemplateArgs, NOUR);496}497 498DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,499                                 NestedNameSpecifierLoc QualifierLoc,500                                 SourceLocation TemplateKWLoc, ValueDecl *D,501                                 bool RefersToEnclosingVariableOrCapture,502                                 const DeclarationNameInfo &NameInfo,503                                 QualType T, ExprValueKind VK,504                                 NamedDecl *FoundD,505                                 const TemplateArgumentListInfo *TemplateArgs,506                                 NonOdrUseReason NOUR) {507  // Filter out cases where the found Decl is the same as the value refenenced.508  if (D == FoundD)509    FoundD = nullptr;510 511  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();512  std::size_t Size =513      totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,514                       ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(515          QualifierLoc ? 1 : 0, FoundD ? 1 : 0,516          HasTemplateKWAndArgsInfo ? 1 : 0,517          TemplateArgs ? TemplateArgs->size() : 0);518 519  void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));520  return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,521                               RefersToEnclosingVariableOrCapture, NameInfo,522                               FoundD, TemplateArgs, T, VK, NOUR);523}524 525DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,526                                      bool HasQualifier,527                                      bool HasFoundDecl,528                                      bool HasTemplateKWAndArgsInfo,529                                      unsigned NumTemplateArgs) {530  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);531  std::size_t Size =532      totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,533                       ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(534          HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,535          NumTemplateArgs);536  void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));537  return new (Mem) DeclRefExpr(EmptyShell());538}539 540void DeclRefExpr::setDecl(ValueDecl *NewD) {541  D = NewD;542  if (getType()->isUndeducedType())543    setType(NewD->getType());544  setDependence(computeDependence(this, NewD->getASTContext()));545}546 547SourceLocation DeclRefExpr::getEndLoc() const {548  if (hasExplicitTemplateArgs())549    return getRAngleLoc();550  return getNameInfo().getEndLoc();551}552 553SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,554                                                   SourceLocation LParen,555                                                   SourceLocation RParen,556                                                   QualType ResultTy,557                                                   TypeSourceInfo *TSI)558    : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),559      OpLoc(OpLoc), LParen(LParen), RParen(RParen) {560  setTypeSourceInfo(TSI);561  setDependence(computeDependence(this));562}563 564SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,565                                                   QualType ResultTy)566    : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}567 568SYCLUniqueStableNameExpr *569SYCLUniqueStableNameExpr::Create(const ASTContext &Ctx, SourceLocation OpLoc,570                                 SourceLocation LParen, SourceLocation RParen,571                                 TypeSourceInfo *TSI) {572  QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());573  return new (Ctx)574      SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);575}576 577SYCLUniqueStableNameExpr *578SYCLUniqueStableNameExpr::CreateEmpty(const ASTContext &Ctx) {579  QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());580  return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);581}582 583std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context) const {584  return SYCLUniqueStableNameExpr::ComputeName(Context,585                                               getTypeSourceInfo()->getType());586}587 588std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context,589                                                  QualType Ty) {590  auto MangleCallback = [](ASTContext &Ctx,591                           const NamedDecl *ND) -> UnsignedOrNone {592    if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))593      return RD->getDeviceLambdaManglingNumber();594    return std::nullopt;595  };596 597  std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(598      Context, Context.getDiagnostics(), MangleCallback)};599 600  std::string Buffer;601  Buffer.reserve(128);602  llvm::raw_string_ostream Out(Buffer);603  Ctx->mangleCanonicalTypeName(Ty, Out);604 605  return Buffer;606}607 608PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy,609                               PredefinedIdentKind IK, bool IsTransparent,610                               StringLiteral *SL)611    : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {612  PredefinedExprBits.Kind = llvm::to_underlying(IK);613  assert((getIdentKind() == IK) &&614         "IdentKind do not fit in PredefinedExprBitfields!");615  bool HasFunctionName = SL != nullptr;616  PredefinedExprBits.HasFunctionName = HasFunctionName;617  PredefinedExprBits.IsTransparent = IsTransparent;618  PredefinedExprBits.Loc = L;619  if (HasFunctionName)620    setFunctionName(SL);621  setDependence(computeDependence(this));622}623 624PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)625    : Expr(PredefinedExprClass, Empty) {626  PredefinedExprBits.HasFunctionName = HasFunctionName;627}628 629PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,630                                       QualType FNTy, PredefinedIdentKind IK,631                                       bool IsTransparent, StringLiteral *SL) {632  bool HasFunctionName = SL != nullptr;633  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),634                           alignof(PredefinedExpr));635  return new (Mem) PredefinedExpr(L, FNTy, IK, IsTransparent, SL);636}637 638PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,639                                            bool HasFunctionName) {640  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),641                           alignof(PredefinedExpr));642  return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);643}644 645StringRef PredefinedExpr::getIdentKindName(PredefinedIdentKind IK) {646  switch (IK) {647  case PredefinedIdentKind::Func:648    return "__func__";649  case PredefinedIdentKind::Function:650    return "__FUNCTION__";651  case PredefinedIdentKind::FuncDName:652    return "__FUNCDNAME__";653  case PredefinedIdentKind::LFunction:654    return "L__FUNCTION__";655  case PredefinedIdentKind::PrettyFunction:656    return "__PRETTY_FUNCTION__";657  case PredefinedIdentKind::FuncSig:658    return "__FUNCSIG__";659  case PredefinedIdentKind::LFuncSig:660    return "L__FUNCSIG__";661  case PredefinedIdentKind::PrettyFunctionNoVirtual:662    break;663  }664  llvm_unreachable("Unknown ident kind for PredefinedExpr");665}666 667// FIXME: Maybe this should use DeclPrinter with a special "print predefined668// expr" policy instead.669std::string PredefinedExpr::ComputeName(PredefinedIdentKind IK,670                                        const Decl *CurrentDecl,671                                        bool ForceElaboratedPrinting) {672  ASTContext &Context = CurrentDecl->getASTContext();673 674  if (IK == PredefinedIdentKind::FuncDName) {675    if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {676      std::unique_ptr<MangleContext> MC;677      MC.reset(Context.createMangleContext());678 679      if (MC->shouldMangleDeclName(ND)) {680        SmallString<256> Buffer;681        llvm::raw_svector_ostream Out(Buffer);682        GlobalDecl GD;683        if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))684          GD = GlobalDecl(CD, Ctor_Base);685        else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))686          GD = GlobalDecl(DD, Dtor_Base);687        else if (auto FD = dyn_cast<FunctionDecl>(ND)) {688          GD = FD->isReferenceableKernel() ? GlobalDecl(FD) : GlobalDecl(ND);689        } else690          GD = GlobalDecl(ND);691        MC->mangleName(GD, Out);692 693        if (!Buffer.empty() && Buffer.front() == '\01')694          return std::string(Buffer.substr(1));695        return std::string(Buffer);696      }697      return std::string(ND->getIdentifier()->getName());698    }699    return "";700  }701  if (isa<BlockDecl>(CurrentDecl)) {702    // For blocks we only emit something if it is enclosed in a function703    // For top-level block we'd like to include the name of variable, but we704    // don't have it at this point.705    auto DC = CurrentDecl->getDeclContext();706    if (DC->isFileContext())707      return "";708 709    SmallString<256> Buffer;710    llvm::raw_svector_ostream Out(Buffer);711    if (auto *DCBlock = dyn_cast<BlockDecl>(DC))712      // For nested blocks, propagate up to the parent.713      Out << ComputeName(IK, DCBlock);714    else if (auto *DCDecl = dyn_cast<Decl>(DC))715      Out << ComputeName(IK, DCDecl) << "_block_invoke";716    return std::string(Out.str());717  }718  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {719    const auto &LO = Context.getLangOpts();720    bool IsFuncOrFunctionInNonMSVCCompatEnv =721        ((IK == PredefinedIdentKind::Func ||722          IK == PredefinedIdentKind ::Function) &&723         !LO.MSVCCompat);724    bool IsLFunctionInMSVCCommpatEnv =725        IK == PredefinedIdentKind::LFunction && LO.MSVCCompat;726    bool IsFuncOrFunctionOrLFunctionOrFuncDName =727        IK != PredefinedIdentKind::PrettyFunction &&728        IK != PredefinedIdentKind::PrettyFunctionNoVirtual &&729        IK != PredefinedIdentKind::FuncSig &&730        IK != PredefinedIdentKind::LFuncSig;731    if ((ForceElaboratedPrinting &&732         (IsFuncOrFunctionInNonMSVCCompatEnv || IsLFunctionInMSVCCommpatEnv)) ||733        (!ForceElaboratedPrinting && IsFuncOrFunctionOrLFunctionOrFuncDName))734      return FD->getNameAsString();735 736    SmallString<256> Name;737    llvm::raw_svector_ostream Out(Name);738 739    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {740      if (MD->isVirtual() && IK != PredefinedIdentKind::PrettyFunctionNoVirtual)741        Out << "virtual ";742      if (MD->isStatic() && !ForceElaboratedPrinting)743        Out << "static ";744    }745 746    class PrettyCallbacks final : public PrintingCallbacks {747    public:748      PrettyCallbacks(const LangOptions &LO) : LO(LO) {}749      std::string remapPath(StringRef Path) const override {750        SmallString<128> p(Path);751        LO.remapPathPrefix(p);752        return std::string(p);753      }754 755    private:756      const LangOptions &LO;757    };758    PrintingPolicy Policy(Context.getLangOpts());759    PrettyCallbacks PrettyCB(Context.getLangOpts());760    Policy.Callbacks = &PrettyCB;761    if (IK == PredefinedIdentKind::Function && ForceElaboratedPrinting)762      Policy.SuppressTagKeyword = !LO.MSVCCompat;763    std::string Proto;764    llvm::raw_string_ostream POut(Proto);765 766    const FunctionDecl *Decl = FD;767    if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())768      Decl = Pattern;769 770    // Bail out if the type of the function has not been set yet.771    // This can notably happen in the trailing return type of a lambda772    // expression.773    const Type *Ty = Decl->getType().getTypePtrOrNull();774    if (!Ty)775      return "";776 777    const FunctionType *AFT = Ty->getAs<FunctionType>();778    const FunctionProtoType *FT = nullptr;779    if (FD->hasWrittenPrototype())780      FT = dyn_cast<FunctionProtoType>(AFT);781 782    if (IK == PredefinedIdentKind::FuncSig ||783        IK == PredefinedIdentKind::LFuncSig) {784      switch (AFT->getCallConv()) {785      case CC_C: POut << "__cdecl "; break;786      case CC_X86StdCall: POut << "__stdcall "; break;787      case CC_X86FastCall: POut << "__fastcall "; break;788      case CC_X86ThisCall: POut << "__thiscall "; break;789      case CC_X86VectorCall: POut << "__vectorcall "; break;790      case CC_X86RegCall: POut << "__regcall "; break;791      // Only bother printing the conventions that MSVC knows about.792      default: break;793      }794    }795 796    FD->printQualifiedName(POut, Policy);797 798    if (IK == PredefinedIdentKind::Function) {799      Out << Proto;800      return std::string(Name);801    }802 803    POut << "(";804    if (FT) {805      for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {806        if (i) POut << ", ";807        POut << Decl->getParamDecl(i)->getType().stream(Policy);808      }809 810      if (FT->isVariadic()) {811        if (FD->getNumParams()) POut << ", ";812        POut << "...";813      } else if ((IK == PredefinedIdentKind::FuncSig ||814                  IK == PredefinedIdentKind::LFuncSig ||815                  !Context.getLangOpts().CPlusPlus) &&816                 !Decl->getNumParams()) {817        POut << "void";818      }819    }820    POut << ")";821 822    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {823      assert(FT && "We must have a written prototype in this case.");824      if (FT->isConst())825        POut << " const";826      if (FT->isVolatile())827        POut << " volatile";828      RefQualifierKind Ref = MD->getRefQualifier();829      if (Ref == RQ_LValue)830        POut << " &";831      else if (Ref == RQ_RValue)832        POut << " &&";833    }834 835    typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;836    SpecsTy Specs;837    const DeclContext *Ctx = FD->getDeclContext();838    while (isa_and_nonnull<NamedDecl>(Ctx)) {839      const ClassTemplateSpecializationDecl *Spec840                               = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);841      if (Spec && !Spec->isExplicitSpecialization())842        Specs.push_back(Spec);843      Ctx = Ctx->getParent();844    }845 846    std::string TemplateParams;847    llvm::raw_string_ostream TOut(TemplateParams);848    for (const ClassTemplateSpecializationDecl *D : llvm::reverse(Specs)) {849      const TemplateParameterList *Params =850          D->getSpecializedTemplate()->getTemplateParameters();851      const TemplateArgumentList &Args = D->getTemplateArgs();852      assert(Params->size() == Args.size());853      for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {854        StringRef Param = Params->getParam(i)->getName();855        if (Param.empty()) continue;856        TOut << Param << " = ";857        Args.get(i).print(Policy, TOut,858                          TemplateParameterList::shouldIncludeTypeForArgument(859                              Policy, Params, i));860        TOut << ", ";861      }862    }863 864    FunctionTemplateSpecializationInfo *FSI865                                          = FD->getTemplateSpecializationInfo();866    if (FSI && !FSI->isExplicitSpecialization()) {867      const TemplateParameterList* Params868                                  = FSI->getTemplate()->getTemplateParameters();869      const TemplateArgumentList* Args = FSI->TemplateArguments;870      assert(Params->size() == Args->size());871      for (unsigned i = 0, e = Params->size(); i != e; ++i) {872        StringRef Param = Params->getParam(i)->getName();873        if (Param.empty()) continue;874        TOut << Param << " = ";875        Args->get(i).print(Policy, TOut, /*IncludeType*/ true);876        TOut << ", ";877      }878    }879 880    if (!TemplateParams.empty()) {881      // remove the trailing comma and space882      TemplateParams.resize(TemplateParams.size() - 2);883      POut << " [" << TemplateParams << "]";884    }885 886    // Print "auto" for all deduced return types. This includes C++1y return887    // type deduction and lambdas. For trailing return types resolve the888    // decltype expression. Otherwise print the real type when this is889    // not a constructor or destructor.890    if (isLambdaMethod(FD))891      Proto = "auto " + Proto;892    else if (FT && FT->getReturnType()->getAs<DecltypeType>())893      FT->getReturnType()894          ->getAs<DecltypeType>()895          ->getUnderlyingType()896          .getAsStringInternal(Proto, Policy);897    else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))898      AFT->getReturnType().getAsStringInternal(Proto, Policy);899 900    Out << Proto;901 902    return std::string(Name);903  }904  if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {905    for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())906      // Skip to its enclosing function or method, but not its enclosing907      // CapturedDecl.908      if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {909        const Decl *D = Decl::castFromDeclContext(DC);910        return ComputeName(IK, D);911      }912    llvm_unreachable("CapturedDecl not inside a function or method");913  }914  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {915    SmallString<256> Name;916    llvm::raw_svector_ostream Out(Name);917    Out << (MD->isInstanceMethod() ? '-' : '+');918    Out << '[';919 920    // For incorrect code, there might not be an ObjCInterfaceDecl.  Do921    // a null check to avoid a crash.922    if (const ObjCInterfaceDecl *ID = MD->getClassInterface())923      Out << *ID;924 925    if (const ObjCCategoryImplDecl *CID =926        dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))927      Out << '(' << *CID << ')';928 929    Out <<  ' ';930    MD->getSelector().print(Out);931    Out <<  ']';932 933    return std::string(Name);934  }935  if (isa<TranslationUnitDecl>(CurrentDecl) &&936      IK == PredefinedIdentKind::PrettyFunction) {937    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.938    return "top level";939  }940  return "";941}942 943void APNumericStorage::setIntValue(const ASTContext &C,944                                   const llvm::APInt &Val) {945  if (hasAllocation())946    C.Deallocate(pVal);947 948  BitWidth = Val.getBitWidth();949  unsigned NumWords = Val.getNumWords();950  const uint64_t* Words = Val.getRawData();951  if (NumWords > 1) {952    pVal = new (C) uint64_t[NumWords];953    std::copy(Words, Words + NumWords, pVal);954  } else if (NumWords == 1)955    VAL = Words[0];956  else957    VAL = 0;958}959 960IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,961                               QualType type, SourceLocation l)962    : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {963  assert(type->isIntegerType() && "Illegal type in IntegerLiteral");964  assert(V.getBitWidth() == C.getIntWidth(type) &&965         "Integer type is not the correct size for constant.");966  setValue(C, V);967  setDependence(ExprDependence::None);968}969 970IntegerLiteral *971IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,972                       QualType type, SourceLocation l) {973  return new (C) IntegerLiteral(C, V, type, l);974}975 976IntegerLiteral *977IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {978  return new (C) IntegerLiteral(Empty);979}980 981FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,982                                     QualType type, SourceLocation l,983                                     unsigned Scale)984    : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),985      Scale(Scale) {986  assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");987  assert(V.getBitWidth() == C.getTypeInfo(type).Width &&988         "Fixed point type is not the correct size for constant.");989  setValue(C, V);990  setDependence(ExprDependence::None);991}992 993FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,994                                                       const llvm::APInt &V,995                                                       QualType type,996                                                       SourceLocation l,997                                                       unsigned Scale) {998  return new (C) FixedPointLiteral(C, V, type, l, Scale);999}1000 1001FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C,1002                                             EmptyShell Empty) {1003  return new (C) FixedPointLiteral(Empty);1004}1005 1006std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {1007  // Currently the longest decimal number that can be printed is the max for an1008  // unsigned long _Accum: 4294967295.999999999767169356346130371093751009  // which is 43 characters.1010  SmallString<64> S;1011  FixedPointValueToString(1012      S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);1013  return std::string(S);1014}1015 1016void CharacterLiteral::print(unsigned Val, CharacterLiteralKind Kind,1017                             raw_ostream &OS) {1018  switch (Kind) {1019  case CharacterLiteralKind::Ascii:1020    break; // no prefix.1021  case CharacterLiteralKind::Wide:1022    OS << 'L';1023    break;1024  case CharacterLiteralKind::UTF8:1025    OS << "u8";1026    break;1027  case CharacterLiteralKind::UTF16:1028    OS << 'u';1029    break;1030  case CharacterLiteralKind::UTF32:1031    OS << 'U';1032    break;1033  }1034 1035  StringRef Escaped = escapeCStyle<EscapeChar::Single>(Val);1036  if (!Escaped.empty()) {1037    OS << "'" << Escaped << "'";1038  } else {1039    // A character literal might be sign-extended, which1040    // would result in an invalid \U escape sequence.1041    // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'1042    // are not correctly handled.1043    if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteralKind::Ascii)1044      Val &= 0xFFu;1045    if (Val < 256 && isPrintable((unsigned char)Val))1046      OS << "'" << (char)Val << "'";1047    else if (Val < 256)1048      OS << "'\\x" << llvm::format("%02x", Val) << "'";1049    else if (Val <= 0xFFFF)1050      OS << "'\\u" << llvm::format("%04x", Val) << "'";1051    else1052      OS << "'\\U" << llvm::format("%08x", Val) << "'";1053  }1054}1055 1056FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,1057                                 bool isexact, QualType Type, SourceLocation L)1058    : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {1059  setSemantics(V.getSemantics());1060  FloatingLiteralBits.IsExact = isexact;1061  setValue(C, V);1062  setDependence(ExprDependence::None);1063}1064 1065FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)1066  : Expr(FloatingLiteralClass, Empty) {1067  setRawSemantics(llvm::APFloatBase::S_IEEEhalf);1068  FloatingLiteralBits.IsExact = false;1069}1070 1071FloatingLiteral *1072FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,1073                        bool isexact, QualType Type, SourceLocation L) {1074  return new (C) FloatingLiteral(C, V, isexact, Type, L);1075}1076 1077FloatingLiteral *1078FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {1079  return new (C) FloatingLiteral(C, Empty);1080}1081 1082/// getValueAsApproximateDouble - This returns the value as an inaccurate1083/// double.  Note that this may cause loss of precision, but is useful for1084/// debugging dumps, etc.1085double FloatingLiteral::getValueAsApproximateDouble() const {1086  llvm::APFloat V = getValue();1087  bool ignored;1088  V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,1089            &ignored);1090  return V.convertToDouble();1091}1092 1093unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,1094                                         StringLiteralKind SK) {1095  unsigned CharByteWidth = 0;1096  switch (SK) {1097  case StringLiteralKind::Ordinary:1098  case StringLiteralKind::UTF8:1099  case StringLiteralKind::Binary:1100    CharByteWidth = Target.getCharWidth();1101    break;1102  case StringLiteralKind::Wide:1103    CharByteWidth = Target.getWCharWidth();1104    break;1105  case StringLiteralKind::UTF16:1106    CharByteWidth = Target.getChar16Width();1107    break;1108  case StringLiteralKind::UTF32:1109    CharByteWidth = Target.getChar32Width();1110    break;1111  case StringLiteralKind::Unevaluated:1112    return sizeof(char); // Host;1113  }1114  assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");1115  CharByteWidth /= 8;1116  assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&1117         "The only supported character byte widths are 1,2 and 4!");1118  return CharByteWidth;1119}1120 1121StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,1122                             StringLiteralKind Kind, bool Pascal, QualType Ty,1123                             ArrayRef<SourceLocation> Locs)1124    : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {1125 1126  unsigned Length = Str.size();1127 1128  StringLiteralBits.Kind = llvm::to_underlying(Kind);1129  StringLiteralBits.NumConcatenated = Locs.size();1130 1131  if (Kind != StringLiteralKind::Unevaluated) {1132    assert(Ctx.getAsConstantArrayType(Ty) &&1133           "StringLiteral must be of constant array type!");1134    unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);1135    unsigned ByteLength = Str.size();1136    assert((ByteLength % CharByteWidth == 0) &&1137           "The size of the data must be a multiple of CharByteWidth!");1138 1139    // Avoid the expensive division. The compiler should be able to figure it1140    // out by itself. However as of clang 7, even with the appropriate1141    // llvm_unreachable added just here, it is not able to do so.1142    switch (CharByteWidth) {1143    case 1:1144      Length = ByteLength;1145      break;1146    case 2:1147      Length = ByteLength / 2;1148      break;1149    case 4:1150      Length = ByteLength / 4;1151      break;1152    default:1153      llvm_unreachable("Unsupported character width!");1154    }1155 1156    StringLiteralBits.CharByteWidth = CharByteWidth;1157    StringLiteralBits.IsPascal = Pascal;1158  } else {1159    assert(!Pascal && "Can't make an unevaluated Pascal string");1160    StringLiteralBits.CharByteWidth = 1;1161    StringLiteralBits.IsPascal = false;1162  }1163 1164  *getTrailingObjects<unsigned>() = Length;1165 1166  // Initialize the trailing array of SourceLocation.1167  // This is safe since SourceLocation is POD-like.1168  llvm::copy(Locs, getTrailingObjects<SourceLocation>());1169 1170  // Initialize the trailing array of char holding the string data.1171  llvm::copy(Str, getTrailingObjects<char>());1172 1173  setDependence(ExprDependence::None);1174}1175 1176StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,1177                             unsigned Length, unsigned CharByteWidth)1178    : Expr(StringLiteralClass, Empty) {1179  StringLiteralBits.CharByteWidth = CharByteWidth;1180  StringLiteralBits.NumConcatenated = NumConcatenated;1181  *getTrailingObjects<unsigned>() = Length;1182}1183 1184StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,1185                                     StringLiteralKind Kind, bool Pascal,1186                                     QualType Ty,1187                                     ArrayRef<SourceLocation> Locs) {1188  void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(1189                               1, Locs.size(), Str.size()),1190                           alignof(StringLiteral));1191  return new (Mem) StringLiteral(Ctx, Str, Kind, Pascal, Ty, Locs);1192}1193 1194StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,1195                                          unsigned NumConcatenated,1196                                          unsigned Length,1197                                          unsigned CharByteWidth) {1198  void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(1199                               1, NumConcatenated, Length * CharByteWidth),1200                           alignof(StringLiteral));1201  return new (Mem)1202      StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);1203}1204 1205void StringLiteral::outputString(raw_ostream &OS) const {1206  switch (getKind()) {1207  case StringLiteralKind::Unevaluated:1208  case StringLiteralKind::Ordinary:1209  case StringLiteralKind::Binary:1210    break; // no prefix.1211  case StringLiteralKind::Wide:1212    OS << 'L';1213    break;1214  case StringLiteralKind::UTF8:1215    OS << "u8";1216    break;1217  case StringLiteralKind::UTF16:1218    OS << 'u';1219    break;1220  case StringLiteralKind::UTF32:1221    OS << 'U';1222    break;1223  }1224  OS << '"';1225  static const char Hex[] = "0123456789ABCDEF";1226 1227  unsigned LastSlashX = getLength();1228  for (unsigned I = 0, N = getLength(); I != N; ++I) {1229    uint32_t Char = getCodeUnit(I);1230    StringRef Escaped = escapeCStyle<EscapeChar::Double>(Char);1231    if (Escaped.empty()) {1232      // FIXME: Convert UTF-8 back to codepoints before rendering.1233 1234      // Convert UTF-16 surrogate pairs back to codepoints before rendering.1235      // Leave invalid surrogates alone; we'll use \x for those.1236      if (getKind() == StringLiteralKind::UTF16 && I != N - 1 &&1237          Char >= 0xd800 && Char <= 0xdbff) {1238        uint32_t Trail = getCodeUnit(I + 1);1239        if (Trail >= 0xdc00 && Trail <= 0xdfff) {1240          Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);1241          ++I;1242        }1243      }1244 1245      if (Char > 0xff) {1246        // If this is a wide string, output characters over 0xff using \x1247        // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a1248        // codepoint: use \x escapes for invalid codepoints.1249        if (getKind() == StringLiteralKind::Wide ||1250            (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {1251          // FIXME: Is this the best way to print wchar_t?1252          OS << "\\x";1253          int Shift = 28;1254          while ((Char >> Shift) == 0)1255            Shift -= 4;1256          for (/**/; Shift >= 0; Shift -= 4)1257            OS << Hex[(Char >> Shift) & 15];1258          LastSlashX = I;1259          continue;1260        }1261 1262        if (Char > 0xffff)1263          OS << "\\U00"1264             << Hex[(Char >> 20) & 15]1265             << Hex[(Char >> 16) & 15];1266        else1267          OS << "\\u";1268        OS << Hex[(Char >> 12) & 15]1269           << Hex[(Char >>  8) & 15]1270           << Hex[(Char >>  4) & 15]1271           << Hex[(Char >>  0) & 15];1272        continue;1273      }1274 1275      // If we used \x... for the previous character, and this character is a1276      // hexadecimal digit, prevent it being slurped as part of the \x.1277      if (LastSlashX + 1 == I) {1278        switch (Char) {1279          case '0': case '1': case '2': case '3': case '4':1280          case '5': case '6': case '7': case '8': case '9':1281          case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':1282          case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':1283            OS << "\"\"";1284        }1285      }1286 1287      assert(Char <= 0xff &&1288             "Characters above 0xff should already have been handled.");1289 1290      if (isPrintable(Char))1291        OS << (char)Char;1292      else  // Output anything hard as an octal escape.1293        OS << '\\'1294           << (char)('0' + ((Char >> 6) & 7))1295           << (char)('0' + ((Char >> 3) & 7))1296           << (char)('0' + ((Char >> 0) & 7));1297    } else {1298      // Handle some common non-printable cases to make dumps prettier.1299      OS << Escaped;1300    }1301  }1302  OS << '"';1303}1304 1305/// getLocationOfByte - Return a source location that points to the specified1306/// byte of this string literal.1307///1308/// Strings are amazingly complex.  They can be formed from multiple tokens and1309/// can have escape sequences in them in addition to the usual trigraph and1310/// escaped newline business.  This routine handles this complexity.1311///1312/// The *StartToken sets the first token to be searched in this function and1313/// the *StartTokenByteOffset is the byte offset of the first token. Before1314/// returning, it updates the *StartToken to the TokNo of the token being found1315/// and sets *StartTokenByteOffset to the byte offset of the token in the1316/// string.1317/// Using these two parameters can reduce the time complexity from O(n^2) to1318/// O(n) if one wants to get the location of byte for all the tokens in a1319/// string.1320///1321SourceLocation1322StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,1323                                 const LangOptions &Features,1324                                 const TargetInfo &Target, unsigned *StartToken,1325                                 unsigned *StartTokenByteOffset) const {1326  // No source location of bytes for binary literals since they don't come from1327  // source.1328  if (getKind() == StringLiteralKind::Binary)1329    return getStrTokenLoc(0);1330 1331  assert((getKind() == StringLiteralKind::Ordinary ||1332          getKind() == StringLiteralKind::UTF8 ||1333          getKind() == StringLiteralKind::Unevaluated) &&1334         "Only narrow string literals are currently supported");1335 1336  // Loop over all of the tokens in this string until we find the one that1337  // contains the byte we're looking for.1338  unsigned TokNo = 0;1339  unsigned StringOffset = 0;1340  if (StartToken)1341    TokNo = *StartToken;1342  if (StartTokenByteOffset) {1343    StringOffset = *StartTokenByteOffset;1344    ByteNo -= StringOffset;1345  }1346  while (true) {1347    assert(TokNo < getNumConcatenated() && "Invalid byte number!");1348    SourceLocation StrTokLoc = getStrTokenLoc(TokNo);1349 1350    // Get the spelling of the string so that we can get the data that makes up1351    // the string literal, not the identifier for the macro it is potentially1352    // expanded through.1353    SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);1354 1355    // Re-lex the token to get its length and original spelling.1356    FileIDAndOffset LocInfo = SM.getDecomposedLoc(StrTokSpellingLoc);1357    bool Invalid = false;1358    StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);1359    if (Invalid) {1360      if (StartTokenByteOffset != nullptr)1361        *StartTokenByteOffset = StringOffset;1362      if (StartToken != nullptr)1363        *StartToken = TokNo;1364      return StrTokSpellingLoc;1365    }1366 1367    const char *StrData = Buffer.data()+LocInfo.second;1368 1369    // Create a lexer starting at the beginning of this token.1370    Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,1371                   Buffer.begin(), StrData, Buffer.end());1372    Token TheTok;1373    TheLexer.LexFromRawLexer(TheTok);1374 1375    // Use the StringLiteralParser to compute the length of the string in bytes.1376    StringLiteralParser SLP(TheTok, SM, Features, Target);1377    unsigned TokNumBytes = SLP.GetStringLength();1378 1379    // If the byte is in this token, return the location of the byte.1380    if (ByteNo < TokNumBytes ||1381        (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {1382      unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);1383 1384      // Now that we know the offset of the token in the spelling, use the1385      // preprocessor to get the offset in the original source.1386      if (StartTokenByteOffset != nullptr)1387        *StartTokenByteOffset = StringOffset;1388      if (StartToken != nullptr)1389        *StartToken = TokNo;1390      return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);1391    }1392 1393    // Move to the next string token.1394    StringOffset += TokNumBytes;1395    ++TokNo;1396    ByteNo -= TokNumBytes;1397  }1398}1399 1400/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it1401/// corresponds to, e.g. "sizeof" or "[pre]++".1402StringRef UnaryOperator::getOpcodeStr(Opcode Op) {1403  switch (Op) {1404#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;1405#include "clang/AST/OperationKinds.def"1406  }1407  llvm_unreachable("Unknown unary operator");1408}1409 1410UnaryOperatorKind1411UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {1412  switch (OO) {1413  default: llvm_unreachable("No unary operator for overloaded function");1414  case OO_PlusPlus:   return Postfix ? UO_PostInc : UO_PreInc;1415  case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;1416  case OO_Amp:        return UO_AddrOf;1417  case OO_Star:       return UO_Deref;1418  case OO_Plus:       return UO_Plus;1419  case OO_Minus:      return UO_Minus;1420  case OO_Tilde:      return UO_Not;1421  case OO_Exclaim:    return UO_LNot;1422  case OO_Coawait:    return UO_Coawait;1423  }1424}1425 1426OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {1427  switch (Opc) {1428  case UO_PostInc: case UO_PreInc: return OO_PlusPlus;1429  case UO_PostDec: case UO_PreDec: return OO_MinusMinus;1430  case UO_AddrOf: return OO_Amp;1431  case UO_Deref: return OO_Star;1432  case UO_Plus: return OO_Plus;1433  case UO_Minus: return OO_Minus;1434  case UO_Not: return OO_Tilde;1435  case UO_LNot: return OO_Exclaim;1436  case UO_Coawait: return OO_Coawait;1437  default: return OO_None;1438  }1439}1440 1441 1442//===----------------------------------------------------------------------===//1443// Postfix Operators.1444//===----------------------------------------------------------------------===//1445#ifndef NDEBUG1446static unsigned SizeOfCallExprInstance(Expr::StmtClass SC) {1447  switch (SC) {1448  case Expr::CallExprClass:1449    return sizeof(CallExpr);1450  case Expr::CXXOperatorCallExprClass:1451    return sizeof(CXXOperatorCallExpr);1452  case Expr::CXXMemberCallExprClass:1453    return sizeof(CXXMemberCallExpr);1454  case Expr::UserDefinedLiteralClass:1455    return sizeof(UserDefinedLiteral);1456  case Expr::CUDAKernelCallExprClass:1457    return sizeof(CUDAKernelCallExpr);1458  default:1459    llvm_unreachable("unexpected class deriving from CallExpr!");1460  }1461}1462#endif1463 1464// changing the size of SourceLocation, CallExpr, and1465// subclasses requires careful considerations1466static_assert(sizeof(SourceLocation) == 4 && sizeof(CXXOperatorCallExpr) <= 32,1467              "we assume CXXOperatorCallExpr is at most 32 bytes");1468 1469CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,1470                   ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,1471                   SourceLocation RParenLoc, FPOptionsOverride FPFeatures,1472                   unsigned MinNumArgs, ADLCallKind UsesADL)1473    : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {1474  NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);1475  unsigned NumPreArgs = PreArgs.size();1476  CallExprBits.NumPreArgs = NumPreArgs;1477  assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");1478  assert(SizeOfCallExprInstance(SC) <= OffsetToTrailingObjects &&1479         "This CallExpr subclass is too big or unsupported");1480 1481  CallExprBits.UsesADL = static_cast<bool>(UsesADL);1482 1483  setCallee(Fn);1484  for (unsigned I = 0; I != NumPreArgs; ++I)1485    setPreArg(I, PreArgs[I]);1486  for (unsigned I = 0; I != Args.size(); ++I)1487    setArg(I, Args[I]);1488  for (unsigned I = Args.size(); I != NumArgs; ++I)1489    setArg(I, nullptr);1490 1491  this->computeDependence();1492 1493  CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();1494  CallExprBits.IsCoroElideSafe = false;1495  CallExprBits.ExplicitObjectMemFunUsingMemberSyntax = false;1496  CallExprBits.HasTrailingSourceLoc = false;1497 1498  if (hasStoredFPFeatures())1499    setStoredFPFeatures(FPFeatures);1500}1501 1502CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,1503                   bool HasFPFeatures, EmptyShell Empty)1504    : Expr(SC, Empty), NumArgs(NumArgs) {1505  CallExprBits.NumPreArgs = NumPreArgs;1506  assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");1507  CallExprBits.HasFPFeatures = HasFPFeatures;1508  CallExprBits.IsCoroElideSafe = false;1509  CallExprBits.ExplicitObjectMemFunUsingMemberSyntax = false;1510  CallExprBits.HasTrailingSourceLoc = false;1511}1512 1513CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,1514                           ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,1515                           SourceLocation RParenLoc,1516                           FPOptionsOverride FPFeatures, unsigned MinNumArgs,1517                           ADLCallKind UsesADL) {1518  unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);1519  unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(1520      /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());1521  void *Mem = Ctx.Allocate(1522      sizeToAllocateForCallExprSubclass<CallExpr>(SizeOfTrailingObjects),1523      alignof(CallExpr));1524  CallExpr *E =1525      new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,1526                         RParenLoc, FPFeatures, MinNumArgs, UsesADL);1527  E->updateTrailingSourceLoc();1528  return E;1529}1530 1531CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,1532                                bool HasFPFeatures, EmptyShell Empty) {1533  unsigned SizeOfTrailingObjects =1534      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);1535  void *Mem = Ctx.Allocate(1536      sizeToAllocateForCallExprSubclass<CallExpr>(SizeOfTrailingObjects),1537      alignof(CallExpr));1538  return new (Mem)1539      CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);1540}1541 1542Decl *Expr::getReferencedDeclOfCallee() {1543 1544  // Optimize for the common case first1545  // (simple function or member function call)1546  // then try more exotic possibilities.1547  Expr *CEE = IgnoreImpCasts();1548 1549  if (auto *DRE = dyn_cast<DeclRefExpr>(CEE))1550    return DRE->getDecl();1551 1552  if (auto *ME = dyn_cast<MemberExpr>(CEE))1553    return ME->getMemberDecl();1554 1555  CEE = CEE->IgnoreParens();1556 1557  while (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE))1558    CEE = NTTP->getReplacement()->IgnoreParenImpCasts();1559 1560  // If we're calling a dereference, look at the pointer instead.1561  while (true) {1562    if (auto *BO = dyn_cast<BinaryOperator>(CEE)) {1563      if (BO->isPtrMemOp()) {1564        CEE = BO->getRHS()->IgnoreParenImpCasts();1565        continue;1566      }1567    } else if (auto *UO = dyn_cast<UnaryOperator>(CEE)) {1568      if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||1569          UO->getOpcode() == UO_Plus) {1570        CEE = UO->getSubExpr()->IgnoreParenImpCasts();1571        continue;1572      }1573    }1574    break;1575  }1576 1577  if (auto *DRE = dyn_cast<DeclRefExpr>(CEE))1578    return DRE->getDecl();1579  if (auto *ME = dyn_cast<MemberExpr>(CEE))1580    return ME->getMemberDecl();1581  if (auto *BE = dyn_cast<BlockExpr>(CEE))1582    return BE->getBlockDecl();1583 1584  return nullptr;1585}1586 1587/// If this is a call to a builtin, return the builtin ID. If not, return 0.1588unsigned CallExpr::getBuiltinCallee() const {1589  const auto *FDecl = getDirectCallee();1590  return FDecl ? FDecl->getBuiltinID() : 0;1591}1592 1593bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {1594  if (unsigned BI = getBuiltinCallee())1595    return Ctx.BuiltinInfo.isUnevaluated(BI);1596  return false;1597}1598 1599QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {1600  const Expr *Callee = getCallee();1601  QualType CalleeType = Callee->getType();1602  if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {1603    CalleeType = FnTypePtr->getPointeeType();1604  } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {1605    CalleeType = BPT->getPointeeType();1606  } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {1607    if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))1608      return Ctx.VoidTy;1609 1610    if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))1611      return Ctx.DependentTy;1612 1613    // This should never be overloaded and so should never return null.1614    CalleeType = Expr::findBoundMemberType(Callee);1615    assert(!CalleeType.isNull());1616  } else if (CalleeType->isRecordType()) {1617    // If the Callee is a record type, then it is a not-yet-resolved1618    // dependent call to the call operator of that type.1619    return Ctx.DependentTy;1620  } else if (CalleeType->isDependentType() ||1621             CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {1622    return Ctx.DependentTy;1623  }1624 1625  const FunctionType *FnType = CalleeType->castAs<FunctionType>();1626  return FnType->getReturnType();1627}1628 1629std::pair<const NamedDecl *, const WarnUnusedResultAttr *>1630Expr::getUnusedResultAttrImpl(const Decl *Callee, QualType ReturnType) {1631  // If the callee is marked nodiscard, return that attribute1632  if (Callee != nullptr)1633    if (const auto *A = Callee->getAttr<WarnUnusedResultAttr>())1634      return {nullptr, A};1635 1636  // If the return type is a struct, union, or enum that is marked nodiscard,1637  // then return the return type attribute.1638  if (const TagDecl *TD = ReturnType->getAsTagDecl())1639    if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())1640      return {TD, A};1641 1642  for (const auto *TD = ReturnType->getAs<TypedefType>(); TD;1643       TD = TD->desugar()->getAs<TypedefType>())1644    if (const auto *A = TD->getDecl()->getAttr<WarnUnusedResultAttr>())1645      return {TD->getDecl(), A};1646  return {nullptr, nullptr};1647}1648 1649OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,1650                                   SourceLocation OperatorLoc,1651                                   TypeSourceInfo *tsi,1652                                   ArrayRef<OffsetOfNode> comps,1653                                   ArrayRef<Expr*> exprs,1654                                   SourceLocation RParenLoc) {1655  void *Mem = C.Allocate(1656      totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));1657 1658  return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,1659                                RParenLoc);1660}1661 1662OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,1663                                        unsigned numComps, unsigned numExprs) {1664  void *Mem =1665      C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));1666  return new (Mem) OffsetOfExpr(numComps, numExprs);1667}1668 1669OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,1670                           SourceLocation OperatorLoc, TypeSourceInfo *tsi,1671                           ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,1672                           SourceLocation RParenLoc)1673    : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),1674      OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),1675      NumComps(comps.size()), NumExprs(exprs.size()) {1676  for (unsigned i = 0; i != comps.size(); ++i)1677    setComponent(i, comps[i]);1678  for (unsigned i = 0; i != exprs.size(); ++i)1679    setIndexExpr(i, exprs[i]);1680 1681  setDependence(computeDependence(this));1682}1683 1684IdentifierInfo *OffsetOfNode::getFieldName() const {1685  assert(getKind() == Field || getKind() == Identifier);1686  if (getKind() == Field)1687    return getField()->getIdentifier();1688 1689  return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);1690}1691 1692UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(1693    UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,1694    SourceLocation op, SourceLocation rp)1695    : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),1696      OpLoc(op), RParenLoc(rp) {1697  assert(ExprKind <= UETT_Last && "invalid enum value!");1698  UnaryExprOrTypeTraitExprBits.Kind = ExprKind;1699  assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&1700         "UnaryExprOrTypeTraitExprBits.Kind overflow!");1701  UnaryExprOrTypeTraitExprBits.IsType = false;1702  Argument.Ex = E;1703  setDependence(computeDependence(this));1704}1705 1706MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,1707                       NestedNameSpecifierLoc QualifierLoc,1708                       SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,1709                       DeclAccessPair FoundDecl,1710                       const DeclarationNameInfo &NameInfo,1711                       const TemplateArgumentListInfo *TemplateArgs, QualType T,1712                       ExprValueKind VK, ExprObjectKind OK,1713                       NonOdrUseReason NOUR)1714    : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),1715      MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {1716  assert(!NameInfo.getName() ||1717         MemberDecl->getDeclName() == NameInfo.getName());1718  MemberExprBits.IsArrow = IsArrow;1719  MemberExprBits.HasQualifier = QualifierLoc.hasQualifier();1720  MemberExprBits.HasFoundDecl =1721      FoundDecl.getDecl() != MemberDecl ||1722      FoundDecl.getAccess() != MemberDecl->getAccess();1723  MemberExprBits.HasTemplateKWAndArgsInfo =1724      TemplateArgs || TemplateKWLoc.isValid();1725  MemberExprBits.HadMultipleCandidates = false;1726  MemberExprBits.NonOdrUseReason = NOUR;1727  MemberExprBits.OperatorLoc = OperatorLoc;1728 1729  if (hasQualifier())1730    new (getTrailingObjects<NestedNameSpecifierLoc>())1731        NestedNameSpecifierLoc(QualifierLoc);1732  if (hasFoundDecl())1733    *getTrailingObjects<DeclAccessPair>() = FoundDecl;1734  if (TemplateArgs) {1735    auto Deps = TemplateArgumentDependence::None;1736    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(1737        TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),1738        Deps);1739  } else if (TemplateKWLoc.isValid()) {1740    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(1741        TemplateKWLoc);1742  }1743  setDependence(computeDependence(this));1744}1745 1746MemberExpr *MemberExpr::Create(1747    const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,1748    NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,1749    ValueDecl *MemberDecl, DeclAccessPair FoundDecl,1750    DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,1751    QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {1752  bool HasQualifier = QualifierLoc.hasQualifier();1753  bool HasFoundDecl = FoundDecl.getDecl() != MemberDecl ||1754                      FoundDecl.getAccess() != MemberDecl->getAccess();1755  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();1756  std::size_t Size =1757      totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair,1758                       ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(1759          HasQualifier, HasFoundDecl, HasTemplateKWAndArgsInfo,1760          TemplateArgs ? TemplateArgs->size() : 0);1761 1762  void *Mem = C.Allocate(Size, alignof(MemberExpr));1763  return new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, QualifierLoc,1764                              TemplateKWLoc, MemberDecl, FoundDecl, NameInfo,1765                              TemplateArgs, T, VK, OK, NOUR);1766}1767 1768MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,1769                                    bool HasQualifier, bool HasFoundDecl,1770                                    bool HasTemplateKWAndArgsInfo,1771                                    unsigned NumTemplateArgs) {1772  assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&1773         "template args but no template arg info?");1774  std::size_t Size =1775      totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair,1776                       ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(1777          HasQualifier, HasFoundDecl, HasTemplateKWAndArgsInfo,1778          NumTemplateArgs);1779  void *Mem = Context.Allocate(Size, alignof(MemberExpr));1780  return new (Mem) MemberExpr(EmptyShell());1781}1782 1783void MemberExpr::setMemberDecl(ValueDecl *NewD) {1784  MemberDecl = NewD;1785  if (getType()->isUndeducedType())1786    setType(NewD->getType());1787  setDependence(computeDependence(this));1788}1789 1790SourceLocation MemberExpr::getBeginLoc() const {1791  if (isImplicitAccess()) {1792    if (hasQualifier())1793      return getQualifierLoc().getBeginLoc();1794    return MemberLoc;1795  }1796 1797  // FIXME: We don't want this to happen. Rather, we should be able to1798  // detect all kinds of implicit accesses more cleanly.1799  SourceLocation BaseStartLoc = getBase()->getBeginLoc();1800  if (BaseStartLoc.isValid())1801    return BaseStartLoc;1802  return MemberLoc;1803}1804SourceLocation MemberExpr::getEndLoc() const {1805  SourceLocation EndLoc = getMemberNameInfo().getEndLoc();1806  if (hasExplicitTemplateArgs())1807    EndLoc = getRAngleLoc();1808  else if (EndLoc.isInvalid())1809    EndLoc = getBase()->getEndLoc();1810  return EndLoc;1811}1812 1813bool CastExpr::CastConsistency() const {1814  switch (getCastKind()) {1815  case CK_DerivedToBase:1816  case CK_UncheckedDerivedToBase:1817  case CK_DerivedToBaseMemberPointer:1818  case CK_BaseToDerived:1819  case CK_BaseToDerivedMemberPointer:1820    assert(!path_empty() && "Cast kind should have a base path!");1821    break;1822 1823  case CK_CPointerToObjCPointerCast:1824    assert(getType()->isObjCObjectPointerType());1825    assert(getSubExpr()->getType()->isPointerType());1826    goto CheckNoBasePath;1827 1828  case CK_BlockPointerToObjCPointerCast:1829    assert(getType()->isObjCObjectPointerType());1830    assert(getSubExpr()->getType()->isBlockPointerType());1831    goto CheckNoBasePath;1832 1833  case CK_ReinterpretMemberPointer:1834    assert(getType()->isMemberPointerType());1835    assert(getSubExpr()->getType()->isMemberPointerType());1836    goto CheckNoBasePath;1837 1838  case CK_BitCast:1839    // Arbitrary casts to C pointer types count as bitcasts.1840    // Otherwise, we should only have block and ObjC pointer casts1841    // here if they stay within the type kind.1842    if (!getType()->isPointerType()) {1843      assert(getType()->isObjCObjectPointerType() ==1844             getSubExpr()->getType()->isObjCObjectPointerType());1845      assert(getType()->isBlockPointerType() ==1846             getSubExpr()->getType()->isBlockPointerType());1847    }1848    goto CheckNoBasePath;1849 1850  case CK_AnyPointerToBlockPointerCast:1851    assert(getType()->isBlockPointerType());1852    assert(getSubExpr()->getType()->isAnyPointerType() &&1853           !getSubExpr()->getType()->isBlockPointerType());1854    goto CheckNoBasePath;1855 1856  case CK_CopyAndAutoreleaseBlockObject:1857    assert(getType()->isBlockPointerType());1858    assert(getSubExpr()->getType()->isBlockPointerType());1859    goto CheckNoBasePath;1860 1861  case CK_FunctionToPointerDecay:1862    assert(getType()->isPointerType());1863    assert(getSubExpr()->getType()->isFunctionType());1864    goto CheckNoBasePath;1865 1866  case CK_AddressSpaceConversion: {1867    auto Ty = getType();1868    auto SETy = getSubExpr()->getType();1869    assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));1870    if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {1871      Ty = Ty->getPointeeType();1872      SETy = SETy->getPointeeType();1873    }1874    assert((Ty->isDependentType() || SETy->isDependentType()) ||1875           (!Ty.isNull() && !SETy.isNull() &&1876            Ty.getAddressSpace() != SETy.getAddressSpace()));1877    goto CheckNoBasePath;1878  }1879  // These should not have an inheritance path.1880  case CK_Dynamic:1881  case CK_ToUnion:1882  case CK_ArrayToPointerDecay:1883  case CK_NullToMemberPointer:1884  case CK_NullToPointer:1885  case CK_ConstructorConversion:1886  case CK_IntegralToPointer:1887  case CK_PointerToIntegral:1888  case CK_ToVoid:1889  case CK_VectorSplat:1890  case CK_IntegralCast:1891  case CK_BooleanToSignedIntegral:1892  case CK_IntegralToFloating:1893  case CK_FloatingToIntegral:1894  case CK_FloatingCast:1895  case CK_ObjCObjectLValueCast:1896  case CK_FloatingRealToComplex:1897  case CK_FloatingComplexToReal:1898  case CK_FloatingComplexCast:1899  case CK_FloatingComplexToIntegralComplex:1900  case CK_IntegralRealToComplex:1901  case CK_IntegralComplexToReal:1902  case CK_IntegralComplexCast:1903  case CK_IntegralComplexToFloatingComplex:1904  case CK_ARCProduceObject:1905  case CK_ARCConsumeObject:1906  case CK_ARCReclaimReturnedObject:1907  case CK_ARCExtendBlockObject:1908  case CK_ZeroToOCLOpaqueType:1909  case CK_IntToOCLSampler:1910  case CK_FloatingToFixedPoint:1911  case CK_FixedPointToFloating:1912  case CK_FixedPointCast:1913  case CK_FixedPointToIntegral:1914  case CK_IntegralToFixedPoint:1915  case CK_MatrixCast:1916    assert(!getType()->isBooleanType() && "unheralded conversion to bool");1917    goto CheckNoBasePath;1918 1919  case CK_Dependent:1920  case CK_LValueToRValue:1921  case CK_NoOp:1922  case CK_AtomicToNonAtomic:1923  case CK_NonAtomicToAtomic:1924  case CK_PointerToBoolean:1925  case CK_IntegralToBoolean:1926  case CK_FloatingToBoolean:1927  case CK_MemberPointerToBoolean:1928  case CK_FloatingComplexToBoolean:1929  case CK_IntegralComplexToBoolean:1930  case CK_LValueBitCast:            // -> bool&1931  case CK_LValueToRValueBitCast:1932  case CK_UserDefinedConversion:    // operator bool()1933  case CK_BuiltinFnToFnPtr:1934  case CK_FixedPointToBoolean:1935  case CK_HLSLArrayRValue:1936  case CK_HLSLVectorTruncation:1937  case CK_HLSLElementwiseCast:1938  case CK_HLSLAggregateSplatCast:1939  CheckNoBasePath:1940    assert(path_empty() && "Cast kind should not have a base path!");1941    break;1942  }1943  return true;1944}1945 1946const char *CastExpr::getCastKindName(CastKind CK) {1947  switch (CK) {1948#define CAST_OPERATION(Name) case CK_##Name: return #Name;1949#include "clang/AST/OperationKinds.def"1950  }1951  llvm_unreachable("Unhandled cast kind!");1952}1953 1954namespace {1955// Skip over implicit nodes produced as part of semantic analysis.1956// Designed for use with IgnoreExprNodes.1957static Expr *ignoreImplicitSemaNodes(Expr *E) {1958  if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))1959    return Materialize->getSubExpr();1960 1961  if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))1962    return Binder->getSubExpr();1963 1964  if (auto *Full = dyn_cast<FullExpr>(E))1965    return Full->getSubExpr();1966 1967  if (auto *CPLIE = dyn_cast<CXXParenListInitExpr>(E);1968      CPLIE && CPLIE->getInitExprs().size() == 1)1969    return CPLIE->getInitExprs()[0];1970 1971  return E;1972}1973} // namespace1974 1975Expr *CastExpr::getSubExprAsWritten() {1976  const Expr *SubExpr = nullptr;1977 1978  for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {1979    SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);1980 1981    // Conversions by constructor and conversion functions have a1982    // subexpression describing the call; strip it off.1983    if (E->getCastKind() == CK_ConstructorConversion) {1984      SubExpr = IgnoreExprNodes(cast<CXXConstructExpr>(SubExpr)->getArg(0),1985                                ignoreImplicitSemaNodes);1986    } else if (E->getCastKind() == CK_UserDefinedConversion) {1987      assert((isa<CallExpr, BlockExpr>(SubExpr)) &&1988             "Unexpected SubExpr for CK_UserDefinedConversion.");1989      if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))1990        SubExpr = MCE->getImplicitObjectArgument();1991    }1992  }1993 1994  return const_cast<Expr *>(SubExpr);1995}1996 1997NamedDecl *CastExpr::getConversionFunction() const {1998  const Expr *SubExpr = nullptr;1999 2000  for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {2001    SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);2002 2003    if (E->getCastKind() == CK_ConstructorConversion)2004      return cast<CXXConstructExpr>(SubExpr)->getConstructor();2005 2006    if (E->getCastKind() == CK_UserDefinedConversion) {2007      if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))2008        return MCE->getMethodDecl();2009    }2010  }2011 2012  return nullptr;2013}2014 2015CXXBaseSpecifier **CastExpr::path_buffer() {2016  switch (getStmtClass()) {2017#define ABSTRACT_STMT(x)2018#define CASTEXPR(Type, Base)                                                   \2019  case Stmt::Type##Class:                                                      \2020    return static_cast<Type *>(this)                                           \2021        ->getTrailingObjectsNonStrict<CXXBaseSpecifier *>();2022#define STMT(Type, Base)2023#include "clang/AST/StmtNodes.inc"2024  default:2025    llvm_unreachable("non-cast expressions not possible here");2026  }2027}2028 2029const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,2030                                                        QualType opType) {2031  return getTargetFieldForToUnionCast(unionType->castAsRecordDecl(), opType);2032}2033 2034const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,2035                                                        QualType OpType) {2036  auto &Ctx = RD->getASTContext();2037  RecordDecl::field_iterator Field, FieldEnd;2038  for (Field = RD->field_begin(), FieldEnd = RD->field_end();2039       Field != FieldEnd; ++Field) {2040    if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&2041        !Field->isUnnamedBitField()) {2042      return *Field;2043    }2044  }2045  return nullptr;2046}2047 2048FPOptionsOverride *CastExpr::getTrailingFPFeatures() {2049  assert(hasStoredFPFeatures());2050  switch (getStmtClass()) {2051  case ImplicitCastExprClass:2052    return static_cast<ImplicitCastExpr *>(this)2053        ->getTrailingObjects<FPOptionsOverride>();2054  case CStyleCastExprClass:2055    return static_cast<CStyleCastExpr *>(this)2056        ->getTrailingObjects<FPOptionsOverride>();2057  case CXXFunctionalCastExprClass:2058    return static_cast<CXXFunctionalCastExpr *>(this)2059        ->getTrailingObjects<FPOptionsOverride>();2060  case CXXStaticCastExprClass:2061    return static_cast<CXXStaticCastExpr *>(this)2062        ->getTrailingObjects<FPOptionsOverride>();2063  default:2064    llvm_unreachable("Cast does not have FPFeatures");2065  }2066}2067 2068ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,2069                                           CastKind Kind, Expr *Operand,2070                                           const CXXCastPath *BasePath,2071                                           ExprValueKind VK,2072                                           FPOptionsOverride FPO) {2073  unsigned PathSize = (BasePath ? BasePath->size() : 0);2074  void *Buffer =2075      C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(2076          PathSize, FPO.requiresTrailingStorage()));2077  // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and2078  // std::nullptr_t have special semantics not captured by CK_LValueToRValue.2079  assert((Kind != CK_LValueToRValue ||2080          !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&2081         "invalid type for lvalue-to-rvalue conversion");2082  ImplicitCastExpr *E =2083      new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);2084  if (PathSize)2085    llvm::uninitialized_copy(*BasePath,2086                             E->getTrailingObjects<CXXBaseSpecifier *>());2087  return E;2088}2089 2090ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,2091                                                unsigned PathSize,2092                                                bool HasFPFeatures) {2093  void *Buffer =2094      C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(2095          PathSize, HasFPFeatures));2096  return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);2097}2098 2099CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,2100                                       ExprValueKind VK, CastKind K, Expr *Op,2101                                       const CXXCastPath *BasePath,2102                                       FPOptionsOverride FPO,2103                                       TypeSourceInfo *WrittenTy,2104                                       SourceLocation L, SourceLocation R) {2105  unsigned PathSize = (BasePath ? BasePath->size() : 0);2106  void *Buffer =2107      C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(2108          PathSize, FPO.requiresTrailingStorage()));2109  CStyleCastExpr *E =2110      new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);2111  if (PathSize)2112    llvm::uninitialized_copy(*BasePath,2113                             E->getTrailingObjects<CXXBaseSpecifier *>());2114  return E;2115}2116 2117CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,2118                                            unsigned PathSize,2119                                            bool HasFPFeatures) {2120  void *Buffer =2121      C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(2122          PathSize, HasFPFeatures));2123  return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);2124}2125 2126/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it2127/// corresponds to, e.g. "<<=".2128StringRef BinaryOperator::getOpcodeStr(Opcode Op) {2129  switch (Op) {2130#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;2131#include "clang/AST/OperationKinds.def"2132  }2133  llvm_unreachable("Invalid OpCode!");2134}2135 2136BinaryOperatorKind2137BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {2138  switch (OO) {2139  default: llvm_unreachable("Not an overloadable binary operator");2140  case OO_Plus: return BO_Add;2141  case OO_Minus: return BO_Sub;2142  case OO_Star: return BO_Mul;2143  case OO_Slash: return BO_Div;2144  case OO_Percent: return BO_Rem;2145  case OO_Caret: return BO_Xor;2146  case OO_Amp: return BO_And;2147  case OO_Pipe: return BO_Or;2148  case OO_Equal: return BO_Assign;2149  case OO_Spaceship: return BO_Cmp;2150  case OO_Less: return BO_LT;2151  case OO_Greater: return BO_GT;2152  case OO_PlusEqual: return BO_AddAssign;2153  case OO_MinusEqual: return BO_SubAssign;2154  case OO_StarEqual: return BO_MulAssign;2155  case OO_SlashEqual: return BO_DivAssign;2156  case OO_PercentEqual: return BO_RemAssign;2157  case OO_CaretEqual: return BO_XorAssign;2158  case OO_AmpEqual: return BO_AndAssign;2159  case OO_PipeEqual: return BO_OrAssign;2160  case OO_LessLess: return BO_Shl;2161  case OO_GreaterGreater: return BO_Shr;2162  case OO_LessLessEqual: return BO_ShlAssign;2163  case OO_GreaterGreaterEqual: return BO_ShrAssign;2164  case OO_EqualEqual: return BO_EQ;2165  case OO_ExclaimEqual: return BO_NE;2166  case OO_LessEqual: return BO_LE;2167  case OO_GreaterEqual: return BO_GE;2168  case OO_AmpAmp: return BO_LAnd;2169  case OO_PipePipe: return BO_LOr;2170  case OO_Comma: return BO_Comma;2171  case OO_ArrowStar: return BO_PtrMemI;2172  }2173}2174 2175OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {2176  static const OverloadedOperatorKind OverOps[] = {2177    /* .* Cannot be overloaded */OO_None, OO_ArrowStar,2178    OO_Star, OO_Slash, OO_Percent,2179    OO_Plus, OO_Minus,2180    OO_LessLess, OO_GreaterGreater,2181    OO_Spaceship,2182    OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,2183    OO_EqualEqual, OO_ExclaimEqual,2184    OO_Amp,2185    OO_Caret,2186    OO_Pipe,2187    OO_AmpAmp,2188    OO_PipePipe,2189    OO_Equal, OO_StarEqual,2190    OO_SlashEqual, OO_PercentEqual,2191    OO_PlusEqual, OO_MinusEqual,2192    OO_LessLessEqual, OO_GreaterGreaterEqual,2193    OO_AmpEqual, OO_CaretEqual,2194    OO_PipeEqual,2195    OO_Comma2196  };2197  return OverOps[Opc];2198}2199 2200bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,2201                                                      Opcode Opc,2202                                                      const Expr *LHS,2203                                                      const Expr *RHS) {2204  if (Opc != BO_Add)2205    return false;2206 2207  // Check that we have one pointer and one integer operand.2208  const Expr *PExp;2209  if (LHS->getType()->isPointerType()) {2210    if (!RHS->getType()->isIntegerType())2211      return false;2212    PExp = LHS;2213  } else if (RHS->getType()->isPointerType()) {2214    if (!LHS->getType()->isIntegerType())2215      return false;2216    PExp = RHS;2217  } else {2218    return false;2219  }2220 2221  // Workaround for old glibc's __PTR_ALIGN macro2222  if (auto *Select =2223          dyn_cast<ConditionalOperator>(PExp->IgnoreParenNoopCasts(Ctx))) {2224    // If the condition can be constant evaluated, we check the selected arm.2225    bool EvalResult;2226    if (!Select->getCond()->EvaluateAsBooleanCondition(EvalResult, Ctx))2227      return false;2228    PExp = EvalResult ? Select->getTrueExpr() : Select->getFalseExpr();2229  }2230 2231  // Check that the pointer is a nullptr.2232  if (!PExp->IgnoreParenCasts()2233          ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))2234    return false;2235 2236  // Check that the pointee type is char-sized.2237  const PointerType *PTy = PExp->getType()->getAs<PointerType>();2238  if (!PTy || !PTy->getPointeeType()->isCharType())2239    return false;2240 2241  return true;2242}2243 2244SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Kind,2245                             QualType ResultTy, SourceLocation BLoc,2246                             SourceLocation RParenLoc,2247                             DeclContext *ParentContext)2248    : Expr(SourceLocExprClass, ResultTy, VK_PRValue, OK_Ordinary),2249      BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {2250  SourceLocExprBits.Kind = llvm::to_underlying(Kind);2251  // In dependent contexts, function names may change.2252  setDependence(MayBeDependent(Kind) && ParentContext->isDependentContext()2253                    ? ExprDependence::Value2254                    : ExprDependence::None);2255}2256 2257StringRef SourceLocExpr::getBuiltinStr() const {2258  switch (getIdentKind()) {2259  case SourceLocIdentKind::File:2260    return "__builtin_FILE";2261  case SourceLocIdentKind::FileName:2262    return "__builtin_FILE_NAME";2263  case SourceLocIdentKind::Function:2264    return "__builtin_FUNCTION";2265  case SourceLocIdentKind::FuncSig:2266    return "__builtin_FUNCSIG";2267  case SourceLocIdentKind::Line:2268    return "__builtin_LINE";2269  case SourceLocIdentKind::Column:2270    return "__builtin_COLUMN";2271  case SourceLocIdentKind::SourceLocStruct:2272    return "__builtin_source_location";2273  }2274  llvm_unreachable("unexpected IdentKind!");2275}2276 2277APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,2278                                         const Expr *DefaultExpr) const {2279  SourceLocation Loc;2280  const DeclContext *Context;2281 2282  if (const auto *DIE = dyn_cast_if_present<CXXDefaultInitExpr>(DefaultExpr)) {2283    Loc = DIE->getUsedLocation();2284    Context = DIE->getUsedContext();2285  } else if (const auto *DAE =2286                 dyn_cast_if_present<CXXDefaultArgExpr>(DefaultExpr)) {2287    Loc = DAE->getUsedLocation();2288    Context = DAE->getUsedContext();2289  } else {2290    Loc = getLocation();2291    Context = getParentContext();2292  }2293 2294  // If we are currently parsing a lambda declarator, we might not have a fully2295  // formed call operator declaration yet, and we could not form a function name2296  // for it. Because we do not have access to Sema/function scopes here, we2297  // detect this case by relying on the fact such method doesn't yet have a2298  // type.2299  if (const auto *D = dyn_cast<CXXMethodDecl>(Context);2300      D && D->getFunctionTypeLoc().isNull() && isLambdaCallOperator(D))2301    Context = D->getParent()->getParent();2302 2303  PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(2304      Ctx.getSourceManager().getExpansionRange(Loc).getEnd());2305 2306  auto MakeStringLiteral = [&](StringRef Tmp) {2307    using LValuePathEntry = APValue::LValuePathEntry;2308    StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);2309    // Decay the string to a pointer to the first character.2310    LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};2311    return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);2312  };2313 2314  switch (getIdentKind()) {2315  case SourceLocIdentKind::FileName: {2316    // __builtin_FILE_NAME() is a Clang-specific extension that expands to the2317    // the last part of __builtin_FILE().2318    SmallString<256> FileName;2319    clang::Preprocessor::processPathToFileName(2320        FileName, PLoc, Ctx.getLangOpts(), Ctx.getTargetInfo());2321    return MakeStringLiteral(FileName);2322  }2323  case SourceLocIdentKind::File: {2324    SmallString<256> Path(PLoc.getFilename());2325    clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),2326                                                 Ctx.getTargetInfo());2327    return MakeStringLiteral(Path);2328  }2329  case SourceLocIdentKind::Function:2330  case SourceLocIdentKind::FuncSig: {2331    const auto *CurDecl = dyn_cast<Decl>(Context);2332    const auto Kind = getIdentKind() == SourceLocIdentKind::Function2333                          ? PredefinedIdentKind::Function2334                          : PredefinedIdentKind::FuncSig;2335    return MakeStringLiteral(2336        CurDecl ? PredefinedExpr::ComputeName(Kind, CurDecl) : std::string(""));2337  }2338  case SourceLocIdentKind::Line:2339    return APValue(Ctx.MakeIntValue(PLoc.getLine(), Ctx.UnsignedIntTy));2340  case SourceLocIdentKind::Column:2341    return APValue(Ctx.MakeIntValue(PLoc.getColumn(), Ctx.UnsignedIntTy));2342  case SourceLocIdentKind::SourceLocStruct: {2343    // Fill in a std::source_location::__impl structure, by creating an2344    // artificial file-scoped CompoundLiteralExpr, and returning a pointer to2345    // that.2346    const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl();2347    assert(ImplDecl);2348 2349    // Construct an APValue for the __impl struct, and get or create a Decl2350    // corresponding to that. Note that we've already verified that the shape of2351    // the ImplDecl type is as expected.2352 2353    APValue Value(APValue::UninitStruct(), 0, 4);2354    for (const FieldDecl *F : ImplDecl->fields()) {2355      StringRef Name = F->getName();2356      if (Name == "_M_file_name") {2357        SmallString<256> Path(PLoc.getFilename());2358        clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),2359                                                     Ctx.getTargetInfo());2360        Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(Path);2361      } else if (Name == "_M_function_name") {2362        // Note: this emits the PrettyFunction name -- different than what2363        // __builtin_FUNCTION() above returns!2364        const auto *CurDecl = dyn_cast<Decl>(Context);2365        Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(2366            CurDecl && !isa<TranslationUnitDecl>(CurDecl)2367                ? StringRef(PredefinedExpr::ComputeName(2368                      PredefinedIdentKind::PrettyFunction, CurDecl))2369                : "");2370      } else if (Name == "_M_line") {2371        llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getLine(), F->getType());2372        Value.getStructField(F->getFieldIndex()) = APValue(IntVal);2373      } else if (Name == "_M_column") {2374        llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getColumn(), F->getType());2375        Value.getStructField(F->getFieldIndex()) = APValue(IntVal);2376      }2377    }2378 2379    UnnamedGlobalConstantDecl *GV =2380        Ctx.getUnnamedGlobalConstantDecl(getType()->getPointeeType(), Value);2381 2382    return APValue(GV, CharUnits::Zero(), ArrayRef<APValue::LValuePathEntry>{},2383                   false);2384  }2385  }2386  llvm_unreachable("unhandled case");2387}2388 2389EmbedExpr::EmbedExpr(const ASTContext &Ctx, SourceLocation Loc,2390                     EmbedDataStorage *Data, unsigned Begin,2391                     unsigned NumOfElements)2392    : Expr(EmbedExprClass, Ctx.IntTy, VK_PRValue, OK_Ordinary),2393      EmbedKeywordLoc(Loc), Ctx(&Ctx), Data(Data), Begin(Begin),2394      NumOfElements(NumOfElements) {2395  setDependence(ExprDependence::None);2396  FakeChildNode = IntegerLiteral::Create(2397      Ctx, llvm::APInt::getZero(Ctx.getTypeSize(getType())), getType(), Loc);2398  assert(getType()->isSignedIntegerType() && "IntTy should be signed");2399}2400 2401InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,2402                           ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)2403    : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),2404      InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),2405      RBraceLoc(rbraceloc), AltForm(nullptr, true) {2406  sawArrayRangeDesignator(false);2407  InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());2408 2409  setDependence(computeDependence(this));2410}2411 2412void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {2413  if (NumInits > InitExprs.size())2414    InitExprs.reserve(C, NumInits);2415}2416 2417void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {2418  InitExprs.resize(C, NumInits, nullptr);2419}2420 2421Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {2422  if (Init >= InitExprs.size()) {2423    InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);2424    setInit(Init, expr);2425    return nullptr;2426  }2427 2428  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);2429  setInit(Init, expr);2430  return Result;2431}2432 2433void InitListExpr::setArrayFiller(Expr *filler) {2434  assert(!hasArrayFiller() && "Filler already set!");2435  ArrayFillerOrUnionFieldInit = filler;2436  // Fill out any "holes" in the array due to designated initializers.2437  Expr **inits = getInits();2438  for (unsigned i = 0, e = getNumInits(); i != e; ++i)2439    if (inits[i] == nullptr)2440      inits[i] = filler;2441}2442 2443bool InitListExpr::isStringLiteralInit() const {2444  if (getNumInits() != 1)2445    return false;2446  const ArrayType *AT = getType()->getAsArrayTypeUnsafe();2447  if (!AT || !AT->getElementType()->isIntegerType())2448    return false;2449  // It is possible for getInit() to return null.2450  const Expr *Init = getInit(0);2451  if (!Init)2452    return false;2453  Init = Init->IgnoreParenImpCasts();2454  return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);2455}2456 2457bool InitListExpr::isTransparent() const {2458  assert(isSemanticForm() && "syntactic form never semantically transparent");2459 2460  // A glvalue InitListExpr is always just sugar.2461  if (isGLValue()) {2462    assert(getNumInits() == 1 && "multiple inits in glvalue init list");2463    return true;2464  }2465 2466  // Otherwise, we're sugar if and only if we have exactly one initializer that2467  // is of the same type.2468  if (getNumInits() != 1 || !getInit(0))2469    return false;2470 2471  // Don't confuse aggregate initialization of a struct X { X &x; }; with a2472  // transparent struct copy.2473  if (!getInit(0)->isPRValue() && getType()->isRecordType())2474    return false;2475 2476  return getType().getCanonicalType() ==2477         getInit(0)->getType().getCanonicalType();2478}2479 2480bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {2481  assert(isSyntacticForm() && "only test syntactic form as zero initializer");2482 2483  if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {2484    return false;2485  }2486 2487  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());2488  return Lit && Lit->getValue() == 0;2489}2490 2491SourceLocation InitListExpr::getBeginLoc() const {2492  if (InitListExpr *SyntacticForm = getSyntacticForm())2493    return SyntacticForm->getBeginLoc();2494  SourceLocation Beg = LBraceLoc;2495  if (Beg.isInvalid()) {2496    // Find the first non-null initializer.2497    for (InitExprsTy::const_iterator I = InitExprs.begin(),2498                                     E = InitExprs.end();2499      I != E; ++I) {2500      if (Stmt *S = *I) {2501        Beg = S->getBeginLoc();2502        break;2503      }2504    }2505  }2506  return Beg;2507}2508 2509SourceLocation InitListExpr::getEndLoc() const {2510  if (InitListExpr *SyntacticForm = getSyntacticForm())2511    return SyntacticForm->getEndLoc();2512  SourceLocation End = RBraceLoc;2513  if (End.isInvalid()) {2514    // Find the first non-null initializer from the end.2515    for (Stmt *S : llvm::reverse(InitExprs)) {2516      if (S) {2517        End = S->getEndLoc();2518        break;2519      }2520    }2521  }2522  return End;2523}2524 2525/// getFunctionType - Return the underlying function type for this block.2526///2527const FunctionProtoType *BlockExpr::getFunctionType() const {2528  // The block pointer is never sugared, but the function type might be.2529  return cast<BlockPointerType>(getType())2530           ->getPointeeType()->castAs<FunctionProtoType>();2531}2532 2533SourceLocation BlockExpr::getCaretLocation() const {2534  return TheBlock->getCaretLocation();2535}2536const Stmt *BlockExpr::getBody() const {2537  return TheBlock->getBody();2538}2539Stmt *BlockExpr::getBody() {2540  return TheBlock->getBody();2541}2542 2543 2544//===----------------------------------------------------------------------===//2545// Generic Expression Routines2546//===----------------------------------------------------------------------===//2547 2548/// Helper to determine wether \c E is a CXXConstructExpr constructing2549/// a DecompositionDecl. Used to skip Clang-generated calls to std::get2550/// for structured bindings.2551static bool IsDecompositionDeclRefExpr(const Expr *E) {2552  const auto *Unwrapped = E->IgnoreUnlessSpelledInSource();2553  const auto *Ref = dyn_cast<DeclRefExpr>(Unwrapped);2554  if (!Ref)2555    return false;2556 2557  return isa_and_nonnull<DecompositionDecl>(Ref->getDecl());2558}2559 2560bool Expr::isReadIfDiscardedInCPlusPlus11() const {2561  // In C++11, discarded-value expressions of a certain form are special,2562  // according to [expr]p10:2563  //   The lvalue-to-rvalue conversion (4.1) is applied only if the2564  //   expression is a glvalue of volatile-qualified type and it has2565  //   one of the following forms:2566  if (!isGLValue() || !getType().isVolatileQualified())2567    return false;2568 2569  const Expr *E = IgnoreParens();2570 2571  //   - id-expression (5.1.1),2572  if (isa<DeclRefExpr>(E))2573    return true;2574 2575  //   - subscripting (5.2.1),2576  if (isa<ArraySubscriptExpr>(E))2577    return true;2578 2579  //   - class member access (5.2.5),2580  if (isa<MemberExpr>(E))2581    return true;2582 2583  //   - indirection (5.3.1),2584  if (auto *UO = dyn_cast<UnaryOperator>(E))2585    if (UO->getOpcode() == UO_Deref)2586      return true;2587 2588  if (auto *BO = dyn_cast<BinaryOperator>(E)) {2589    //   - pointer-to-member operation (5.5),2590    if (BO->isPtrMemOp())2591      return true;2592 2593    //   - comma expression (5.18) where the right operand is one of the above.2594    if (BO->getOpcode() == BO_Comma)2595      return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();2596  }2597 2598  //   - conditional expression (5.16) where both the second and the third2599  //     operands are one of the above, or2600  if (auto *CO = dyn_cast<ConditionalOperator>(E))2601    return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&2602           CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();2603  // The related edge case of "*x ?: *x".2604  if (auto *BCO =2605          dyn_cast<BinaryConditionalOperator>(E)) {2606    if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))2607      return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&2608             BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();2609  }2610 2611  // Objective-C++ extensions to the rule.2612  if (isa<ObjCIvarRefExpr>(E))2613    return true;2614  if (const auto *POE = dyn_cast<PseudoObjectExpr>(E)) {2615    if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(POE->getSyntacticForm()))2616      return true;2617  }2618 2619  return false;2620}2621 2622/// isUnusedResultAWarning - Return true if this immediate expression should2623/// be warned about if the result is unused.  If so, fill in Loc and Ranges2624/// with location to warn on and the source range[s] to report with the2625/// warning.2626bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,2627                                  SourceRange &R1, SourceRange &R2,2628                                  ASTContext &Ctx) const {2629  // Don't warn if the expr is type dependent. The type could end up2630  // instantiating to void.2631  if (isTypeDependent())2632    return false;2633 2634  switch (getStmtClass()) {2635  default:2636    if (getType()->isVoidType())2637      return false;2638    WarnE = this;2639    Loc = getExprLoc();2640    R1 = getSourceRange();2641    return true;2642  case ParenExprClass:2643    return cast<ParenExpr>(this)->getSubExpr()->2644      isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2645  case GenericSelectionExprClass:2646    return cast<GenericSelectionExpr>(this)->getResultExpr()->2647      isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2648  case CoawaitExprClass:2649  case CoyieldExprClass:2650    return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->2651      isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2652  case ChooseExprClass:2653    return cast<ChooseExpr>(this)->getChosenSubExpr()->2654      isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2655  case UnaryOperatorClass: {2656    const UnaryOperator *UO = cast<UnaryOperator>(this);2657 2658    switch (UO->getOpcode()) {2659    case UO_Plus:2660    case UO_Minus:2661    case UO_AddrOf:2662    case UO_Not:2663    case UO_LNot:2664    case UO_Deref:2665      break;2666    case UO_Coawait:2667      // This is just the 'operator co_await' call inside the guts of a2668      // dependent co_await call.2669    case UO_PostInc:2670    case UO_PostDec:2671    case UO_PreInc:2672    case UO_PreDec:                 // ++/--2673      return false;  // Not a warning.2674    case UO_Real:2675    case UO_Imag:2676      // accessing a piece of a volatile complex is a side-effect.2677      if (Ctx.getCanonicalType(UO->getSubExpr()->getType())2678          .isVolatileQualified())2679        return false;2680      break;2681    case UO_Extension:2682      return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2683    }2684    WarnE = this;2685    Loc = UO->getOperatorLoc();2686    R1 = UO->getSubExpr()->getSourceRange();2687    return true;2688  }2689  case BinaryOperatorClass: {2690    const BinaryOperator *BO = cast<BinaryOperator>(this);2691    switch (BO->getOpcode()) {2692      default:2693        break;2694      // Consider the RHS of comma for side effects. LHS was checked by2695      // Sema::CheckCommaOperands.2696      case BO_Comma:2697        // ((foo = <blah>), 0) is an idiom for hiding the result (and2698        // lvalue-ness) of an assignment written in a macro.2699        if (IntegerLiteral *IE =2700              dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))2701          if (IE->getValue() == 0)2702            return false;2703        return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2704      // Consider '||', '&&' to have side effects if the LHS or RHS does.2705      case BO_LAnd:2706      case BO_LOr:2707        if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||2708            !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))2709          return false;2710        break;2711    }2712    if (BO->isAssignmentOp())2713      return false;2714    WarnE = this;2715    Loc = BO->getOperatorLoc();2716    R1 = BO->getLHS()->getSourceRange();2717    R2 = BO->getRHS()->getSourceRange();2718    return true;2719  }2720  case CompoundAssignOperatorClass:2721  case VAArgExprClass:2722  case AtomicExprClass:2723    return false;2724 2725  case ConditionalOperatorClass: {2726    // If only one of the LHS or RHS is a warning, the operator might2727    // be being used for control flow. Only warn if both the LHS and2728    // RHS are warnings.2729    const auto *Exp = cast<ConditionalOperator>(this);2730    return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&2731           Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2732  }2733  case BinaryConditionalOperatorClass: {2734    const auto *Exp = cast<BinaryConditionalOperator>(this);2735    return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2736  }2737 2738  case MemberExprClass:2739    WarnE = this;2740    Loc = cast<MemberExpr>(this)->getMemberLoc();2741    R1 = SourceRange(Loc, Loc);2742    R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();2743    return true;2744 2745  case ArraySubscriptExprClass:2746    WarnE = this;2747    Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();2748    R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();2749    R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();2750    return true;2751 2752  case CXXOperatorCallExprClass: {2753    // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator2754    // overloads as there is no reasonable way to define these such that they2755    // have non-trivial, desirable side-effects. See the -Wunused-comparison2756    // warning: operators == and != are commonly typo'ed, and so warning on them2757    // provides additional value as well. If this list is updated,2758    // DiagnoseUnusedComparison should be as well.2759    const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);2760    switch (Op->getOperator()) {2761    default:2762      break;2763    case OO_EqualEqual:2764    case OO_ExclaimEqual:2765    case OO_Less:2766    case OO_Greater:2767    case OO_GreaterEqual:2768    case OO_LessEqual:2769      if (Op->getCallReturnType(Ctx)->isReferenceType() ||2770          Op->getCallReturnType(Ctx)->isVoidType())2771        break;2772      WarnE = this;2773      Loc = Op->getOperatorLoc();2774      R1 = Op->getSourceRange();2775      return true;2776    }2777 2778    // Fallthrough for generic call handling.2779    [[fallthrough]];2780  }2781  case CallExprClass:2782  case CXXMemberCallExprClass:2783  case UserDefinedLiteralClass: {2784    // If this is a direct call, get the callee.2785    const CallExpr *CE = cast<CallExpr>(this);2786    // If the callee has attribute pure, const, or warn_unused_result, warn2787    // about it. void foo() { strlen("bar"); } should warn.2788    // Note: If new cases are added here, DiagnoseUnusedExprResult should be2789    // updated to match for QoI.2790    const Decl *FD = CE->getCalleeDecl();2791    bool PureOrConst =2792        FD && (FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>());2793    if (CE->hasUnusedResultAttr(Ctx) || PureOrConst) {2794      WarnE = this;2795      Loc = getBeginLoc();2796      R1 = getSourceRange();2797 2798      if (unsigned NumArgs = CE->getNumArgs())2799        R2 = SourceRange(CE->getArg(0)->getBeginLoc(),2800                         CE->getArg(NumArgs - 1)->getEndLoc());2801      return true;2802    }2803    return false;2804  }2805 2806  // If we don't know precisely what we're looking at, let's not warn.2807  case UnresolvedLookupExprClass:2808  case CXXUnresolvedConstructExprClass:2809  case RecoveryExprClass:2810    return false;2811 2812  case CXXTemporaryObjectExprClass:2813  case CXXConstructExprClass: {2814    const auto *CE = cast<CXXConstructExpr>(this);2815    const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl();2816 2817    if ((Type && Type->hasAttr<WarnUnusedAttr>()) ||2818        CE->hasUnusedResultAttr(Ctx)) {2819      WarnE = this;2820      Loc = getBeginLoc();2821      R1 = getSourceRange();2822 2823      if (unsigned NumArgs = CE->getNumArgs())2824        R2 = SourceRange(CE->getArg(0)->getBeginLoc(),2825                         CE->getArg(NumArgs - 1)->getEndLoc());2826      return true;2827    }2828    return false;2829  }2830 2831  case ObjCMessageExprClass: {2832    const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);2833    if (Ctx.getLangOpts().ObjCAutoRefCount &&2834        ME->isInstanceMessage() &&2835        !ME->getType()->isVoidType() &&2836        ME->getMethodFamily() == OMF_init) {2837      WarnE = this;2838      Loc = getExprLoc();2839      R1 = ME->getSourceRange();2840      return true;2841    }2842 2843    if (ME->hasUnusedResultAttr(Ctx)) {2844      WarnE = this;2845      Loc = getExprLoc();2846      return true;2847    }2848 2849    return false;2850  }2851 2852  case ObjCPropertyRefExprClass:2853  case ObjCSubscriptRefExprClass:2854    WarnE = this;2855    Loc = getExprLoc();2856    R1 = getSourceRange();2857    return true;2858 2859  case PseudoObjectExprClass: {2860    const auto *POE = cast<PseudoObjectExpr>(this);2861 2862    // For some syntactic forms, we should always warn.2863    if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(2864            POE->getSyntacticForm())) {2865      WarnE = this;2866      Loc = getExprLoc();2867      R1 = getSourceRange();2868      return true;2869    }2870 2871    // For others, we should never warn.2872    if (auto *BO = dyn_cast<BinaryOperator>(POE->getSyntacticForm()))2873      if (BO->isAssignmentOp())2874        return false;2875    if (auto *UO = dyn_cast<UnaryOperator>(POE->getSyntacticForm()))2876      if (UO->isIncrementDecrementOp())2877        return false;2878 2879    // Otherwise, warn if the result expression would warn.2880    const Expr *Result = POE->getResultExpr();2881    return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2882  }2883 2884  case StmtExprClass: {2885    // Statement exprs don't logically have side effects themselves, but are2886    // sometimes used in macros in ways that give them a type that is unused.2887    // For example ({ blah; foo(); }) will end up with a type if foo has a type.2888    // however, if the result of the stmt expr is dead, we don't want to emit a2889    // warning.2890    const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();2891    if (!CS->body_empty()) {2892      if (const Expr *E = dyn_cast<Expr>(CS->body_back()))2893        return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2894      if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))2895        if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))2896          return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2897    }2898 2899    if (getType()->isVoidType())2900      return false;2901    WarnE = this;2902    Loc = cast<StmtExpr>(this)->getLParenLoc();2903    R1 = getSourceRange();2904    return true;2905  }2906  case CXXFunctionalCastExprClass:2907  case CStyleCastExprClass: {2908    // Ignore an explicit cast to void, except in C++98 if the operand is a2909    // volatile glvalue for which we would trigger an implicit read in any2910    // other language mode. (Such an implicit read always happens as part of2911    // the lvalue conversion in C, and happens in C++ for expressions of all2912    // forms where it seems likely the user intended to trigger a volatile2913    // load.)2914    const CastExpr *CE = cast<CastExpr>(this);2915    const Expr *SubE = CE->getSubExpr()->IgnoreParens();2916    if (CE->getCastKind() == CK_ToVoid) {2917      if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&2918          SubE->isReadIfDiscardedInCPlusPlus11()) {2919        // Suppress the "unused value" warning for idiomatic usage of2920        // '(void)var;' used to suppress "unused variable" warnings.2921        if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))2922          if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))2923            if (!VD->isExternallyVisible())2924              return false;2925 2926        // The lvalue-to-rvalue conversion would have no effect for an array.2927        // It's implausible that the programmer expected this to result in a2928        // volatile array load, so don't warn.2929        if (SubE->getType()->isArrayType())2930          return false;2931 2932        return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2933      }2934      return false;2935    }2936 2937    // If this is a cast to a constructor conversion, check the operand.2938    // Otherwise, the result of the cast is unused.2939    if (CE->getCastKind() == CK_ConstructorConversion)2940      return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2941    if (CE->getCastKind() == CK_Dependent)2942      return false;2943 2944    WarnE = this;2945    if (const CXXFunctionalCastExpr *CXXCE =2946            dyn_cast<CXXFunctionalCastExpr>(this)) {2947      Loc = CXXCE->getBeginLoc();2948      R1 = CXXCE->getSubExpr()->getSourceRange();2949    } else {2950      const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);2951      Loc = CStyleCE->getLParenLoc();2952      R1 = CStyleCE->getSubExpr()->getSourceRange();2953    }2954    return true;2955  }2956  case ImplicitCastExprClass: {2957    const CastExpr *ICE = cast<ImplicitCastExpr>(this);2958 2959    // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.2960    if (ICE->getCastKind() == CK_LValueToRValue &&2961        ICE->getSubExpr()->getType().isVolatileQualified())2962      return false;2963 2964    return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2965  }2966  case CXXDefaultArgExprClass:2967    return (cast<CXXDefaultArgExpr>(this)2968            ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));2969  case CXXDefaultInitExprClass:2970    return (cast<CXXDefaultInitExpr>(this)2971            ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));2972 2973  case CXXNewExprClass:2974    // FIXME: In theory, there might be new expressions that don't have side2975    // effects (e.g. a placement new with an uninitialized POD).2976  case CXXDeleteExprClass:2977    return false;2978  case MaterializeTemporaryExprClass:2979    return cast<MaterializeTemporaryExpr>(this)2980        ->getSubExpr()2981        ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2982  case CXXBindTemporaryExprClass:2983    return cast<CXXBindTemporaryExpr>(this)->getSubExpr()2984               ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2985  case ExprWithCleanupsClass:2986    return cast<ExprWithCleanups>(this)->getSubExpr()2987               ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);2988  case OpaqueValueExprClass:2989    return cast<OpaqueValueExpr>(this)->getSourceExpr()->isUnusedResultAWarning(2990        WarnE, Loc, R1, R2, Ctx);2991  }2992}2993 2994/// isOBJCGCCandidate - Check if an expression is objc gc'able.2995/// returns true, if it is; false otherwise.2996bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {2997  const Expr *E = IgnoreParens();2998  switch (E->getStmtClass()) {2999  default:3000    return false;3001  case ObjCIvarRefExprClass:3002    return true;3003  case Expr::UnaryOperatorClass:3004    return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);3005  case ImplicitCastExprClass:3006    return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);3007  case MaterializeTemporaryExprClass:3008    return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(3009        Ctx);3010  case CStyleCastExprClass:3011    return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);3012  case DeclRefExprClass: {3013    const Decl *D = cast<DeclRefExpr>(E)->getDecl();3014 3015    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {3016      if (VD->hasGlobalStorage())3017        return true;3018      QualType T = VD->getType();3019      // dereferencing to a  pointer is always a gc'able candidate,3020      // unless it is __weak.3021      return T->isPointerType() &&3022             (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);3023    }3024    return false;3025  }3026  case MemberExprClass: {3027    const MemberExpr *M = cast<MemberExpr>(E);3028    return M->getBase()->isOBJCGCCandidate(Ctx);3029  }3030  case ArraySubscriptExprClass:3031    return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);3032  }3033}3034 3035bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {3036  if (isTypeDependent())3037    return false;3038  return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;3039}3040 3041QualType Expr::findBoundMemberType(const Expr *expr) {3042  assert(expr->hasPlaceholderType(BuiltinType::BoundMember));3043 3044  // Bound member expressions are always one of these possibilities:3045  //   x->m      x.m      x->*y      x.*y3046  // (possibly parenthesized)3047 3048  expr = expr->IgnoreParens();3049  if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {3050    assert(isa<CXXMethodDecl>(mem->getMemberDecl()));3051    return mem->getMemberDecl()->getType();3052  }3053 3054  if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {3055    QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()3056                      ->getPointeeType();3057    assert(type->isFunctionType());3058    return type;3059  }3060 3061  assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));3062  return QualType();3063}3064 3065Expr *Expr::IgnoreImpCasts() {3066  return IgnoreExprNodes(this, IgnoreImplicitCastsSingleStep);3067}3068 3069Expr *Expr::IgnoreCasts() {3070  return IgnoreExprNodes(this, IgnoreCastsSingleStep);3071}3072 3073Expr *Expr::IgnoreImplicit() {3074  return IgnoreExprNodes(this, IgnoreImplicitSingleStep);3075}3076 3077Expr *Expr::IgnoreImplicitAsWritten() {3078  return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);3079}3080 3081Expr *Expr::IgnoreParens() {3082  return IgnoreExprNodes(this, IgnoreParensSingleStep);3083}3084 3085Expr *Expr::IgnoreParenImpCasts() {3086  return IgnoreExprNodes(this, IgnoreParensSingleStep,3087                         IgnoreImplicitCastsExtraSingleStep);3088}3089 3090Expr *Expr::IgnoreParenCasts() {3091  return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);3092}3093 3094Expr *Expr::IgnoreConversionOperatorSingleStep() {3095  if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {3096    if (isa_and_nonnull<CXXConversionDecl>(MCE->getMethodDecl()))3097      return MCE->getImplicitObjectArgument();3098  }3099  return this;3100}3101 3102Expr *Expr::IgnoreParenLValueCasts() {3103  return IgnoreExprNodes(this, IgnoreParensSingleStep,3104                         IgnoreLValueCastsSingleStep);3105}3106 3107Expr *Expr::IgnoreParenBaseCasts() {3108  return IgnoreExprNodes(this, IgnoreParensSingleStep,3109                         IgnoreBaseCastsSingleStep);3110}3111 3112Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {3113  auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {3114    if (auto *CE = dyn_cast<CastExpr>(E)) {3115      // We ignore integer <-> casts that are of the same width, ptr<->ptr and3116      // ptr<->int casts of the same width. We also ignore all identity casts.3117      Expr *SubExpr = CE->getSubExpr();3118      bool IsIdentityCast =3119          Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());3120      bool IsSameWidthCast = (E->getType()->isPointerType() ||3121                              E->getType()->isIntegralType(Ctx)) &&3122                             (SubExpr->getType()->isPointerType() ||3123                              SubExpr->getType()->isIntegralType(Ctx)) &&3124                             (Ctx.getTypeSize(E->getType()) ==3125                              Ctx.getTypeSize(SubExpr->getType()));3126 3127      if (IsIdentityCast || IsSameWidthCast)3128        return SubExpr;3129    } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))3130      return NTTP->getReplacement();3131 3132    return E;3133  };3134  return IgnoreExprNodes(this, IgnoreParensSingleStep,3135                         IgnoreNoopCastsSingleStep);3136}3137 3138Expr *Expr::IgnoreUnlessSpelledInSource() {3139  auto IgnoreImplicitConstructorSingleStep = [](Expr *E) {3140    if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {3141      auto *SE = Cast->getSubExpr();3142      if (SE->getSourceRange() == E->getSourceRange())3143        return SE;3144    }3145 3146    if (auto *C = dyn_cast<CXXConstructExpr>(E)) {3147      auto NumArgs = C->getNumArgs();3148      if (NumArgs == 1 ||3149          (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {3150        Expr *A = C->getArg(0);3151        if (A->getSourceRange() == E->getSourceRange() || C->isElidable())3152          return A;3153      }3154    }3155    return E;3156  };3157  auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {3158    if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {3159      Expr *ExprNode = C->getImplicitObjectArgument();3160      if (ExprNode->getSourceRange() == E->getSourceRange()) {3161        return ExprNode;3162      }3163      if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {3164        if (PE->getSourceRange() == C->getSourceRange()) {3165          return cast<Expr>(PE);3166        }3167      }3168      ExprNode = ExprNode->IgnoreParenImpCasts();3169      if (ExprNode->getSourceRange() == E->getSourceRange())3170        return ExprNode;3171    }3172    return E;3173  };3174 3175  // Used when Clang generates calls to std::get for decomposing3176  // structured bindings.3177  auto IgnoreImplicitCallSingleStep = [](Expr *E) {3178    auto *C = dyn_cast<CallExpr>(E);3179    if (!C)3180      return E;3181 3182    // Looking for calls to a std::get, which usually just takes3183    // 1 argument (i.e., the structure being decomposed). If it has3184    // more than 1 argument, the others need to be defaulted.3185    unsigned NumArgs = C->getNumArgs();3186    if (NumArgs == 0 || (NumArgs > 1 && !isa<CXXDefaultArgExpr>(C->getArg(1))))3187      return E;3188 3189    Expr *A = C->getArg(0);3190 3191    // This was spelled out in source. Don't ignore.3192    if (A->getSourceRange() != E->getSourceRange())3193      return E;3194 3195    // If the argument refers to a DecompositionDecl construction,3196    // ignore it.3197    if (IsDecompositionDeclRefExpr(A))3198      return A;3199 3200    return E;3201  };3202 3203  return IgnoreExprNodes(3204      this, IgnoreImplicitSingleStep, IgnoreImplicitCastsExtraSingleStep,3205      IgnoreParensOnlySingleStep, IgnoreImplicitConstructorSingleStep,3206      IgnoreImplicitMemberCallSingleStep, IgnoreImplicitCallSingleStep);3207}3208 3209bool Expr::isDefaultArgument() const {3210  const Expr *E = this;3211  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))3212    E = M->getSubExpr();3213 3214  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))3215    E = ICE->getSubExprAsWritten();3216 3217  return isa<CXXDefaultArgExpr>(E);3218}3219 3220/// Skip over any no-op casts and any temporary-binding3221/// expressions.3222static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {3223  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))3224    E = M->getSubExpr();3225 3226  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {3227    if (ICE->getCastKind() == CK_NoOp)3228      E = ICE->getSubExpr();3229    else3230      break;3231  }3232 3233  while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))3234    E = BE->getSubExpr();3235 3236  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {3237    if (ICE->getCastKind() == CK_NoOp)3238      E = ICE->getSubExpr();3239    else3240      break;3241  }3242 3243  return E->IgnoreParens();3244}3245 3246/// isTemporaryObject - Determines if this expression produces a3247/// temporary of the given class type.3248bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {3249  if (!C.hasSameUnqualifiedType(getType(), C.getCanonicalTagType(TempTy)))3250    return false;3251 3252  const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);3253 3254  // Temporaries are by definition pr-values of class type.3255  if (!E->Classify(C).isPRValue()) {3256    // In this context, property reference is a message call and is pr-value.3257    if (!isa<ObjCPropertyRefExpr>(E))3258      return false;3259  }3260 3261  // Black-list a few cases which yield pr-values of class type that don't3262  // refer to temporaries of that type:3263 3264  // - implicit derived-to-base conversions3265  if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {3266    switch (ICE->getCastKind()) {3267    case CK_DerivedToBase:3268    case CK_UncheckedDerivedToBase:3269      return false;3270    default:3271      break;3272    }3273  }3274 3275  // - member expressions (all)3276  if (isa<MemberExpr>(E))3277    return false;3278 3279  if (const auto *BO = dyn_cast<BinaryOperator>(E))3280    if (BO->isPtrMemOp())3281      return false;3282 3283  // - opaque values (all)3284  if (isa<OpaqueValueExpr>(E))3285    return false;3286 3287  return true;3288}3289 3290bool Expr::isImplicitCXXThis() const {3291  const Expr *E = this;3292 3293  // Strip away parentheses and casts we don't care about.3294  while (true) {3295    if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {3296      E = Paren->getSubExpr();3297      continue;3298    }3299 3300    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {3301      if (ICE->getCastKind() == CK_NoOp ||3302          ICE->getCastKind() == CK_LValueToRValue ||3303          ICE->getCastKind() == CK_DerivedToBase ||3304          ICE->getCastKind() == CK_UncheckedDerivedToBase) {3305        E = ICE->getSubExpr();3306        continue;3307      }3308    }3309 3310    if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {3311      if (UnOp->getOpcode() == UO_Extension) {3312        E = UnOp->getSubExpr();3313        continue;3314      }3315    }3316 3317    if (const MaterializeTemporaryExpr *M3318                                      = dyn_cast<MaterializeTemporaryExpr>(E)) {3319      E = M->getSubExpr();3320      continue;3321    }3322 3323    break;3324  }3325 3326  if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))3327    return This->isImplicit();3328 3329  return false;3330}3331 3332/// hasAnyTypeDependentArguments - Determines if any of the expressions3333/// in Exprs is type-dependent.3334bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {3335  for (unsigned I = 0; I < Exprs.size(); ++I)3336    if (Exprs[I]->isTypeDependent())3337      return true;3338 3339  return false;3340}3341 3342bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,3343                                 const Expr **Culprit) const {3344  assert(!isValueDependent() &&3345         "Expression evaluator can't be called on a dependent expression.");3346 3347  // This function is attempting whether an expression is an initializer3348  // which can be evaluated at compile-time. It very closely parallels3349  // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it3350  // will lead to unexpected results.  Like ConstExprEmitter, it falls back3351  // to isEvaluatable most of the time.3352  //3353  // If we ever capture reference-binding directly in the AST, we can3354  // kill the second parameter.3355 3356  if (IsForRef) {3357    if (auto *EWC = dyn_cast<ExprWithCleanups>(this))3358      return EWC->getSubExpr()->isConstantInitializer(Ctx, true, Culprit);3359    if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(this))3360      return MTE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);3361    EvalResult Result;3362    if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)3363      return true;3364    if (Culprit)3365      *Culprit = this;3366    return false;3367  }3368 3369  switch (getStmtClass()) {3370  default: break;3371  case Stmt::ExprWithCleanupsClass:3372    return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(3373        Ctx, IsForRef, Culprit);3374  case StringLiteralClass:3375  case ObjCEncodeExprClass:3376    return true;3377  case CXXTemporaryObjectExprClass:3378  case CXXConstructExprClass: {3379    const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);3380 3381    if (CE->getConstructor()->isTrivial() &&3382        CE->getConstructor()->getParent()->hasTrivialDestructor()) {3383      // Trivial default constructor3384      if (!CE->getNumArgs()) return true;3385 3386      // Trivial copy constructor3387      assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");3388      return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);3389    }3390 3391    break;3392  }3393  case ConstantExprClass: {3394    // FIXME: We should be able to return "true" here, but it can lead to extra3395    // error messages. E.g. in Sema/array-init.c.3396    const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();3397    return Exp->isConstantInitializer(Ctx, false, Culprit);3398  }3399  case CompoundLiteralExprClass: {3400    // This handles gcc's extension that allows global initializers like3401    // "struct x {int x;} x = (struct x) {};".3402    // FIXME: This accepts other cases it shouldn't!3403    const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();3404    return Exp->isConstantInitializer(Ctx, false, Culprit);3405  }3406  case DesignatedInitUpdateExprClass: {3407    const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);3408    return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&3409           DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);3410  }3411  case InitListExprClass: {3412    // C++ [dcl.init.aggr]p2:3413    //   The elements of an aggregate are:3414    //   - for an array, the array elements in increasing subscript order, or3415    //   - for a class, the direct base classes in declaration order, followed3416    //     by the direct non-static data members (11.4) that are not members of3417    //     an anonymous union, in declaration order.3418    const InitListExpr *ILE = cast<InitListExpr>(this);3419    assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");3420 3421    if (ILE->isTransparent())3422      return ILE->getInit(0)->isConstantInitializer(Ctx, false, Culprit);3423 3424    if (ILE->getType()->isArrayType()) {3425      unsigned numInits = ILE->getNumInits();3426      for (unsigned i = 0; i < numInits; i++) {3427        if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))3428          return false;3429      }3430      return true;3431    }3432 3433    if (ILE->getType()->isRecordType()) {3434      unsigned ElementNo = 0;3435      auto *RD = ILE->getType()->castAsRecordDecl();3436 3437      // In C++17, bases were added to the list of members used by aggregate3438      // initialization.3439      if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {3440        for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) {3441          if (ElementNo < ILE->getNumInits()) {3442            const Expr *Elt = ILE->getInit(ElementNo++);3443            if (!Elt->isConstantInitializer(Ctx, false, Culprit))3444              return false;3445          }3446        }3447      }3448 3449      for (const auto *Field : RD->fields()) {3450        // If this is a union, skip all the fields that aren't being initialized.3451        if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)3452          continue;3453 3454        // Don't emit anonymous bitfields, they just affect layout.3455        if (Field->isUnnamedBitField())3456          continue;3457 3458        if (ElementNo < ILE->getNumInits()) {3459          const Expr *Elt = ILE->getInit(ElementNo++);3460          if (Field->isBitField()) {3461            // Bitfields have to evaluate to an integer.3462            EvalResult Result;3463            if (!Elt->EvaluateAsInt(Result, Ctx)) {3464              if (Culprit)3465                *Culprit = Elt;3466              return false;3467            }3468          } else {3469            bool RefType = Field->getType()->isReferenceType();3470            if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))3471              return false;3472          }3473        }3474      }3475      return true;3476    }3477 3478    break;3479  }3480  case ImplicitValueInitExprClass:3481  case NoInitExprClass:3482    return true;3483  case ParenExprClass:3484    return cast<ParenExpr>(this)->getSubExpr()3485      ->isConstantInitializer(Ctx, IsForRef, Culprit);3486  case GenericSelectionExprClass:3487    return cast<GenericSelectionExpr>(this)->getResultExpr()3488      ->isConstantInitializer(Ctx, IsForRef, Culprit);3489  case ChooseExprClass:3490    if (cast<ChooseExpr>(this)->isConditionDependent()) {3491      if (Culprit)3492        *Culprit = this;3493      return false;3494    }3495    return cast<ChooseExpr>(this)->getChosenSubExpr()3496      ->isConstantInitializer(Ctx, IsForRef, Culprit);3497  case UnaryOperatorClass: {3498    const UnaryOperator* Exp = cast<UnaryOperator>(this);3499    if (Exp->getOpcode() == UO_Extension)3500      return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);3501    break;3502  }3503  case PackIndexingExprClass: {3504    return cast<PackIndexingExpr>(this)3505        ->getSelectedExpr()3506        ->isConstantInitializer(Ctx, false, Culprit);3507  }3508  case CXXFunctionalCastExprClass:3509  case CXXStaticCastExprClass:3510  case ImplicitCastExprClass:3511  case CStyleCastExprClass:3512  case ObjCBridgedCastExprClass:3513  case CXXDynamicCastExprClass:3514  case CXXReinterpretCastExprClass:3515  case CXXAddrspaceCastExprClass:3516  case CXXConstCastExprClass: {3517    const CastExpr *CE = cast<CastExpr>(this);3518 3519    // Handle misc casts we want to ignore.3520    if (CE->getCastKind() == CK_NoOp ||3521        CE->getCastKind() == CK_LValueToRValue ||3522        CE->getCastKind() == CK_ToUnion ||3523        CE->getCastKind() == CK_ConstructorConversion ||3524        CE->getCastKind() == CK_NonAtomicToAtomic ||3525        CE->getCastKind() == CK_AtomicToNonAtomic ||3526        CE->getCastKind() == CK_NullToPointer ||3527        CE->getCastKind() == CK_IntToOCLSampler)3528      return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);3529 3530    break;3531  }3532  case MaterializeTemporaryExprClass:3533    return cast<MaterializeTemporaryExpr>(this)3534        ->getSubExpr()3535        ->isConstantInitializer(Ctx, false, Culprit);3536 3537  case SubstNonTypeTemplateParmExprClass:3538    return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()3539      ->isConstantInitializer(Ctx, false, Culprit);3540  case CXXDefaultArgExprClass:3541    return cast<CXXDefaultArgExpr>(this)->getExpr()3542      ->isConstantInitializer(Ctx, false, Culprit);3543  case CXXDefaultInitExprClass:3544    return cast<CXXDefaultInitExpr>(this)->getExpr()3545      ->isConstantInitializer(Ctx, false, Culprit);3546  }3547  // Allow certain forms of UB in constant initializers: signed integer3548  // overflow and floating-point division by zero. We'll give a warning on3549  // these, but they're common enough that we have to accept them.3550  if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))3551    return true;3552  if (Culprit)3553    *Culprit = this;3554  return false;3555}3556 3557bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {3558  unsigned BuiltinID = getBuiltinCallee();3559  if (BuiltinID != Builtin::BI__assume &&3560      BuiltinID != Builtin::BI__builtin_assume)3561    return false;3562 3563  const Expr* Arg = getArg(0);3564  bool ArgVal;3565  return !Arg->isValueDependent() &&3566         Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;3567}3568 3569const AllocSizeAttr *CallExpr::getCalleeAllocSizeAttr() const {3570  if (const FunctionDecl *DirectCallee = getDirectCallee())3571    return DirectCallee->getAttr<AllocSizeAttr>();3572  if (const Decl *IndirectCallee = getCalleeDecl())3573    return IndirectCallee->getAttr<AllocSizeAttr>();3574  return nullptr;3575}3576 3577std::optional<llvm::APInt>3578CallExpr::evaluateBytesReturnedByAllocSizeCall(const ASTContext &Ctx) const {3579  const AllocSizeAttr *AllocSize = getCalleeAllocSizeAttr();3580 3581  assert(AllocSize && AllocSize->getElemSizeParam().isValid());3582  unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();3583  unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());3584  if (getNumArgs() <= SizeArgNo)3585    return std::nullopt;3586 3587  auto EvaluateAsSizeT = [&](const Expr *E, llvm::APSInt &Into) {3588    Expr::EvalResult ExprResult;3589    if (E->isValueDependent() ||3590        !E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))3591      return false;3592    Into = ExprResult.Val.getInt();3593    if (Into.isNegative() || !Into.isIntN(BitsInSizeT))3594      return false;3595    Into = Into.zext(BitsInSizeT);3596    return true;3597  };3598 3599  llvm::APSInt SizeOfElem;3600  if (!EvaluateAsSizeT(getArg(SizeArgNo), SizeOfElem))3601    return std::nullopt;3602 3603  if (!AllocSize->getNumElemsParam().isValid())3604    return SizeOfElem;3605 3606  llvm::APSInt NumberOfElems;3607  unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();3608  if (!EvaluateAsSizeT(getArg(NumArgNo), NumberOfElems))3609    return std::nullopt;3610 3611  bool Overflow;3612  llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);3613  if (Overflow)3614    return std::nullopt;3615 3616  return BytesAvailable;3617}3618 3619bool CallExpr::isCallToStdMove() const {3620  return getBuiltinCallee() == Builtin::BImove;3621}3622 3623namespace {3624  /// Look for any side effects within a Stmt.3625  class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {3626    typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;3627    const bool IncludePossibleEffects;3628    bool HasSideEffects;3629 3630  public:3631    explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)3632      : Inherited(Context),3633        IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }3634 3635    bool hasSideEffects() const { return HasSideEffects; }3636 3637    void VisitDecl(const Decl *D) {3638      if (!D)3639        return;3640 3641      // We assume the caller checks subexpressions (eg, the initializer, VLA3642      // bounds) for side-effects on our behalf.3643      if (auto *VD = dyn_cast<VarDecl>(D)) {3644        // Registering a destructor is a side-effect.3645        if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&3646            VD->needsDestruction(Context))3647          HasSideEffects = true;3648      }3649    }3650 3651    void VisitDeclStmt(const DeclStmt *DS) {3652      for (auto *D : DS->decls())3653        VisitDecl(D);3654      Inherited::VisitDeclStmt(DS);3655    }3656 3657    void VisitExpr(const Expr *E) {3658      if (!HasSideEffects &&3659          E->HasSideEffects(Context, IncludePossibleEffects))3660        HasSideEffects = true;3661    }3662  };3663}3664 3665bool Expr::HasSideEffects(const ASTContext &Ctx,3666                          bool IncludePossibleEffects) const {3667  // In circumstances where we care about definite side effects instead of3668  // potential side effects, we want to ignore expressions that are part of a3669  // macro expansion as a potential side effect.3670  if (!IncludePossibleEffects && getExprLoc().isMacroID())3671    return false;3672 3673  switch (getStmtClass()) {3674  case NoStmtClass:3675#define ABSTRACT_STMT(Type)3676#define STMT(Type, Base) case Type##Class:3677#define EXPR(Type, Base)3678#include "clang/AST/StmtNodes.inc"3679    llvm_unreachable("unexpected Expr kind");3680 3681  case DependentScopeDeclRefExprClass:3682  case CXXUnresolvedConstructExprClass:3683  case CXXDependentScopeMemberExprClass:3684  case UnresolvedLookupExprClass:3685  case UnresolvedMemberExprClass:3686  case PackExpansionExprClass:3687  case SubstNonTypeTemplateParmPackExprClass:3688  case FunctionParmPackExprClass:3689  case RecoveryExprClass:3690  case CXXFoldExprClass:3691    // Make a conservative assumption for dependent nodes.3692    return IncludePossibleEffects;3693 3694  case DeclRefExprClass:3695  case ObjCIvarRefExprClass:3696  case PredefinedExprClass:3697  case IntegerLiteralClass:3698  case FixedPointLiteralClass:3699  case FloatingLiteralClass:3700  case ImaginaryLiteralClass:3701  case StringLiteralClass:3702  case CharacterLiteralClass:3703  case OffsetOfExprClass:3704  case ImplicitValueInitExprClass:3705  case UnaryExprOrTypeTraitExprClass:3706  case AddrLabelExprClass:3707  case GNUNullExprClass:3708  case ArrayInitIndexExprClass:3709  case NoInitExprClass:3710  case CXXBoolLiteralExprClass:3711  case CXXNullPtrLiteralExprClass:3712  case CXXThisExprClass:3713  case CXXScalarValueInitExprClass:3714  case TypeTraitExprClass:3715  case ArrayTypeTraitExprClass:3716  case ExpressionTraitExprClass:3717  case CXXNoexceptExprClass:3718  case SizeOfPackExprClass:3719  case ObjCStringLiteralClass:3720  case ObjCEncodeExprClass:3721  case ObjCBoolLiteralExprClass:3722  case ObjCAvailabilityCheckExprClass:3723  case CXXUuidofExprClass:3724  case OpaqueValueExprClass:3725  case SourceLocExprClass:3726  case EmbedExprClass:3727  case ConceptSpecializationExprClass:3728  case RequiresExprClass:3729  case SYCLUniqueStableNameExprClass:3730  case PackIndexingExprClass:3731  case HLSLOutArgExprClass:3732  case OpenACCAsteriskSizeExprClass:3733    // These never have a side-effect.3734    return false;3735 3736  case ConstantExprClass:3737    // FIXME: Move this into the "return false;" block above.3738    return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(3739        Ctx, IncludePossibleEffects);3740 3741  case CallExprClass:3742  case CXXOperatorCallExprClass:3743  case CXXMemberCallExprClass:3744  case CUDAKernelCallExprClass:3745  case UserDefinedLiteralClass: {3746    // We don't know a call definitely has side effects, except for calls3747    // to pure/const functions that definitely don't.3748    // If the call itself is considered side-effect free, check the operands.3749    const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();3750    bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());3751    if (IsPure || !IncludePossibleEffects)3752      break;3753    return true;3754  }3755 3756  case BlockExprClass:3757  case CXXBindTemporaryExprClass:3758    if (!IncludePossibleEffects)3759      break;3760    return true;3761 3762  case MSPropertyRefExprClass:3763  case MSPropertySubscriptExprClass:3764  case CompoundAssignOperatorClass:3765  case VAArgExprClass:3766  case AtomicExprClass:3767  case CXXThrowExprClass:3768  case CXXNewExprClass:3769  case CXXDeleteExprClass:3770  case CoawaitExprClass:3771  case DependentCoawaitExprClass:3772  case CoyieldExprClass:3773    // These always have a side-effect.3774    return true;3775 3776  case StmtExprClass: {3777    // StmtExprs have a side-effect if any substatement does.3778    SideEffectFinder Finder(Ctx, IncludePossibleEffects);3779    Finder.Visit(cast<StmtExpr>(this)->getSubStmt());3780    return Finder.hasSideEffects();3781  }3782 3783  case ExprWithCleanupsClass:3784    if (IncludePossibleEffects)3785      if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())3786        return true;3787    break;3788 3789  case ParenExprClass:3790  case ArraySubscriptExprClass:3791  case MatrixSubscriptExprClass:3792  case ArraySectionExprClass:3793  case OMPArrayShapingExprClass:3794  case OMPIteratorExprClass:3795  case MemberExprClass:3796  case ConditionalOperatorClass:3797  case BinaryConditionalOperatorClass:3798  case CompoundLiteralExprClass:3799  case ExtVectorElementExprClass:3800  case DesignatedInitExprClass:3801  case DesignatedInitUpdateExprClass:3802  case ArrayInitLoopExprClass:3803  case ParenListExprClass:3804  case CXXPseudoDestructorExprClass:3805  case CXXRewrittenBinaryOperatorClass:3806  case CXXStdInitializerListExprClass:3807  case SubstNonTypeTemplateParmExprClass:3808  case MaterializeTemporaryExprClass:3809  case ShuffleVectorExprClass:3810  case ConvertVectorExprClass:3811  case AsTypeExprClass:3812  case CXXParenListInitExprClass:3813    // These have a side-effect if any subexpression does.3814    break;3815 3816  case UnaryOperatorClass:3817    if (cast<UnaryOperator>(this)->isIncrementDecrementOp())3818      return true;3819    break;3820 3821  case BinaryOperatorClass:3822    if (cast<BinaryOperator>(this)->isAssignmentOp())3823      return true;3824    break;3825 3826  case InitListExprClass:3827    // FIXME: The children for an InitListExpr doesn't include the array filler.3828    if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())3829      if (E->HasSideEffects(Ctx, IncludePossibleEffects))3830        return true;3831    break;3832 3833  case GenericSelectionExprClass:3834    return cast<GenericSelectionExpr>(this)->getResultExpr()->HasSideEffects(3835        Ctx, IncludePossibleEffects);3836 3837  case ChooseExprClass:3838    return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(3839        Ctx, IncludePossibleEffects);3840 3841  case CXXDefaultArgExprClass:3842    return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(3843        Ctx, IncludePossibleEffects);3844 3845  case CXXDefaultInitExprClass: {3846    const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();3847    if (const Expr *E = FD->getInClassInitializer())3848      return E->HasSideEffects(Ctx, IncludePossibleEffects);3849    // If we've not yet parsed the initializer, assume it has side-effects.3850    return true;3851  }3852 3853  case CXXDynamicCastExprClass: {3854    // A dynamic_cast expression has side-effects if it can throw.3855    const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);3856    if (DCE->getTypeAsWritten()->isReferenceType() &&3857        DCE->getCastKind() == CK_Dynamic)3858      return true;3859  }3860    [[fallthrough]];3861  case ImplicitCastExprClass:3862  case CStyleCastExprClass:3863  case CXXStaticCastExprClass:3864  case CXXReinterpretCastExprClass:3865  case CXXConstCastExprClass:3866  case CXXAddrspaceCastExprClass:3867  case CXXFunctionalCastExprClass:3868  case BuiltinBitCastExprClass: {3869    // While volatile reads are side-effecting in both C and C++, we treat them3870    // as having possible (not definite) side-effects. This allows idiomatic3871    // code to behave without warning, such as sizeof(*v) for a volatile-3872    // qualified pointer.3873    if (!IncludePossibleEffects)3874      break;3875 3876    const CastExpr *CE = cast<CastExpr>(this);3877    if (CE->getCastKind() == CK_LValueToRValue &&3878        CE->getSubExpr()->getType().isVolatileQualified())3879      return true;3880    break;3881  }3882 3883  case CXXTypeidExprClass: {3884    const auto *TE = cast<CXXTypeidExpr>(this);3885    if (!TE->isPotentiallyEvaluated())3886      return false;3887 3888    // If this type id expression can throw because of a null pointer, that is a3889    // side-effect independent of if the operand has a side-effect3890    if (IncludePossibleEffects && TE->hasNullCheck())3891      return true;3892 3893    break;3894  }3895 3896  case CXXConstructExprClass:3897  case CXXTemporaryObjectExprClass: {3898    const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);3899    if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)3900      return true;3901    // A trivial constructor does not add any side-effects of its own. Just look3902    // at its arguments.3903    break;3904  }3905 3906  case CXXInheritedCtorInitExprClass: {3907    const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);3908    if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)3909      return true;3910    break;3911  }3912 3913  case LambdaExprClass: {3914    const LambdaExpr *LE = cast<LambdaExpr>(this);3915    for (Expr *E : LE->capture_inits())3916      if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))3917        return true;3918    return false;3919  }3920 3921  case PseudoObjectExprClass: {3922    // Only look for side-effects in the semantic form, and look past3923    // OpaqueValueExpr bindings in that form.3924    const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);3925    for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),3926                                                    E = PO->semantics_end();3927         I != E; ++I) {3928      const Expr *Subexpr = *I;3929      if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))3930        Subexpr = OVE->getSourceExpr();3931      if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))3932        return true;3933    }3934    return false;3935  }3936 3937  case ObjCBoxedExprClass:3938  case ObjCArrayLiteralClass:3939  case ObjCDictionaryLiteralClass:3940  case ObjCSelectorExprClass:3941  case ObjCProtocolExprClass:3942  case ObjCIsaExprClass:3943  case ObjCIndirectCopyRestoreExprClass:3944  case ObjCSubscriptRefExprClass:3945  case ObjCBridgedCastExprClass:3946  case ObjCMessageExprClass:3947  case ObjCPropertyRefExprClass:3948    // FIXME: Classify these cases better.3949    if (IncludePossibleEffects)3950      return true;3951    break;3952  }3953 3954  // Recurse to children.3955  for (const Stmt *SubStmt : children())3956    if (SubStmt &&3957        cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))3958      return true;3959 3960  return false;3961}3962 3963FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const {3964  if (auto Call = dyn_cast<CallExpr>(this))3965    return Call->getFPFeaturesInEffect(LO);3966  if (auto UO = dyn_cast<UnaryOperator>(this))3967    return UO->getFPFeaturesInEffect(LO);3968  if (auto BO = dyn_cast<BinaryOperator>(this))3969    return BO->getFPFeaturesInEffect(LO);3970  if (auto Cast = dyn_cast<CastExpr>(this))3971    return Cast->getFPFeaturesInEffect(LO);3972  if (auto ConvertVector = dyn_cast<ConvertVectorExpr>(this))3973    return ConvertVector->getFPFeaturesInEffect(LO);3974  return FPOptions::defaultWithoutTrailingStorage(LO);3975}3976 3977namespace {3978  /// Look for a call to a non-trivial function within an expression.3979  class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>3980  {3981    typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;3982 3983    bool NonTrivial;3984 3985  public:3986    explicit NonTrivialCallFinder(const ASTContext &Context)3987      : Inherited(Context), NonTrivial(false) { }3988 3989    bool hasNonTrivialCall() const { return NonTrivial; }3990 3991    void VisitCallExpr(const CallExpr *E) {3992      if (const CXXMethodDecl *Method3993          = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {3994        if (Method->isTrivial()) {3995          // Recurse to children of the call.3996          Inherited::VisitStmt(E);3997          return;3998        }3999      }4000 4001      NonTrivial = true;4002    }4003 4004    void VisitCXXConstructExpr(const CXXConstructExpr *E) {4005      if (E->getConstructor()->isTrivial()) {4006        // Recurse to children of the call.4007        Inherited::VisitStmt(E);4008        return;4009      }4010 4011      NonTrivial = true;4012    }4013 4014    void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {4015      // Destructor of the temporary might be null if destructor declaration4016      // is not valid.4017      if (const CXXDestructorDecl *DtorDecl =4018              E->getTemporary()->getDestructor()) {4019        if (DtorDecl->isTrivial()) {4020          Inherited::VisitStmt(E);4021          return;4022        }4023      }4024 4025      NonTrivial = true;4026    }4027  };4028}4029 4030bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {4031  NonTrivialCallFinder Finder(Ctx);4032  Finder.Visit(this);4033  return Finder.hasNonTrivialCall();4034}4035 4036/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null4037/// pointer constant or not, as well as the specific kind of constant detected.4038/// Null pointer constants can be integer constant expressions with the4039/// value zero, casts of zero to void*, nullptr (C++0X), or __null4040/// (a GNU extension).4041Expr::NullPointerConstantKind4042Expr::isNullPointerConstant(ASTContext &Ctx,4043                            NullPointerConstantValueDependence NPC) const {4044  if (isValueDependent() &&4045      (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {4046    // Error-dependent expr should never be a null pointer.4047    if (containsErrors())4048      return NPCK_NotNull;4049    switch (NPC) {4050    case NPC_NeverValueDependent:4051      llvm_unreachable("Unexpected value dependent expression!");4052    case NPC_ValueDependentIsNull:4053      if (isTypeDependent() || getType()->isIntegralType(Ctx))4054        return NPCK_ZeroExpression;4055      else4056        return NPCK_NotNull;4057 4058    case NPC_ValueDependentIsNotNull:4059      return NPCK_NotNull;4060    }4061  }4062 4063  // Strip off a cast to void*, if it exists. Except in C++.4064  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {4065    if (!Ctx.getLangOpts().CPlusPlus) {4066      // Check that it is a cast to void*.4067      if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {4068        QualType Pointee = PT->getPointeeType();4069        Qualifiers Qs = Pointee.getQualifiers();4070        // Only (void*)0 or equivalent are treated as nullptr. If pointee type4071        // has non-default address space it is not treated as nullptr.4072        // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr4073        // since it cannot be assigned to a pointer to constant address space.4074        if (Ctx.getLangOpts().OpenCL &&4075            Pointee.getAddressSpace() == Ctx.getDefaultOpenCLPointeeAddrSpace())4076          Qs.removeAddressSpace();4077 4078        if (Pointee->isVoidType() && Qs.empty() && // to void*4079            CE->getSubExpr()->getType()->isIntegerType()) // from int4080          return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);4081      }4082    }4083  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {4084    // Ignore the ImplicitCastExpr type entirely.4085    return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);4086  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {4087    // Accept ((void*)0) as a null pointer constant, as many other4088    // implementations do.4089    return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);4090  } else if (const GenericSelectionExpr *GE =4091               dyn_cast<GenericSelectionExpr>(this)) {4092    if (GE->isResultDependent())4093      return NPCK_NotNull;4094    return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);4095  } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {4096    if (CE->isConditionDependent())4097      return NPCK_NotNull;4098    return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);4099  } else if (const CXXDefaultArgExpr *DefaultArg4100               = dyn_cast<CXXDefaultArgExpr>(this)) {4101    // See through default argument expressions.4102    return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);4103  } else if (const CXXDefaultInitExpr *DefaultInit4104               = dyn_cast<CXXDefaultInitExpr>(this)) {4105    // See through default initializer expressions.4106    return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);4107  } else if (isa<GNUNullExpr>(this)) {4108    // The GNU __null extension is always a null pointer constant.4109    return NPCK_GNUNull;4110  } else if (const MaterializeTemporaryExpr *M4111                                   = dyn_cast<MaterializeTemporaryExpr>(this)) {4112    return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);4113  } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {4114    if (const Expr *Source = OVE->getSourceExpr())4115      return Source->isNullPointerConstant(Ctx, NPC);4116  }4117 4118  // If the expression has no type information, it cannot be a null pointer4119  // constant.4120  if (getType().isNull())4121    return NPCK_NotNull;4122 4123  // C++11/C23 nullptr_t is always a null pointer constant.4124  if (getType()->isNullPtrType())4125    return NPCK_CXX11_nullptr;4126 4127  if (const RecordType *UT = getType()->getAsUnionType())4128    if (!Ctx.getLangOpts().CPlusPlus11 && UT &&4129        UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>())4130      if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){4131        const Expr *InitExpr = CLE->getInitializer();4132        if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))4133          return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);4134      }4135  // This expression must be an integer type.4136  if (!getType()->isIntegerType() ||4137      (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))4138    return NPCK_NotNull;4139 4140  if (Ctx.getLangOpts().CPlusPlus11) {4141    // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with4142    // value zero or a prvalue of type std::nullptr_t.4143    // Microsoft mode permits C++98 rules reflecting MSVC behavior.4144    const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);4145    if (Lit && !Lit->getValue())4146      return NPCK_ZeroLiteral;4147    if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))4148      return NPCK_NotNull;4149  } else {4150    // If we have an integer constant expression, we need to *evaluate* it and4151    // test for the value 0.4152    if (!isIntegerConstantExpr(Ctx))4153      return NPCK_NotNull;4154  }4155 4156  if (EvaluateKnownConstInt(Ctx) != 0)4157    return NPCK_NotNull;4158 4159  if (isa<IntegerLiteral>(this))4160    return NPCK_ZeroLiteral;4161  return NPCK_ZeroExpression;4162}4163 4164/// If this expression is an l-value for an Objective C4165/// property, find the underlying property reference expression.4166const ObjCPropertyRefExpr *Expr::getObjCProperty() const {4167  const Expr *E = this;4168  while (true) {4169    assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&4170           "expression is not a property reference");4171    E = E->IgnoreParenCasts();4172    if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {4173      if (BO->getOpcode() == BO_Comma) {4174        E = BO->getRHS();4175        continue;4176      }4177    }4178 4179    break;4180  }4181 4182  return cast<ObjCPropertyRefExpr>(E);4183}4184 4185bool Expr::isObjCSelfExpr() const {4186  const Expr *E = IgnoreParenImpCasts();4187 4188  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);4189  if (!DRE)4190    return false;4191 4192  const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());4193  if (!Param)4194    return false;4195 4196  const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());4197  if (!M)4198    return false;4199 4200  return M->getSelfDecl() == Param;4201}4202 4203FieldDecl *Expr::getSourceBitField() {4204  Expr *E = this->IgnoreParens();4205 4206  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {4207    if (ICE->getCastKind() == CK_LValueToRValue ||4208        (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))4209      E = ICE->getSubExpr()->IgnoreParens();4210    else4211      break;4212  }4213 4214  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))4215    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))4216      if (Field->isBitField())4217        return Field;4218 4219  if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {4220    FieldDecl *Ivar = IvarRef->getDecl();4221    if (Ivar->isBitField())4222      return Ivar;4223  }4224 4225  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {4226    if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))4227      if (Field->isBitField())4228        return Field;4229 4230    if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))4231      if (Expr *E = BD->getBinding())4232        return E->getSourceBitField();4233  }4234 4235  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {4236    if (BinOp->isAssignmentOp() && BinOp->getLHS())4237      return BinOp->getLHS()->getSourceBitField();4238 4239    if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())4240      return BinOp->getRHS()->getSourceBitField();4241  }4242 4243  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))4244    if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())4245      return UnOp->getSubExpr()->getSourceBitField();4246 4247  return nullptr;4248}4249 4250EnumConstantDecl *Expr::getEnumConstantDecl() {4251  Expr *E = this->IgnoreParenImpCasts();4252  if (auto *DRE = dyn_cast<DeclRefExpr>(E))4253    return dyn_cast<EnumConstantDecl>(DRE->getDecl());4254  return nullptr;4255}4256 4257bool Expr::refersToVectorElement() const {4258  // FIXME: Why do we not just look at the ObjectKind here?4259  const Expr *E = this->IgnoreParens();4260 4261  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {4262    if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)4263      E = ICE->getSubExpr()->IgnoreParens();4264    else4265      break;4266  }4267 4268  if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))4269    return ASE->getBase()->getType()->isVectorType();4270 4271  if (isa<ExtVectorElementExpr>(E))4272    return true;4273 4274  if (auto *DRE = dyn_cast<DeclRefExpr>(E))4275    if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))4276      if (auto *E = BD->getBinding())4277        return E->refersToVectorElement();4278 4279  return false;4280}4281 4282bool Expr::refersToGlobalRegisterVar() const {4283  const Expr *E = this->IgnoreParenImpCasts();4284 4285  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))4286    if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))4287      if (VD->getStorageClass() == SC_Register &&4288          VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())4289        return true;4290 4291  return false;4292}4293 4294bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {4295  E1 = E1->IgnoreParens();4296  E2 = E2->IgnoreParens();4297 4298  if (E1->getStmtClass() != E2->getStmtClass())4299    return false;4300 4301  switch (E1->getStmtClass()) {4302    default:4303      return false;4304    case CXXThisExprClass:4305      return true;4306    case DeclRefExprClass: {4307      // DeclRefExpr without an ImplicitCastExpr can happen for integral4308      // template parameters.4309      const auto *DRE1 = cast<DeclRefExpr>(E1);4310      const auto *DRE2 = cast<DeclRefExpr>(E2);4311 4312      if (DRE1->getDecl() != DRE2->getDecl())4313        return false;4314 4315      if ((DRE1->isPRValue() && DRE2->isPRValue()) ||4316          (DRE1->isLValue() && DRE2->isLValue()))4317        return true;4318 4319      return false;4320    }4321    case ImplicitCastExprClass: {4322      // Peel off implicit casts.4323      while (true) {4324        const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);4325        const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);4326        if (!ICE1 || !ICE2)4327          return false;4328        if (ICE1->getCastKind() != ICE2->getCastKind())4329          return isSameComparisonOperand(ICE1->IgnoreParenImpCasts(),4330                                         ICE2->IgnoreParenImpCasts());4331        E1 = ICE1->getSubExpr()->IgnoreParens();4332        E2 = ICE2->getSubExpr()->IgnoreParens();4333        // The final cast must be one of these types.4334        if (ICE1->getCastKind() == CK_LValueToRValue ||4335            ICE1->getCastKind() == CK_ArrayToPointerDecay ||4336            ICE1->getCastKind() == CK_FunctionToPointerDecay) {4337          break;4338        }4339      }4340 4341      const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);4342      const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);4343      if (DRE1 && DRE2)4344        return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());4345 4346      const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);4347      const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);4348      if (Ivar1 && Ivar2) {4349        return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&4350               declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());4351      }4352 4353      const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);4354      const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);4355      if (Array1 && Array2) {4356        if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))4357          return false;4358 4359        auto Idx1 = Array1->getIdx();4360        auto Idx2 = Array2->getIdx();4361        const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);4362        const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);4363        if (Integer1 && Integer2) {4364          if (!llvm::APInt::isSameValue(Integer1->getValue(),4365                                        Integer2->getValue()))4366            return false;4367        } else {4368          if (!isSameComparisonOperand(Idx1, Idx2))4369            return false;4370        }4371 4372        return true;4373      }4374 4375      // Walk the MemberExpr chain.4376      while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {4377        const auto *ME1 = cast<MemberExpr>(E1);4378        const auto *ME2 = cast<MemberExpr>(E2);4379        if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))4380          return false;4381        if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))4382          if (D->isStaticDataMember())4383            return true;4384        E1 = ME1->getBase()->IgnoreParenImpCasts();4385        E2 = ME2->getBase()->IgnoreParenImpCasts();4386      }4387 4388      if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))4389        return true;4390 4391      // A static member variable can end the MemberExpr chain with either4392      // a MemberExpr or a DeclRefExpr.4393      auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {4394        if (const auto *DRE = dyn_cast<DeclRefExpr>(E))4395          return DRE->getDecl();4396        if (const auto *ME = dyn_cast<MemberExpr>(E))4397          return ME->getMemberDecl();4398        return nullptr;4399      };4400 4401      const ValueDecl *VD1 = getAnyDecl(E1);4402      const ValueDecl *VD2 = getAnyDecl(E2);4403      return declaresSameEntity(VD1, VD2);4404    }4405  }4406}4407 4408/// isArrow - Return true if the base expression is a pointer to vector,4409/// return false if the base expression is a vector.4410bool ExtVectorElementExpr::isArrow() const {4411  return getBase()->getType()->isPointerType();4412}4413 4414unsigned ExtVectorElementExpr::getNumElements() const {4415  if (const VectorType *VT = getType()->getAs<VectorType>())4416    return VT->getNumElements();4417  return 1;4418}4419 4420/// containsDuplicateElements - Return true if any element access is repeated.4421bool ExtVectorElementExpr::containsDuplicateElements() const {4422  // FIXME: Refactor this code to an accessor on the AST node which returns the4423  // "type" of component access, and share with code below and in Sema.4424  StringRef Comp = Accessor->getName();4425 4426  // Halving swizzles do not contain duplicate elements.4427  if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")4428    return false;4429 4430  // Advance past s-char prefix on hex swizzles.4431  if (Comp[0] == 's' || Comp[0] == 'S')4432    Comp = Comp.substr(1);4433 4434  for (unsigned i = 0, e = Comp.size(); i != e; ++i)4435    if (Comp.substr(i + 1).contains(Comp[i]))4436        return true;4437 4438  return false;4439}4440 4441/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.4442void ExtVectorElementExpr::getEncodedElementAccess(4443    SmallVectorImpl<uint32_t> &Elts) const {4444  StringRef Comp = Accessor->getName();4445  bool isNumericAccessor = false;4446  if (Comp[0] == 's' || Comp[0] == 'S') {4447    Comp = Comp.substr(1);4448    isNumericAccessor = true;4449  }4450 4451  bool isHi =   Comp == "hi";4452  bool isLo =   Comp == "lo";4453  bool isEven = Comp == "even";4454  bool isOdd  = Comp == "odd";4455 4456  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {4457    uint64_t Index;4458 4459    if (isHi)4460      Index = e + i;4461    else if (isLo)4462      Index = i;4463    else if (isEven)4464      Index = 2 * i;4465    else if (isOdd)4466      Index = 2 * i + 1;4467    else4468      Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);4469 4470    Elts.push_back(Index);4471  }4472}4473 4474ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,4475                                     QualType Type, SourceLocation BLoc,4476                                     SourceLocation RP)4477    : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),4478      BuiltinLoc(BLoc), RParenLoc(RP) {4479  ShuffleVectorExprBits.NumExprs = args.size();4480  SubExprs = new (C) Stmt*[args.size()];4481  for (unsigned i = 0; i != args.size(); i++)4482    SubExprs[i] = args[i];4483 4484  setDependence(computeDependence(this));4485}4486 4487void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {4488  if (SubExprs) C.Deallocate(SubExprs);4489 4490  this->ShuffleVectorExprBits.NumExprs = Exprs.size();4491  SubExprs = new (C) Stmt *[ShuffleVectorExprBits.NumExprs];4492  llvm::copy(Exprs, SubExprs);4493}4494 4495GenericSelectionExpr::GenericSelectionExpr(4496    const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,4497    ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,4498    SourceLocation DefaultLoc, SourceLocation RParenLoc,4499    bool ContainsUnexpandedParameterPack, unsigned ResultIndex)4500    : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),4501           AssocExprs[ResultIndex]->getValueKind(),4502           AssocExprs[ResultIndex]->getObjectKind()),4503      NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),4504      IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {4505  assert(AssocTypes.size() == AssocExprs.size() &&4506         "Must have the same number of association expressions"4507         " and TypeSourceInfo!");4508  assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");4509 4510  GenericSelectionExprBits.GenericLoc = GenericLoc;4511  getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =4512      ControllingExpr;4513  llvm::copy(AssocExprs,4514             getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());4515  llvm::copy(AssocTypes, getTrailingObjects<TypeSourceInfo *>() +4516                             getIndexOfStartOfAssociatedTypes());4517 4518  setDependence(computeDependence(this, ContainsUnexpandedParameterPack));4519}4520 4521GenericSelectionExpr::GenericSelectionExpr(4522    const ASTContext &, SourceLocation GenericLoc,4523    TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,4524    ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,4525    SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,4526    unsigned ResultIndex)4527    : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),4528           AssocExprs[ResultIndex]->getValueKind(),4529           AssocExprs[ResultIndex]->getObjectKind()),4530      NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),4531      IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {4532  assert(AssocTypes.size() == AssocExprs.size() &&4533         "Must have the same number of association expressions"4534         " and TypeSourceInfo!");4535  assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");4536 4537  GenericSelectionExprBits.GenericLoc = GenericLoc;4538  getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =4539      ControllingType;4540  llvm::copy(AssocExprs,4541             getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());4542  llvm::copy(AssocTypes, getTrailingObjects<TypeSourceInfo *>() +4543                             getIndexOfStartOfAssociatedTypes());4544 4545  setDependence(computeDependence(this, ContainsUnexpandedParameterPack));4546}4547 4548GenericSelectionExpr::GenericSelectionExpr(4549    const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,4550    ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,4551    SourceLocation DefaultLoc, SourceLocation RParenLoc,4552    bool ContainsUnexpandedParameterPack)4553    : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,4554           OK_Ordinary),4555      NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),4556      IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {4557  assert(AssocTypes.size() == AssocExprs.size() &&4558         "Must have the same number of association expressions"4559         " and TypeSourceInfo!");4560 4561  GenericSelectionExprBits.GenericLoc = GenericLoc;4562  getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =4563      ControllingExpr;4564  llvm::copy(AssocExprs,4565             getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());4566  llvm::copy(AssocTypes, getTrailingObjects<TypeSourceInfo *>() +4567                             getIndexOfStartOfAssociatedTypes());4568 4569  setDependence(computeDependence(this, ContainsUnexpandedParameterPack));4570}4571 4572GenericSelectionExpr::GenericSelectionExpr(4573    const ASTContext &Context, SourceLocation GenericLoc,4574    TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,4575    ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,4576    SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack)4577    : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,4578           OK_Ordinary),4579      NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),4580      IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {4581  assert(AssocTypes.size() == AssocExprs.size() &&4582         "Must have the same number of association expressions"4583         " and TypeSourceInfo!");4584 4585  GenericSelectionExprBits.GenericLoc = GenericLoc;4586  getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =4587      ControllingType;4588  llvm::copy(AssocExprs,4589             getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());4590  llvm::copy(AssocTypes, getTrailingObjects<TypeSourceInfo *>() +4591                             getIndexOfStartOfAssociatedTypes());4592 4593  setDependence(computeDependence(this, ContainsUnexpandedParameterPack));4594}4595 4596GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)4597    : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}4598 4599GenericSelectionExpr *GenericSelectionExpr::Create(4600    const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,4601    ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,4602    SourceLocation DefaultLoc, SourceLocation RParenLoc,4603    bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {4604  unsigned NumAssocs = AssocExprs.size();4605  void *Mem = Context.Allocate(4606      totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),4607      alignof(GenericSelectionExpr));4608  return new (Mem) GenericSelectionExpr(4609      Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,4610      RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);4611}4612 4613GenericSelectionExpr *GenericSelectionExpr::Create(4614    const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,4615    ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,4616    SourceLocation DefaultLoc, SourceLocation RParenLoc,4617    bool ContainsUnexpandedParameterPack) {4618  unsigned NumAssocs = AssocExprs.size();4619  void *Mem = Context.Allocate(4620      totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),4621      alignof(GenericSelectionExpr));4622  return new (Mem) GenericSelectionExpr(4623      Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,4624      RParenLoc, ContainsUnexpandedParameterPack);4625}4626 4627GenericSelectionExpr *GenericSelectionExpr::Create(4628    const ASTContext &Context, SourceLocation GenericLoc,4629    TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,4630    ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,4631    SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,4632    unsigned ResultIndex) {4633  unsigned NumAssocs = AssocExprs.size();4634  void *Mem = Context.Allocate(4635      totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),4636      alignof(GenericSelectionExpr));4637  return new (Mem) GenericSelectionExpr(4638      Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,4639      RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);4640}4641 4642GenericSelectionExpr *GenericSelectionExpr::Create(4643    const ASTContext &Context, SourceLocation GenericLoc,4644    TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,4645    ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,4646    SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) {4647  unsigned NumAssocs = AssocExprs.size();4648  void *Mem = Context.Allocate(4649      totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),4650      alignof(GenericSelectionExpr));4651  return new (Mem) GenericSelectionExpr(4652      Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,4653      RParenLoc, ContainsUnexpandedParameterPack);4654}4655 4656GenericSelectionExpr *4657GenericSelectionExpr::CreateEmpty(const ASTContext &Context,4658                                  unsigned NumAssocs) {4659  void *Mem = Context.Allocate(4660      totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),4661      alignof(GenericSelectionExpr));4662  return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);4663}4664 4665//===----------------------------------------------------------------------===//4666//  DesignatedInitExpr4667//===----------------------------------------------------------------------===//4668 4669const IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {4670  assert(isFieldDesignator() && "Only valid on a field designator");4671  if (FieldInfo.NameOrField & 0x01)4672    return reinterpret_cast<IdentifierInfo *>(FieldInfo.NameOrField & ~0x01);4673  return getFieldDecl()->getIdentifier();4674}4675 4676DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,4677                                       ArrayRef<Designator> Designators,4678                                       SourceLocation EqualOrColonLoc,4679                                       bool GNUSyntax,4680                                       ArrayRef<Expr *> IndexExprs, Expr *Init)4681    : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),4682           Init->getObjectKind()),4683      EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),4684      NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {4685  this->Designators = new (C) Designator[NumDesignators];4686 4687  // Record the initializer itself.4688  child_iterator Child = child_begin();4689  *Child++ = Init;4690 4691  // Copy the designators and their subexpressions, computing4692  // value-dependence along the way.4693  unsigned IndexIdx = 0;4694  for (unsigned I = 0; I != NumDesignators; ++I) {4695    this->Designators[I] = Designators[I];4696    if (this->Designators[I].isArrayDesignator()) {4697      // Copy the index expressions into permanent storage.4698      *Child++ = IndexExprs[IndexIdx++];4699    } else if (this->Designators[I].isArrayRangeDesignator()) {4700      // Copy the start/end expressions into permanent storage.4701      *Child++ = IndexExprs[IndexIdx++];4702      *Child++ = IndexExprs[IndexIdx++];4703    }4704  }4705 4706  assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");4707  setDependence(computeDependence(this));4708}4709 4710DesignatedInitExpr *DesignatedInitExpr::Create(const ASTContext &C,4711                                               ArrayRef<Designator> Designators,4712                                               ArrayRef<Expr *> IndexExprs,4713                                               SourceLocation ColonOrEqualLoc,4714                                               bool UsesColonSyntax,4715                                               Expr *Init) {4716  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),4717                         alignof(DesignatedInitExpr));4718  return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,4719                                      ColonOrEqualLoc, UsesColonSyntax,4720                                      IndexExprs, Init);4721}4722 4723DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,4724                                                    unsigned NumIndexExprs) {4725  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),4726                         alignof(DesignatedInitExpr));4727  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);4728}4729 4730void DesignatedInitExpr::setDesignators(const ASTContext &C,4731                                        const Designator *Desigs,4732                                        unsigned NumDesigs) {4733  Designators = new (C) Designator[NumDesigs];4734  NumDesignators = NumDesigs;4735  for (unsigned I = 0; I != NumDesigs; ++I)4736    Designators[I] = Desigs[I];4737}4738 4739SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {4740  DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);4741  if (size() == 1)4742    return DIE->getDesignator(0)->getSourceRange();4743  return SourceRange(DIE->getDesignator(0)->getBeginLoc(),4744                     DIE->getDesignator(size() - 1)->getEndLoc());4745}4746 4747SourceLocation DesignatedInitExpr::getBeginLoc() const {4748  auto *DIE = const_cast<DesignatedInitExpr *>(this);4749  Designator &First = *DIE->getDesignator(0);4750  if (First.isFieldDesignator()) {4751    // Skip past implicit designators for anonymous structs/unions, since4752    // these do not have valid source locations.4753    for (unsigned int i = 0; i < DIE->size(); i++) {4754      Designator &Des = *DIE->getDesignator(i);4755      SourceLocation retval = GNUSyntax ? Des.getFieldLoc() : Des.getDotLoc();4756      if (!retval.isValid())4757        continue;4758      return retval;4759    }4760  }4761  return First.getLBracketLoc();4762}4763 4764SourceLocation DesignatedInitExpr::getEndLoc() const {4765  return getInit()->getEndLoc();4766}4767 4768Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {4769  assert(D.isArrayDesignator() && "Requires array designator");4770  return getSubExpr(D.getArrayIndex() + 1);4771}4772 4773Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {4774  assert(D.isArrayRangeDesignator() && "Requires array range designator");4775  return getSubExpr(D.getArrayIndex() + 1);4776}4777 4778Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {4779  assert(D.isArrayRangeDesignator() && "Requires array range designator");4780  return getSubExpr(D.getArrayIndex() + 2);4781}4782 4783/// Replaces the designator at index @p Idx with the series4784/// of designators in [First, Last).4785void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,4786                                          const Designator *First,4787                                          const Designator *Last) {4788  unsigned NumNewDesignators = Last - First;4789  if (NumNewDesignators == 0) {4790    std::copy_backward(Designators + Idx + 1,4791                       Designators + NumDesignators,4792                       Designators + Idx);4793    --NumNewDesignators;4794    return;4795  }4796  if (NumNewDesignators == 1) {4797    Designators[Idx] = *First;4798    return;4799  }4800 4801  Designator *NewDesignators4802    = new (C) Designator[NumDesignators - 1 + NumNewDesignators];4803  std::copy(Designators, Designators + Idx, NewDesignators);4804  std::copy(First, Last, NewDesignators + Idx);4805  std::copy(Designators + Idx + 1, Designators + NumDesignators,4806            NewDesignators + Idx + NumNewDesignators);4807  Designators = NewDesignators;4808  NumDesignators = NumDesignators - 1 + NumNewDesignators;4809}4810 4811DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,4812                                                   SourceLocation lBraceLoc,4813                                                   Expr *baseExpr,4814                                                   SourceLocation rBraceLoc)4815    : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,4816           OK_Ordinary) {4817  BaseAndUpdaterExprs[0] = baseExpr;4818 4819  InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, {}, rBraceLoc);4820  ILE->setType(baseExpr->getType());4821  BaseAndUpdaterExprs[1] = ILE;4822 4823  // FIXME: this is wrong, set it correctly.4824  setDependence(ExprDependence::None);4825}4826 4827SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {4828  return getBase()->getBeginLoc();4829}4830 4831SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {4832  return getBase()->getEndLoc();4833}4834 4835ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,4836                             SourceLocation RParenLoc)4837    : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),4838      LParenLoc(LParenLoc), RParenLoc(RParenLoc) {4839  ParenListExprBits.NumExprs = Exprs.size();4840  llvm::copy(Exprs, getTrailingObjects());4841  setDependence(computeDependence(this));4842}4843 4844ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)4845    : Expr(ParenListExprClass, Empty) {4846  ParenListExprBits.NumExprs = NumExprs;4847}4848 4849ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,4850                                     SourceLocation LParenLoc,4851                                     ArrayRef<Expr *> Exprs,4852                                     SourceLocation RParenLoc) {4853  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),4854                           alignof(ParenListExpr));4855  return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);4856}4857 4858ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,4859                                          unsigned NumExprs) {4860  void *Mem =4861      Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));4862  return new (Mem) ParenListExpr(EmptyShell(), NumExprs);4863}4864 4865/// Certain overflow-dependent code patterns can have their integer overflow4866/// sanitization disabled. Check for the common pattern `if (a + b < a)` and4867/// return the resulting BinaryOperator responsible for the addition so we can4868/// elide overflow checks during codegen.4869static std::optional<BinaryOperator *>4870getOverflowPatternBinOp(const BinaryOperator *E) {4871  Expr *Addition, *ComparedTo;4872  if (E->getOpcode() == BO_LT) {4873    Addition = E->getLHS();4874    ComparedTo = E->getRHS();4875  } else if (E->getOpcode() == BO_GT) {4876    Addition = E->getRHS();4877    ComparedTo = E->getLHS();4878  } else {4879    return {};4880  }4881 4882  const Expr *AddLHS = nullptr, *AddRHS = nullptr;4883  BinaryOperator *BO = dyn_cast<BinaryOperator>(Addition);4884 4885  if (BO && BO->getOpcode() == clang::BO_Add) {4886    // now store addends for lookup on other side of '>'4887    AddLHS = BO->getLHS();4888    AddRHS = BO->getRHS();4889  }4890 4891  if (!AddLHS || !AddRHS)4892    return {};4893 4894  const Decl *LHSDecl, *RHSDecl, *OtherDecl;4895 4896  LHSDecl = AddLHS->IgnoreParenImpCasts()->getReferencedDeclOfCallee();4897  RHSDecl = AddRHS->IgnoreParenImpCasts()->getReferencedDeclOfCallee();4898  OtherDecl = ComparedTo->IgnoreParenImpCasts()->getReferencedDeclOfCallee();4899 4900  if (!OtherDecl)4901    return {};4902 4903  if (!LHSDecl && !RHSDecl)4904    return {};4905 4906  if ((LHSDecl && LHSDecl == OtherDecl && LHSDecl != RHSDecl) ||4907      (RHSDecl && RHSDecl == OtherDecl && RHSDecl != LHSDecl))4908    return BO;4909  return {};4910}4911 4912/// Compute and set the OverflowPatternExclusion bit based on whether the4913/// BinaryOperator expression matches an overflow pattern being ignored by4914/// -fsanitize-undefined-ignore-overflow-pattern=add-signed-overflow-test or4915/// -fsanitize-undefined-ignore-overflow-pattern=add-unsigned-overflow-test4916static void computeOverflowPatternExclusion(const ASTContext &Ctx,4917                                            const BinaryOperator *E) {4918  std::optional<BinaryOperator *> Result = getOverflowPatternBinOp(E);4919  if (!Result.has_value())4920    return;4921  QualType AdditionResultType = Result.value()->getType();4922 4923  if ((AdditionResultType->isSignedIntegerType() &&4924       Ctx.getLangOpts().isOverflowPatternExcluded(4925           LangOptions::OverflowPatternExclusionKind::AddSignedOverflowTest)) ||4926      (AdditionResultType->isUnsignedIntegerType() &&4927       Ctx.getLangOpts().isOverflowPatternExcluded(4928           LangOptions::OverflowPatternExclusionKind::AddUnsignedOverflowTest)))4929    Result.value()->setExcludedOverflowPattern(true);4930}4931 4932BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,4933                               Opcode opc, QualType ResTy, ExprValueKind VK,4934                               ExprObjectKind OK, SourceLocation opLoc,4935                               FPOptionsOverride FPFeatures)4936    : Expr(BinaryOperatorClass, ResTy, VK, OK) {4937  BinaryOperatorBits.Opc = opc;4938  assert(!isCompoundAssignmentOp() &&4939         "Use CompoundAssignOperator for compound assignments");4940  BinaryOperatorBits.OpLoc = opLoc;4941  BinaryOperatorBits.ExcludedOverflowPattern = false;4942  SubExprs[LHS] = lhs;4943  SubExprs[RHS] = rhs;4944  computeOverflowPatternExclusion(Ctx, this);4945  BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();4946  if (hasStoredFPFeatures())4947    setStoredFPFeatures(FPFeatures);4948  setDependence(computeDependence(this));4949}4950 4951BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,4952                               Opcode opc, QualType ResTy, ExprValueKind VK,4953                               ExprObjectKind OK, SourceLocation opLoc,4954                               FPOptionsOverride FPFeatures, bool dead2)4955    : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {4956  BinaryOperatorBits.Opc = opc;4957  BinaryOperatorBits.ExcludedOverflowPattern = false;4958  assert(isCompoundAssignmentOp() &&4959         "Use CompoundAssignOperator for compound assignments");4960  BinaryOperatorBits.OpLoc = opLoc;4961  SubExprs[LHS] = lhs;4962  SubExprs[RHS] = rhs;4963  BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();4964  if (hasStoredFPFeatures())4965    setStoredFPFeatures(FPFeatures);4966  setDependence(computeDependence(this));4967}4968 4969BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,4970                                            bool HasFPFeatures) {4971  unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);4972  void *Mem =4973      C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));4974  return new (Mem) BinaryOperator(EmptyShell());4975}4976 4977BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs,4978                                       Expr *rhs, Opcode opc, QualType ResTy,4979                                       ExprValueKind VK, ExprObjectKind OK,4980                                       SourceLocation opLoc,4981                                       FPOptionsOverride FPFeatures) {4982  bool HasFPFeatures = FPFeatures.requiresTrailingStorage();4983  unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);4984  void *Mem =4985      C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));4986  return new (Mem)4987      BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);4988}4989 4990CompoundAssignOperator *4991CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {4992  unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);4993  void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,4994                         alignof(CompoundAssignOperator));4995  return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);4996}4997 4998CompoundAssignOperator *4999CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs,5000                               Opcode opc, QualType ResTy, ExprValueKind VK,5001                               ExprObjectKind OK, SourceLocation opLoc,5002                               FPOptionsOverride FPFeatures,5003                               QualType CompLHSType, QualType CompResultType) {5004  bool HasFPFeatures = FPFeatures.requiresTrailingStorage();5005  unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);5006  void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,5007                         alignof(CompoundAssignOperator));5008  return new (Mem)5009      CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,5010                             CompLHSType, CompResultType);5011}5012 5013UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C,5014                                          bool hasFPFeatures) {5015  void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),5016                         alignof(UnaryOperator));5017  return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());5018}5019 5020UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc,5021                             QualType type, ExprValueKind VK, ExprObjectKind OK,5022                             SourceLocation l, bool CanOverflow,5023                             FPOptionsOverride FPFeatures)5024    : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {5025  UnaryOperatorBits.Opc = opc;5026  UnaryOperatorBits.CanOverflow = CanOverflow;5027  UnaryOperatorBits.Loc = l;5028  UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();5029  if (hasStoredFPFeatures())5030    setStoredFPFeatures(FPFeatures);5031  setDependence(computeDependence(this, Ctx));5032}5033 5034UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input,5035                                     Opcode opc, QualType type,5036                                     ExprValueKind VK, ExprObjectKind OK,5037                                     SourceLocation l, bool CanOverflow,5038                                     FPOptionsOverride FPFeatures) {5039  bool HasFPFeatures = FPFeatures.requiresTrailingStorage();5040  unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);5041  void *Mem = C.Allocate(Size, alignof(UnaryOperator));5042  return new (Mem)5043      UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);5044}5045 5046const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {5047  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))5048    e = ewc->getSubExpr();5049  if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))5050    e = m->getSubExpr();5051  e = cast<CXXConstructExpr>(e)->getArg(0);5052  while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))5053    e = ice->getSubExpr();5054  return cast<OpaqueValueExpr>(e);5055}5056 5057PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,5058                                           EmptyShell sh,5059                                           unsigned numSemanticExprs) {5060  void *buffer =5061      Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),5062                       alignof(PseudoObjectExpr));5063  return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);5064}5065 5066PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)5067  : Expr(PseudoObjectExprClass, shell) {5068  PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;5069}5070 5071PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,5072                                           ArrayRef<Expr*> semantics,5073                                           unsigned resultIndex) {5074  assert(syntax && "no syntactic expression!");5075  assert(semantics.size() && "no semantic expressions!");5076 5077  QualType type;5078  ExprValueKind VK;5079  if (resultIndex == NoResult) {5080    type = C.VoidTy;5081    VK = VK_PRValue;5082  } else {5083    assert(resultIndex < semantics.size());5084    type = semantics[resultIndex]->getType();5085    VK = semantics[resultIndex]->getValueKind();5086    assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);5087  }5088 5089  void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),5090                            alignof(PseudoObjectExpr));5091  return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,5092                                      resultIndex);5093}5094 5095PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,5096                                   Expr *syntax, ArrayRef<Expr *> semantics,5097                                   unsigned resultIndex)5098    : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {5099  PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;5100  PseudoObjectExprBits.ResultIndex = resultIndex + 1;5101  MutableArrayRef<Expr *> Trail = getTrailingObjects(semantics.size() + 1);5102  Trail[0] = syntax;5103 5104  assert(llvm::all_of(semantics,5105                      [](const Expr *E) {5106                        return !isa<OpaqueValueExpr>(E) ||5107                               cast<OpaqueValueExpr>(E)->getSourceExpr() !=5108                                   nullptr;5109                      }) &&5110         "opaque-value semantic expressions for pseudo-object "5111         "operations must have sources");5112 5113  llvm::copy(semantics, Trail.drop_front().begin());5114  setDependence(computeDependence(this));5115}5116 5117//===----------------------------------------------------------------------===//5118//  Child Iterators for iterating over subexpressions/substatements5119//===----------------------------------------------------------------------===//5120 5121// UnaryExprOrTypeTraitExpr5122Stmt::child_range UnaryExprOrTypeTraitExpr::children() {5123  const_child_range CCR =5124      const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();5125  return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));5126}5127 5128Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {5129  // If this is of a type and the type is a VLA type (and not a typedef), the5130  // size expression of the VLA needs to be treated as an executable expression.5131  // Why isn't this weirdness documented better in StmtIterator?5132  if (isArgumentType()) {5133    if (const VariableArrayType *T =5134            dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))5135      return const_child_range(const_child_iterator(T), const_child_iterator());5136    return const_child_range(const_child_iterator(), const_child_iterator());5137  }5138  return const_child_range(&Argument.Ex, &Argument.Ex + 1);5139}5140 5141AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,5142                       AtomicOp op, SourceLocation RP)5143    : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),5144      NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {5145  assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");5146  for (unsigned i = 0; i != args.size(); i++)5147    SubExprs[i] = args[i];5148  setDependence(computeDependence(this));5149}5150 5151unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {5152  switch (Op) {5153  case AO__c11_atomic_init:5154  case AO__opencl_atomic_init:5155  case AO__c11_atomic_load:5156  case AO__atomic_load_n:5157  case AO__atomic_test_and_set:5158  case AO__atomic_clear:5159    return 2;5160 5161  case AO__scoped_atomic_load_n:5162  case AO__opencl_atomic_load:5163  case AO__hip_atomic_load:5164  case AO__c11_atomic_store:5165  case AO__c11_atomic_exchange:5166  case AO__atomic_load:5167  case AO__atomic_store:5168  case AO__atomic_store_n:5169  case AO__atomic_exchange_n:5170  case AO__c11_atomic_fetch_add:5171  case AO__c11_atomic_fetch_sub:5172  case AO__c11_atomic_fetch_and:5173  case AO__c11_atomic_fetch_or:5174  case AO__c11_atomic_fetch_xor:5175  case AO__c11_atomic_fetch_nand:5176  case AO__c11_atomic_fetch_max:5177  case AO__c11_atomic_fetch_min:5178  case AO__atomic_fetch_add:5179  case AO__atomic_fetch_sub:5180  case AO__atomic_fetch_and:5181  case AO__atomic_fetch_or:5182  case AO__atomic_fetch_xor:5183  case AO__atomic_fetch_nand:5184  case AO__atomic_add_fetch:5185  case AO__atomic_sub_fetch:5186  case AO__atomic_and_fetch:5187  case AO__atomic_or_fetch:5188  case AO__atomic_xor_fetch:5189  case AO__atomic_nand_fetch:5190  case AO__atomic_min_fetch:5191  case AO__atomic_max_fetch:5192  case AO__atomic_fetch_min:5193  case AO__atomic_fetch_max:5194    return 3;5195 5196  case AO__scoped_atomic_load:5197  case AO__scoped_atomic_store:5198  case AO__scoped_atomic_store_n:5199  case AO__scoped_atomic_fetch_add:5200  case AO__scoped_atomic_fetch_sub:5201  case AO__scoped_atomic_fetch_and:5202  case AO__scoped_atomic_fetch_or:5203  case AO__scoped_atomic_fetch_xor:5204  case AO__scoped_atomic_fetch_nand:5205  case AO__scoped_atomic_add_fetch:5206  case AO__scoped_atomic_sub_fetch:5207  case AO__scoped_atomic_and_fetch:5208  case AO__scoped_atomic_or_fetch:5209  case AO__scoped_atomic_xor_fetch:5210  case AO__scoped_atomic_nand_fetch:5211  case AO__scoped_atomic_min_fetch:5212  case AO__scoped_atomic_max_fetch:5213  case AO__scoped_atomic_fetch_min:5214  case AO__scoped_atomic_fetch_max:5215  case AO__scoped_atomic_exchange_n:5216  case AO__scoped_atomic_uinc_wrap:5217  case AO__scoped_atomic_udec_wrap:5218  case AO__hip_atomic_exchange:5219  case AO__hip_atomic_fetch_add:5220  case AO__hip_atomic_fetch_sub:5221  case AO__hip_atomic_fetch_and:5222  case AO__hip_atomic_fetch_or:5223  case AO__hip_atomic_fetch_xor:5224  case AO__hip_atomic_fetch_min:5225  case AO__hip_atomic_fetch_max:5226  case AO__opencl_atomic_store:5227  case AO__hip_atomic_store:5228  case AO__opencl_atomic_exchange:5229  case AO__opencl_atomic_fetch_add:5230  case AO__opencl_atomic_fetch_sub:5231  case AO__opencl_atomic_fetch_and:5232  case AO__opencl_atomic_fetch_or:5233  case AO__opencl_atomic_fetch_xor:5234  case AO__opencl_atomic_fetch_min:5235  case AO__opencl_atomic_fetch_max:5236  case AO__atomic_exchange:5237    return 4;5238 5239  case AO__scoped_atomic_exchange:5240  case AO__c11_atomic_compare_exchange_strong:5241  case AO__c11_atomic_compare_exchange_weak:5242    return 5;5243  case AO__hip_atomic_compare_exchange_strong:5244  case AO__opencl_atomic_compare_exchange_strong:5245  case AO__opencl_atomic_compare_exchange_weak:5246  case AO__hip_atomic_compare_exchange_weak:5247  case AO__atomic_compare_exchange:5248  case AO__atomic_compare_exchange_n:5249    return 6;5250 5251  case AO__scoped_atomic_compare_exchange:5252  case AO__scoped_atomic_compare_exchange_n:5253    return 7;5254  }5255  llvm_unreachable("unknown atomic op");5256}5257 5258QualType AtomicExpr::getValueType() const {5259  auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();5260  if (auto AT = T->getAs<AtomicType>())5261    return AT->getValueType();5262  return T;5263}5264 5265QualType ArraySectionExpr::getBaseOriginalType(const Expr *Base) {5266  unsigned ArraySectionCount = 0;5267  while (auto *OASE = dyn_cast<ArraySectionExpr>(Base->IgnoreParens())) {5268    Base = OASE->getBase();5269    ++ArraySectionCount;5270  }5271  while (auto *ASE =5272             dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {5273    Base = ASE->getBase();5274    ++ArraySectionCount;5275  }5276  Base = Base->IgnoreParenImpCasts();5277  auto OriginalTy = Base->getType();5278  if (auto *DRE = dyn_cast<DeclRefExpr>(Base))5279    if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))5280      OriginalTy = PVD->getOriginalType().getNonReferenceType();5281 5282  for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {5283    if (OriginalTy->isAnyPointerType())5284      OriginalTy = OriginalTy->getPointeeType();5285    else if (OriginalTy->isArrayType())5286      OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();5287    else5288      return {};5289  }5290  return OriginalTy;5291}5292 5293QualType ArraySectionExpr::getElementType() const {5294  QualType BaseTy = getBase()->IgnoreParenImpCasts()->getType();5295  // We only have to look into the array section exprs, else we will get the5296  // type of the base, which should already be valid.5297  if (auto *ASE = dyn_cast<ArraySectionExpr>(getBase()->IgnoreParenImpCasts()))5298    BaseTy = ASE->getElementType();5299 5300  if (BaseTy->isAnyPointerType())5301    return BaseTy->getPointeeType();5302  if (BaseTy->isArrayType())5303    return BaseTy->castAsArrayTypeUnsafe()->getElementType();5304 5305  // If this isn't a pointer or array, the base is a dependent expression, so5306  // just return the BaseTy anyway.5307  assert(BaseTy->isInstantiationDependentType());5308  return BaseTy;5309}5310 5311QualType ArraySectionExpr::getBaseType() const {5312  // We only have to look into the array section exprs, else we will get the5313  // type of the base, which should already be valid.5314  if (auto *ASE = dyn_cast<ArraySectionExpr>(getBase()->IgnoreParenImpCasts()))5315    return ASE->getElementType();5316 5317  return getBase()->IgnoreParenImpCasts()->getType();5318}5319 5320RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,5321                           SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)5322    : Expr(RecoveryExprClass, T.getNonReferenceType(),5323           T->isDependentType() ? VK_LValue : getValueKindForType(T),5324           OK_Ordinary),5325      BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {5326  assert(!T.isNull());5327  assert(!llvm::is_contained(SubExprs, nullptr));5328 5329  llvm::copy(SubExprs, getTrailingObjects());5330  setDependence(computeDependence(this));5331}5332 5333RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T,5334                                   SourceLocation BeginLoc,5335                                   SourceLocation EndLoc,5336                                   ArrayRef<Expr *> SubExprs) {5337  void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),5338                           alignof(RecoveryExpr));5339  return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);5340}5341 5342RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {5343  void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),5344                           alignof(RecoveryExpr));5345  return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);5346}5347 5348void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {5349  assert(5350      NumDims == Dims.size() &&5351      "Preallocated number of dimensions is different from the provided one.");5352  llvm::copy(Dims, getTrailingObjects<Expr *>());5353}5354 5355void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {5356  assert(5357      NumDims == BR.size() &&5358      "Preallocated number of dimensions is different from the provided one.");5359  llvm::copy(BR, getTrailingObjects<SourceRange>());5360}5361 5362OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,5363                                         SourceLocation L, SourceLocation R,5364                                         ArrayRef<Expr *> Dims)5365    : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),5366      RPLoc(R), NumDims(Dims.size()) {5367  setBase(Op);5368  setDimensions(Dims);5369  setDependence(computeDependence(this));5370}5371 5372OMPArrayShapingExpr *5373OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op,5374                            SourceLocation L, SourceLocation R,5375                            ArrayRef<Expr *> Dims,5376                            ArrayRef<SourceRange> BracketRanges) {5377  assert(Dims.size() == BracketRanges.size() &&5378         "Different number of dimensions and brackets ranges.");5379  void *Mem = Context.Allocate(5380      totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),5381      alignof(OMPArrayShapingExpr));5382  auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);5383  E->setBracketsRanges(BracketRanges);5384  return E;5385}5386 5387OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,5388                                                      unsigned NumDims) {5389  void *Mem = Context.Allocate(5390      totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),5391      alignof(OMPArrayShapingExpr));5392  return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);5393}5394 5395void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {5396  getTrailingObjects<Decl *>(NumIterators)[I] = D;5397}5398 5399void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {5400  assert(I < NumIterators &&5401         "Idx is greater or equal the number of iterators definitions.");5402  getTrailingObjects<5403      SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +5404                        static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;5405}5406 5407void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,5408                                       SourceLocation ColonLoc, Expr *End,5409                                       SourceLocation SecondColonLoc,5410                                       Expr *Step) {5411  assert(I < NumIterators &&5412         "Idx is greater or equal the number of iterators definitions.");5413  getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +5414                               static_cast<int>(RangeExprOffset::Begin)] =5415      Begin;5416  getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +5417                               static_cast<int>(RangeExprOffset::End)] = End;5418  getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +5419                               static_cast<int>(RangeExprOffset::Step)] = Step;5420  getTrailingObjects<5421      SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +5422                        static_cast<int>(RangeLocOffset::FirstColonLoc)] =5423      ColonLoc;5424  getTrailingObjects<5425      SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +5426                        static_cast<int>(RangeLocOffset::SecondColonLoc)] =5427      SecondColonLoc;5428}5429 5430Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) {5431  return getTrailingObjects<Decl *>()[I];5432}5433 5434OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) {5435  IteratorRange Res;5436  Res.Begin =5437      getTrailingObjects<Expr *>()[I * static_cast<int>(5438                                           RangeExprOffset::Total) +5439                                   static_cast<int>(RangeExprOffset::Begin)];5440  Res.End =5441      getTrailingObjects<Expr *>()[I * static_cast<int>(5442                                           RangeExprOffset::Total) +5443                                   static_cast<int>(RangeExprOffset::End)];5444  Res.Step =5445      getTrailingObjects<Expr *>()[I * static_cast<int>(5446                                           RangeExprOffset::Total) +5447                                   static_cast<int>(RangeExprOffset::Step)];5448  return Res;5449}5450 5451SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const {5452  return getTrailingObjects<5453      SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +5454                        static_cast<int>(RangeLocOffset::AssignLoc)];5455}5456 5457SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const {5458  return getTrailingObjects<5459      SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +5460                        static_cast<int>(RangeLocOffset::FirstColonLoc)];5461}5462 5463SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const {5464  return getTrailingObjects<5465      SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +5466                        static_cast<int>(RangeLocOffset::SecondColonLoc)];5467}5468 5469void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {5470  getTrailingObjects<OMPIteratorHelperData>()[I] = D;5471}5472 5473OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) {5474  return getTrailingObjects<OMPIteratorHelperData>()[I];5475}5476 5477const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const {5478  return getTrailingObjects<OMPIteratorHelperData>()[I];5479}5480 5481OMPIteratorExpr::OMPIteratorExpr(5482    QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,5483    SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,5484    ArrayRef<OMPIteratorHelperData> Helpers)5485    : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),5486      IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),5487      NumIterators(Data.size()) {5488  for (unsigned I = 0, E = Data.size(); I < E; ++I) {5489    const IteratorDefinition &D = Data[I];5490    setIteratorDeclaration(I, D.IteratorDecl);5491    setAssignmentLoc(I, D.AssignmentLoc);5492    setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,5493                     D.SecondColonLoc, D.Range.Step);5494    setHelper(I, Helpers[I]);5495  }5496  setDependence(computeDependence(this));5497}5498 5499OMPIteratorExpr *5500OMPIteratorExpr::Create(const ASTContext &Context, QualType T,5501                        SourceLocation IteratorKwLoc, SourceLocation L,5502                        SourceLocation R,5503                        ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,5504                        ArrayRef<OMPIteratorHelperData> Helpers) {5505  assert(Data.size() == Helpers.size() &&5506         "Data and helpers must have the same size.");5507  void *Mem = Context.Allocate(5508      totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(5509          Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),5510          Data.size() * static_cast<int>(RangeLocOffset::Total),5511          Helpers.size()),5512      alignof(OMPIteratorExpr));5513  return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);5514}5515 5516OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,5517                                              unsigned NumIterators) {5518  void *Mem = Context.Allocate(5519      totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(5520          NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),5521          NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),5522      alignof(OMPIteratorExpr));5523  return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);5524}5525 5526HLSLOutArgExpr *HLSLOutArgExpr::Create(const ASTContext &C, QualType Ty,5527                                       OpaqueValueExpr *Base,5528                                       OpaqueValueExpr *OpV, Expr *WB,5529                                       bool IsInOut) {5530  return new (C) HLSLOutArgExpr(Ty, Base, OpV, WB, IsInOut);5531}5532 5533HLSLOutArgExpr *HLSLOutArgExpr::CreateEmpty(const ASTContext &C) {5534  return new (C) HLSLOutArgExpr(EmptyShell());5535}5536 5537OpenACCAsteriskSizeExpr *OpenACCAsteriskSizeExpr::Create(const ASTContext &C,5538                                                         SourceLocation Loc) {5539  return new (C) OpenACCAsteriskSizeExpr(Loc, C.IntTy);5540}5541 5542OpenACCAsteriskSizeExpr *5543OpenACCAsteriskSizeExpr::CreateEmpty(const ASTContext &C) {5544  return new (C) OpenACCAsteriskSizeExpr({}, C.IntTy);5545}5546 5547ConvertVectorExpr *ConvertVectorExpr::CreateEmpty(const ASTContext &C,5548                                                  bool hasFPFeatures) {5549  void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),5550                         alignof(ConvertVectorExpr));5551  return new (Mem) ConvertVectorExpr(hasFPFeatures, EmptyShell());5552}5553 5554ConvertVectorExpr *ConvertVectorExpr::Create(5555    const ASTContext &C, Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,5556    ExprValueKind VK, ExprObjectKind OK, SourceLocation BuiltinLoc,5557    SourceLocation RParenLoc, FPOptionsOverride FPFeatures) {5558  bool HasFPFeatures = FPFeatures.requiresTrailingStorage();5559  unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);5560  void *Mem = C.Allocate(Size, alignof(ConvertVectorExpr));5561  return new (Mem) ConvertVectorExpr(SrcExpr, TI, DstType, VK, OK, BuiltinLoc,5562                                     RParenLoc, FPFeatures);5563}5564 5565APValue &CompoundLiteralExpr::getOrCreateStaticValue(ASTContext &Ctx) const {5566  assert(hasStaticStorage());5567  if (!StaticValue) {5568    StaticValue = new (Ctx) APValue;5569    Ctx.addDestruction(StaticValue);5570  }5571  return *StaticValue;5572}5573 5574APValue &CompoundLiteralExpr::getStaticValue() const {5575  assert(StaticValue);5576  return *StaticValue;5577}5578