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