1d874057dim//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2d874057dim//
3d874057dim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4d874057dim// See https://llvm.org/LICENSE.txt for license information.
5d874057dim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d874057dim//
7d874057dim//===----------------------------------------------------------------------===//
8d874057dim//
9d874057dim// This file implements the Expr class and subclasses.
10d874057dim//
11d874057dim//===----------------------------------------------------------------------===//
12d874057dim
13d874057dim#include "clang/AST/Expr.h"
14d874057dim#include "clang/AST/APValue.h"
15d874057dim#include "clang/AST/ASTContext.h"
16d874057dim#include "clang/AST/Attr.h"
17d874057dim#include "clang/AST/DeclCXX.h"
18d874057dim#include "clang/AST/DeclObjC.h"
19d874057dim#include "clang/AST/DeclTemplate.h"
20d874057dim#include "clang/AST/EvaluatedExprVisitor.h"
21d874057dim#include "clang/AST/ExprCXX.h"
22d874057dim#include "clang/AST/Mangle.h"
23d874057dim#include "clang/AST/RecordLayout.h"
24d874057dim#include "clang/AST/StmtVisitor.h"
25d874057dim#include "clang/Basic/Builtins.h"
26d874057dim#include "clang/Basic/CharInfo.h"
27d874057dim#include "clang/Basic/SourceManager.h"
28d874057dim#include "clang/Basic/TargetInfo.h"
29d874057dim#include "clang/Lex/Lexer.h"
30d874057dim#include "clang/Lex/LiteralSupport.h"
31d874057dim#include "llvm/Support/ErrorHandling.h"
32d874057dim#include "llvm/Support/raw_ostream.h"
33d874057dim#include <algorithm>
34d874057dim#include <cstring>
35d874057dimusing namespace clang;
36d874057dim
37d874057dimconst Expr *Expr::getBestDynamicClassTypeExpr() const {
38d874057dim  const Expr *E = this;
39d874057dim  while (true) {
40d874057dim    E = E->ignoreParenBaseCasts();
41d874057dim
42d874057dim    // Follow the RHS of a comma operator.
43d874057dim    if (auto *BO = dyn_cast<BinaryOperator>(E)) {
44d874057dim      if (BO->getOpcode() == BO_Comma) {
45d874057dim        E = BO->getRHS();
46d874057dim        continue;
47d874057dim      }
48d874057dim    }
49d874057dim
50d874057dim    // Step into initializer for materialized temporaries.
51d874057dim    if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
52332da66dim      E = MTE->getSubExpr();
53d874057dim      continue;
54d874057dim    }
55d874057dim
56d874057dim    break;
57d874057dim  }
58d874057dim
59d874057dim  return E;
60d874057dim}
61d874057dim
62d874057dimconst CXXRecordDecl *Expr::getBestDynamicClassType() const {
63d874057dim  const Expr *E = getBestDynamicClassTypeExpr();
64d874057dim  QualType DerivedType = E->getType();
65d874057dim  if (const PointerType *PTy = DerivedType->getAs<PointerType>())
66d874057dim    DerivedType = PTy->getPointeeType();
67d874057dim
68d874057dim  if (DerivedType->isDependentType())
69d874057dim    return nullptr;
70d874057dim
71d874057dim  const RecordType *Ty = DerivedType->castAs<RecordType>();
72d874057dim  Decl *D = Ty->getDecl();
73d874057dim  return cast<CXXRecordDecl>(D);
74d874057dim}
75d874057dim
76d874057dimconst Expr *Expr::skipRValueSubobjectAdjustments(
77d874057dim    SmallVectorImpl<const Expr *> &CommaLHSs,
78d874057dim    SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
79d874057dim  const Expr *E = this;
80d874057dim  while (true) {
81d874057dim    E = E->IgnoreParens();
82d874057dim
83d874057dim    if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
84d874057dim      if ((CE->getCastKind() == CK_DerivedToBase ||
85d874057dim           CE->getCastKind() == CK_UncheckedDerivedToBase) &&
86d874057dim          E->getType()->isRecordType()) {
87d874057dim        E = CE->getSubExpr();
88d874057dim        auto *Derived =
89d874057dim            cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
90d874057dim        Adjustments.push_back(SubobjectAdjustment(CE, Derived));
91d874057dim        continue;
92d874057dim      }
93d874057dim
94d874057dim      if (CE->getCastKind() == CK_NoOp) {
95d874057dim        E = CE->getSubExpr();
96d874057dim        continue;
97d874057dim      }
98d874057dim    } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
99d874057dim      if (!ME->isArrow()) {
100d874057dim        assert(ME->getBase()->getType()->isRecordType());
101d874057dim        if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
102d874057dim          if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
103d874057dim            E = ME->getBase();
104d874057dim            Adjustments.push_back(SubobjectAdjustment(Field));
105d874057dim            continue;
106d874057dim          }
107d874057dim        }
108d874057dim      }
109d874057dim    } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
110d874057dim      if (BO->getOpcode() == BO_PtrMemD) {
111d874057dim        assert(BO->getRHS()->isRValue());
112d874057dim        E = BO->getLHS();
113d874057dim        const MemberPointerType *MPT =
114d874057dim          BO->getRHS()->getType()->getAs<MemberPointerType>();
115d874057dim        Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
116d874057dim        continue;
117d874057dim      } else if (BO->getOpcode() == BO_Comma) {
118d874057dim        CommaLHSs.push_back(BO->getLHS());
119d874057dim        E = BO->getRHS();
120d874057dim        continue;
121d874057dim      }
122d874057dim    }
123d874057dim
124d874057dim    // Nothing changed.
125d874057dim    break;
126d874057dim  }
127d874057dim  return E;
128d874057dim}
129d874057dim
130332da66dimbool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
131d874057dim  const Expr *E = IgnoreParens();
132d874057dim
133d874057dim  // If this value has _Bool type, it is obvious 0/1.
134d874057dim  if (E->getType()->isBooleanType()) return true;
135d874057dim  // If this is a non-scalar-integer type, we don't care enough to try.
136d874057dim  if (!E->getType()->isIntegralOrEnumerationType()) return false;
137d874057dim
138d874057dim  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
139d874057dim    switch (UO->getOpcode()) {
140d874057dim    case UO_Plus:
141332da66dim      return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
142d874057dim    case UO_LNot:
143d874057dim      return true;
144d874057dim    default:
145d874057dim      return false;
146d874057dim    }
147d874057dim  }
148d874057dim
149d874057dim  // Only look through implicit casts.  If the user writes
150d874057dim  // '(int) (a && b)' treat it as an arbitrary int.
151332da66dim  // FIXME: Should we look through any cast expression in !Semantic mode?
152d874057dim  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
153332da66dim    return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
154d874057dim
155d874057dim  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
156d874057dim    switch (BO->getOpcode()) {
157d874057dim    default: return false;
158d874057dim    case BO_LT:   // Relational operators.
159d874057dim    case BO_GT:
160d874057dim    case BO_LE:
161d874057dim    case BO_GE:
162d874057dim    case BO_EQ:   // Equality operators.
163d874057dim    case BO_NE:
164d874057dim    case BO_LAnd: // AND operator.
165d874057dim    case BO_LOr:  // Logical OR operator.
166d874057dim      return true;
167d874057dim
168d874057dim    case BO_And:  // Bitwise AND operator.
169d874057dim    case BO_Xor:  // Bitwise XOR operator.
170d874057dim    case BO_Or:   // Bitwise OR operator.
171d874057dim      // Handle things like (x==2)|(y==12).
172332da66dim      return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
173332da66dim             BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
174d874057dim
175d874057dim    case BO_Comma:
176d874057dim    case BO_Assign:
177332da66dim      return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
178d874057dim    }
179d874057dim  }
180d874057dim
181d874057dim  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
182332da66dim    return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
183332da66dim           CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
184d874057dim
185d874057dim  if (isa<ObjCBoolLiteralExpr>(E))
186d874057dim    return true;
187d874057dim
188d874057dim  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
189332da66dim    return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
190332da66dim
191332da66dim  if (const FieldDecl *FD = E->getSourceBitField())
192332da66dim    if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
193332da66dim        !FD->getBitWidth()->isValueDependent() &&
194332da66dim        FD->getBitWidthValue(FD->getASTContext()) == 1)
195332da66dim      return true;
196d874057dim
197d874057dim  return false;
198d874057dim}
199d874057dim
200d874057dim// Amusing macro metaprogramming hack: check whether a class provides
201d874057dim// a more specific implementation of getExprLoc().
202d874057dim//
203d874057dim// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
204d874057dimnamespace {
205d874057dim  /// This implementation is used when a class provides a custom
206d874057dim  /// implementation of getExprLoc.
207d874057dim  template <class E, class T>
208d874057dim  SourceLocation getExprLocImpl(const Expr *expr,
209d874057dim                                SourceLocation (T::*v)() const) {
210d874057dim    return static_cast<const E*>(expr)->getExprLoc();
211d874057dim  }
212d874057dim
213d874057dim  /// This implementation is used when a class doesn't provide
214d874057dim  /// a custom implementation of getExprLoc.  Overload resolution
215d874057dim  /// should pick it over the implementation above because it's
216d874057dim  /// more specialized according to function template partial ordering.
217d874057dim  template <class E>
218d874057dim  SourceLocation getExprLocImpl(const Expr *expr,
219d874057dim                                SourceLocation (Expr::*v)() const) {
220d874057dim    return static_cast<const E *>(expr)->getBeginLoc();
221d874057dim  }
222d874057dim}
223d874057dim
224d874057dimSourceLocation Expr::getExprLoc() const {
225d874057dim  switch (getStmtClass()) {
226d874057dim  case Stmt::NoStmtClass: llvm_unreachable("statement without class");
227d874057dim#define ABSTRACT_STMT(type)
228d874057dim#define STMT(type, base) \
229d874057dim  case Stmt::type##Class: break;
230d874057dim#define EXPR(type, base) \
231d874057dim  case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
232d874057dim#include "clang/AST/StmtNodes.inc"
233d874057dim  }
234d874057dim  llvm_unreachable("unknown expression kind");
235d874057dim}
236d874057dim
237d874057dim//===----------------------------------------------------------------------===//
238d874057dim// Primary Expressions.
239d874057dim//===----------------------------------------------------------------------===//
240d874057dim
241d874057dimstatic void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind) {
242d874057dim  assert((Kind == ConstantExpr::RSK_APValue ||
243d874057dim          Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) &&
244d874057dim         "Invalid StorageKind Value");
245d874057dim}
246d874057dim
247d874057dimConstantExpr::ResultStorageKind
248d874057dimConstantExpr::getStorageKind(const APValue &Value) {
249d874057dim  switch (Value.getKind()) {
250d874057dim  case APValue::None:
251d874057dim  case APValue::Indeterminate:
252d874057dim    return ConstantExpr::RSK_None;
253d874057dim  case APValue::Int:
254d874057dim    if (!Value.getInt().needsCleanup())
255d874057dim      return ConstantExpr::RSK_Int64;
256d874057dim    LLVM_FALLTHROUGH;
257d874057dim  default:
258d874057dim    return ConstantExpr::RSK_APValue;
259d874057dim  }
260d874057dim}
261d874057dim
262d874057dimConstantExpr::ResultStorageKind
263d874057dimConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
264d874057dim  if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
265d874057dim    return ConstantExpr::RSK_Int64;
266d874057dim  return ConstantExpr::RSK_APValue;
267d874057dim}
268d874057dim
269d874057dimvoid ConstantExpr::DefaultInit(ResultStorageKind StorageKind) {
270d874057dim  ConstantExprBits.ResultKind = StorageKind;
271d874057dim  ConstantExprBits.APValueKind = APValue::None;
272d874057dim  ConstantExprBits.HasCleanup = false;
273d874057dim  if (StorageKind == ConstantExpr::RSK_APValue)
274d874057dim    ::new (getTrailingObjects<APValue>()) APValue();
275d874057dim}
276d874057dim
277d874057dimConstantExpr::ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind)
278d874057dim    : FullExpr(ConstantExprClass, subexpr) {
279d874057dim  DefaultInit(StorageKind);
280d874057dim}
281d874057dim
282d874057dimConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
283d874057dim                                   ResultStorageKind StorageKind) {
284d874057dim  assert(!isa<ConstantExpr>(E));
285d874057dim  AssertResultStorageKind(StorageKind);
286d874057dim  unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
287d874057dim      StorageKind == ConstantExpr::RSK_APValue,
288d874057dim      StorageKind == ConstantExpr::RSK_Int64);
289d874057dim  void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
290d874057dim  ConstantExpr *Self = new (Mem) ConstantExpr(E, StorageKind);
291d874057dim  return Self;
292d874057dim}
293d874057dim
294d874057dimConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
295d874057dim                                   const APValue &Result) {
296d874057dim  ResultStorageKind StorageKind = getStorageKind(Result);
297d874057dim  ConstantExpr *Self = Create(Context, E, StorageKind);
298d874057dim  Self->SetResult(Result, Context);
299d874057dim  return Self;
300d874057dim}
301d874057dim
302d874057dimConstantExpr::ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty)
303d874057dim    : FullExpr(ConstantExprClass, Empty) {
304d874057dim  DefaultInit(StorageKind);
305d874057dim}
306d874057dim
307d874057dimConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
308d874057dim                                        ResultStorageKind StorageKind,
309d874057dim                                        EmptyShell Empty) {
310d874057dim  AssertResultStorageKind(StorageKind);
311d874057dim  unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
312d874057dim      StorageKind == ConstantExpr::RSK_APValue,
313d874057dim      StorageKind == ConstantExpr::RSK_Int64);
314d874057dim  void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
315d874057dim  ConstantExpr *Self = new (Mem) ConstantExpr(StorageKind, Empty);
316d874057dim  return Self;
317d874057dim}
318d874057dim
319d874057dimvoid ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
320d874057dim  assert(getStorageKind(Value) == ConstantExprBits.ResultKind &&
321d874057dim         "Invalid storage for this value kind");
322d874057dim  ConstantExprBits.APValueKind = Value.getKind();
323d874057dim  switch (ConstantExprBits.ResultKind) {
324d874057dim  case RSK_None:
325d874057dim    return;
326d874057dim  case RSK_Int64:
327d874057dim    Int64Result() = *Value.getInt().getRawData();
328d874057dim    ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
329d874057dim    ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
330d874057dim    return;
331d874057dim  case RSK_APValue:
332d874057dim    if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
333d874057dim      ConstantExprBits.HasCleanup = true;
334d874057dim      Context.addDestruction(&APValueResult());
335d874057dim    }
336d874057dim    APValueResult() = std::move(Value);
337d874057dim    return;
338d874057dim  }
339d874057dim  llvm_unreachable("Invalid ResultKind Bits");
340d874057dim}
341d874057dim
342d874057dimllvm::APSInt ConstantExpr::getResultAsAPSInt() const {
343d874057dim  switch (ConstantExprBits.ResultKind) {
344d874057dim  case ConstantExpr::RSK_APValue:
345d874057dim    return APValueResult().getInt();
346d874057dim  case ConstantExpr::RSK_Int64:
347d874057dim    return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
348d874057dim                        ConstantExprBits.IsUnsigned);
349d874057dim  default:
350d874057dim    llvm_unreachable("invalid Accessor");
351d874057dim  }
352d874057dim}
353d874057dim
354d874057dimAPValue ConstantExpr::getAPValueResult() const {
355d874057dim  switch (ConstantExprBits.ResultKind) {
356d874057dim  case ConstantExpr::RSK_APValue:
357d874057dim    return APValueResult();
358d874057dim  case ConstantExpr::RSK_Int64:
359d874057dim    return APValue(
360d874057dim        llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
361d874057dim                     ConstantExprBits.IsUnsigned));
362d874057dim  case ConstantExpr::RSK_None:
363d874057dim    return APValue();
364d874057dim  }
365d874057dim  llvm_unreachable("invalid ResultKind");
366d874057dim}
367d874057dim
368d874057dim/// Compute the type-, value-, and instantiation-dependence of a
369d874057dim/// declaration reference
370d874057dim/// based on the declaration being referenced.
371d874057dimstatic void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
372d874057dim                                     QualType T, bool &TypeDependent,
373d874057dim                                     bool &ValueDependent,
374d874057dim                                     bool &InstantiationDependent) {
375d874057dim  TypeDependent = false;
376d874057dim  ValueDependent = false;
377d874057dim  InstantiationDependent = false;
378d874057dim
379d874057dim  // (TD) C++ [temp.dep.expr]p3:
380d874057dim  //   An id-expression is type-dependent if it contains:
381d874057dim  //
382d874057dim  // and
383d874057dim  //
384d874057dim  // (VD) C++ [temp.dep.constexpr]p2:
385d874057dim  //  An identifier is value-dependent if it is:
386d874057dim
387d874057dim  //  (TD)  - an identifier that was declared with dependent type
388d874057dim  //  (VD)  - a name declared with a dependent type,
389d874057dim  if (T->isDependentType()) {
390d874057dim    TypeDependent = true;
391d874057dim    ValueDependent = true;
392d874057dim    InstantiationDependent = true;
393d874057dim    return;
394d874057dim  } else if (T->isInstantiationDependentType()) {
395d874057dim    InstantiationDependent = true;
396d874057dim  }
397d874057dim
398d874057dim  //  (TD)  - a conversion-function-id that specifies a dependent type
399d874057dim  if (D->getDeclName().getNameKind()
400d874057dim                                == DeclarationName::CXXConversionFunctionName) {
401d874057dim    QualType T = D->getDeclName().getCXXNameType();
402d874057dim    if (T->isDependentType()) {
403d874057dim      TypeDependent = true;
404d874057dim      ValueDependent = true;
405d874057dim      InstantiationDependent = true;
406d874057dim      return;
407d874057dim    }
408d874057dim
409d874057dim    if (T->isInstantiationDependentType())
410d874057dim      InstantiationDependent = true;
411d874057dim  }
412d874057dim
413d874057dim  //  (VD)  - the name of a non-type template parameter,
414d874057dim  if (isa<NonTypeTemplateParmDecl>(D)) {
415d874057dim    ValueDependent = true;
416d874057dim    InstantiationDependent = true;
417d874057dim    return;
418d874057dim  }
419d874057dim
420d874057dim  //  (VD) - a constant with integral or enumeration type and is
421d874057dim  //         initialized with an expression that is value-dependent.
422d874057dim  //  (VD) - a constant with literal type and is initialized with an
423d874057dim  //         expression that is value-dependent [C++11].
424d874057dim  //  (VD) - FIXME: Missing from the standard:
425d874057dim  //       -  an entity with reference type and is initialized with an
426d874057dim  //          expression that is value-dependent [C++11]
427d874057dim  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
428d874057dim    if ((Ctx.getLangOpts().CPlusPlus11 ?
429d874057dim           Var->getType()->isLiteralType(Ctx) :
430d874057dim           Var->getType()->isIntegralOrEnumerationType()) &&
431d874057dim        (Var->getType().isConstQualified() ||
432d874057dim         Var->getType()->isReferenceType())) {
433d874057dim      if (const Expr *Init = Var->getAnyInitializer())
434d874057dim        if (Init->isValueDependent()) {
435d874057dim          ValueDependent = true;
436d874057dim          InstantiationDependent = true;
437d874057dim        }
438d874057dim    }
439d874057dim
440d874057dim    // (VD) - FIXME: Missing from the standard:
441d874057dim    //      -  a member function or a static data member of the current
442d874057dim    //         instantiation
443d874057dim    if (Var->isStaticDataMember() &&
444d874057dim        Var->getDeclContext()->isDependentContext()) {
445d874057dim      ValueDependent = true;
446d874057dim      InstantiationDependent = true;
447d874057dim      TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
448d874057dim      if (TInfo->getType()->isIncompleteArrayType())
449d874057dim        TypeDependent = true;
450d874057dim    }
451d874057dim
452d874057dim    return;
453d874057dim  }
454d874057dim
455d874057dim  // (VD) - FIXME: Missing from the standard:
456d874057dim  //      -  a member function or a static data member of the current
457d874057dim  //         instantiation
458d874057dim  if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
459d874057dim    ValueDependent = true;
460d874057dim    InstantiationDependent = true;
461d874057dim  }
462d874057dim}
463d874057dim
464d874057dimvoid DeclRefExpr::computeDependence(const ASTContext &Ctx) {
465d874057dim  bool TypeDependent = false;
466d874057dim  bool ValueDependent = false;
467d874057dim  bool InstantiationDependent = false;
468d874057dim  computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
469d874057dim                           ValueDependent, InstantiationDependent);
470d874057dim
471d874057dim  ExprBits.TypeDependent |= TypeDependent;
472d874057dim  ExprBits.ValueDependent |= ValueDependent;
473d874057dim  ExprBits.InstantiationDependent |= InstantiationDependent;
474d874057dim
475d874057dim  // Is the declaration a parameter pack?
476d874057dim  if (getDecl()->isParameterPack())
477d874057dim    ExprBits.ContainsUnexpandedParameterPack = true;
478d874057dim}
479d874057dim
480d874057dimDeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
481d874057dim                         bool RefersToEnclosingVariableOrCapture, QualType T,
482d874057dim                         ExprValueKind VK, SourceLocation L,
483d874057dim                         const DeclarationNameLoc &LocInfo,
484d874057dim                         NonOdrUseReason NOUR)
485d874057dim    : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
486d874057dim      D(D), DNLoc(LocInfo) {
487d874057dim  DeclRefExprBits.HasQualifier = false;
488d874057dim  DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
489d874057dim  DeclRefExprBits.HasFoundDecl = false;
490d874057dim  DeclRefExprBits.HadMultipleCandidates = false;
491d874057dim  DeclRefExprBits.RefersToEnclosingVariableOrCapture =
492d874057dim      RefersToEnclosingVariableOrCapture;
493d874057dim  DeclRefExprBits.NonOdrUseReason = NOUR;
494d874057dim  DeclRefExprBits.Loc = L;
495d874057dim  computeDependence(Ctx);
496d874057dim}
497d874057dim
498d874057dimDeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
499d874057dim                         NestedNameSpecifierLoc QualifierLoc,
500d874057dim                         SourceLocation TemplateKWLoc, ValueDecl *D,
501d874057dim                         bool RefersToEnclosingVariableOrCapture,
502d874057dim                         const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
503d874057dim                         const TemplateArgumentListInfo *TemplateArgs,
504d874057dim                         QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
505d874057dim    : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
506d874057dim      D(D), DNLoc(NameInfo.getInfo()) {
507d874057dim  DeclRefExprBits.Loc = NameInfo.getLoc();
508d874057dim  DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
509d874057dim  if (QualifierLoc) {
510d874057dim    new (getTrailingObjects<NestedNameSpecifierLoc>())
511d874057dim        NestedNameSpecifierLoc(QualifierLoc);
512d874057dim    auto *NNS = QualifierLoc.getNestedNameSpecifier();
513d874057dim    if (NNS->isInstantiationDependent())
514d874057dim      ExprBits.InstantiationDependent = true;
515d874057dim    if (NNS->containsUnexpandedParameterPack())
516d874057dim      ExprBits.ContainsUnexpandedParameterPack = true;
517d874057dim  }
518d874057dim  DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
519d874057dim  if (FoundD)
520d874057dim    *getTrailingObjects<NamedDecl *>() = FoundD;
521d874057dim  DeclRefExprBits.HasTemplateKWAndArgsInfo
522d874057dim    = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
523d874057dim  DeclRefExprBits.RefersToEnclosingVariableOrCapture =
524d874057dim      RefersToEnclosingVariableOrCapture;
525d874057dim  DeclRefExprBits.NonOdrUseReason = NOUR;
526d874057dim  if (TemplateArgs) {
527d874057dim    bool Dependent = false;
528d874057dim    bool InstantiationDependent = false;
529d874057dim    bool ContainsUnexpandedParameterPack = false;
530d874057dim    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
531d874057dim        TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
532d874057dim        Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
533d874057dim    assert(!Dependent && "built a DeclRefExpr with dependent template args");
534d874057dim    ExprBits.InstantiationDependent |= InstantiationDependent;
535d874057dim    ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
536d874057dim  } else if (TemplateKWLoc.isValid()) {
537d874057dim    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
538d874057dim        TemplateKWLoc);
539d874057dim  }
540d874057dim  DeclRefExprBits.HadMultipleCandidates = 0;
541d874057dim
542d874057dim  computeDependence(Ctx);
543d874057dim}
544d874057dim
545d874057dimDeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
546d874057dim                                 NestedNameSpecifierLoc QualifierLoc,
547d874057dim                                 SourceLocation TemplateKWLoc, ValueDecl *D,
548d874057dim                                 bool RefersToEnclosingVariableOrCapture,
549d874057dim                                 SourceLocation NameLoc, QualType T,
550d874057dim                                 ExprValueKind VK, NamedDecl *FoundD,
551d874057dim                                 const TemplateArgumentListInfo *TemplateArgs,
552d874057dim                                 NonOdrUseReason NOUR) {
553d874057dim  return Create(Context, QualifierLoc, TemplateKWLoc, D,
554d874057dim                RefersToEnclosingVariableOrCapture,
555d874057dim                DeclarationNameInfo(D->getDeclName(), NameLoc),
556d874057dim                T, VK, FoundD, TemplateArgs, NOUR);
557d874057dim}
558d874057dim
559d874057dimDeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
560d874057dim                                 NestedNameSpecifierLoc QualifierLoc,
561d874057dim                                 SourceLocation TemplateKWLoc, ValueDecl *D,
562d874057dim                                 bool RefersToEnclosingVariableOrCapture,
563d874057dim                                 const DeclarationNameInfo &NameInfo,
564d874057dim                                 QualType T, ExprValueKind VK,
565d874057dim                                 NamedDecl *FoundD,
566d874057dim                                 const TemplateArgumentListInfo *TemplateArgs,
567d874057dim                                 NonOdrUseReason NOUR) {
568d874057dim  // Filter out cases where the found Decl is the same as the value refenenced.
569d874057dim  if (D == FoundD)
570d874057dim    FoundD = nullptr;
571d874057dim
572d874057dim  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
573d874057dim  std::size_t Size =
574d874057dim      totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
575d874057dim                       ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
576d874057dim          QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
577d874057dim          HasTemplateKWAndArgsInfo ? 1 : 0,
578d874057dim          TemplateArgs ? TemplateArgs->size() : 0);
579d874057dim
580d874057dim  void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
581d874057dim  return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
582d874057dim                               RefersToEnclosingVariableOrCapture, NameInfo,
583d874057dim                               FoundD, TemplateArgs, T, VK, NOUR);
584d874057dim}
585d874057dim
586d874057dimDeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
587d874057dim                                      bool HasQualifier,
588d874057dim                                      bool HasFoundDecl,
589d874057dim                                      bool HasTemplateKWAndArgsInfo,
590d874057dim                                      unsigned NumTemplateArgs) {
591d874057dim  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
592d874057dim  std::size_t Size =
593d874057dim      totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
594d874057dim                       ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
595d874057dim          HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
596d874057dim          NumTemplateArgs);
597d874057dim  void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
598d874057dim  return new (Mem) DeclRefExpr(EmptyShell());
599d874057dim}
600d874057dim
601d874057dimSourceLocation DeclRefExpr::getBeginLoc() const {
602d874057dim  if (hasQualifier())
603d874057dim    return getQualifierLoc().getBeginLoc();
604d874057dim  return getNameInfo().getBeginLoc();
605d874057dim}
606d874057dimSourceLocation DeclRefExpr::getEndLoc() const {
607d874057dim  if (hasExplicitTemplateArgs())
608d874057dim    return getRAngleLoc();
609d874057dim  return getNameInfo().getEndLoc();
610d874057dim}
611d874057dim
612d874057dimPredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
613d874057dim                               StringLiteral *SL)
614d874057dim    : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
615d874057dim           FNTy->isDependentType(), FNTy->isDependentType(),
616d874057dim           FNTy->isInstantiationDependentType(),
617d874057dim           /*ContainsUnexpandedParameterPack=*/false) {
618d874057dim  PredefinedExprBits.Kind = IK;
619d874057dim  assert((getIdentKind() == IK) &&
620d874057dim         "IdentKind do not fit in PredefinedExprBitfields!");
621d874057dim  bool HasFunctionName = SL != nullptr;
622d874057dim  PredefinedExprBits.HasFunctionName = HasFunctionName;
623d874057dim  PredefinedExprBits.Loc = L;
624d874057dim  if (HasFunctionName)
625d874057dim    setFunctionName(SL);
626d874057dim}
627d874057dim
628d874057dimPredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
629d874057dim    : Expr(PredefinedExprClass, Empty) {
630d874057dim  PredefinedExprBits.HasFunctionName = HasFunctionName;
631d874057dim}
632d874057dim
633d874057dimPredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
634d874057dim                                       QualType FNTy, IdentKind IK,
635d874057dim                                       StringLiteral *SL) {
636d874057dim  bool HasFunctionName = SL != nullptr;
637d874057dim  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
638d874057dim                           alignof(PredefinedExpr));
639d874057dim  return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
640d874057dim}
641d874057dim
642d874057dimPredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
643d874057dim                                            bool HasFunctionName) {
644d874057dim  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
645d874057dim                           alignof(PredefinedExpr));
646d874057dim  return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
647d874057dim}
648d874057dim
649d874057dimStringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
650d874057dim  switch (IK) {
651d874057dim  case Func:
652d874057dim    return "__func__";
653d874057dim  case Function:
654d874057dim    return "__FUNCTION__";
655d874057dim  case FuncDName:
656d874057dim    return "__FUNCDNAME__";
657d874057dim  case LFunction:
658d874057dim    return "L__FUNCTION__";
659d874057dim  case PrettyFunction:
660d874057dim    return "__PRETTY_FUNCTION__";
661d874057dim  case FuncSig:
662d874057dim    return "__FUNCSIG__";
663d874057dim  case LFuncSig:
664d874057dim    return "L__FUNCSIG__";
665d874057dim  case PrettyFunctionNoVirtual:
666d874057dim    break;
667d874057dim  }
668d874057dim  llvm_unreachable("Unknown ident kind for PredefinedExpr");
669d874057dim}
670d874057dim
671d874057dim// FIXME: Maybe this should use DeclPrinter with a special "print predefined
672d874057dim// expr" policy instead.
673d874057dimstd::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
674d874057dim  ASTContext &Context = CurrentDecl->getASTContext();
675d874057dim
676d874057dim  if (IK == PredefinedExpr::FuncDName) {
677d874057dim    if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
678d874057dim      std::unique_ptr<MangleContext> MC;
679d874057dim      MC.reset(Context.createMangleContext());
680d874057dim
681d874057dim      if (MC->shouldMangleDeclName(ND)) {
682d874057dim        SmallString<256> Buffer;
683d874057dim        llvm::raw_svector_ostream Out(Buffer);
684d874057dim        if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
685d874057dim          MC->mangleCXXCtor(CD, Ctor_Base, Out);
686d874057dim        else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
687d874057dim          MC->mangleCXXDtor(DD, Dtor_Base, Out);
688d874057dim        else
689d874057dim          MC->mangleName(ND, Out);
690d874057dim
691d874057dim        if (!Buffer.empty() && Buffer.front() == '\01')
692d874057dim          return Buffer.substr(1);
693d874057dim        return Buffer.str();
694d874057dim      } else
695d874057dim        return ND->getIdentifier()->getName();
696d874057dim    }
697d874057dim    return "";
698d874057dim  }
699d874057dim  if (isa<BlockDecl>(CurrentDecl)) {
700d874057dim    // For blocks we only emit something if it is enclosed in a function
701d874057dim    // For top-level block we'd like to include the name of variable, but we
702d874057dim    // don't have it at this point.
703d874057dim    auto DC = CurrentDecl->getDeclContext();
704d874057dim    if (DC->isFileContext())
705d874057dim      return "";
706d874057dim
707d874057dim    SmallString<256> Buffer;
708d874057dim    llvm::raw_svector_ostream Out(Buffer);
709d874057dim    if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
710d874057dim      // For nested blocks, propagate up to the parent.
711d874057dim      Out << ComputeName(IK, DCBlock);
712d874057dim    else if (auto *DCDecl = dyn_cast<Decl>(DC))
713d874057dim      Out << ComputeName(IK, DCDecl) << "_block_invoke";
714d874057dim    return Out.str();
715d874057dim  }
716d874057dim  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
717d874057dim    if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
718d874057dim        IK != FuncSig && IK != LFuncSig)
719d874057dim      return FD->getNameAsString();
720d874057dim
721d874057dim    SmallString<256> Name;
722d874057dim    llvm::raw_svector_ostream Out(Name);
723d874057dim
724d874057dim    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
725d874057dim      if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
726d874057dim        Out << "virtual ";
727d874057dim      if (MD->isStatic())
728d874057dim        Out << "static ";
729d874057dim    }
730d874057dim
731d874057dim    PrintingPolicy Policy(Context.getLangOpts());
732d874057dim    std::string Proto;
733d874057dim    llvm::raw_string_ostream POut(Proto);
734d874057dim
735d874057dim    const FunctionDecl *Decl = FD;
736d874057dim    if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
737d874057dim      Decl = Pattern;
738d874057dim    const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
739d874057dim    const FunctionProtoType *FT = nullptr;
740d874057dim    if (FD->hasWrittenPrototype())
741d874057dim      FT = dyn_cast<FunctionProtoType>(AFT);
742d874057dim
743d874057dim    if (IK == FuncSig || IK == LFuncSig) {
744d874057dim      switch (AFT->getCallConv()) {
745d874057dim      case CC_C: POut << "__cdecl "; break;
746d874057dim      case CC_X86StdCall: POut << "__stdcall "; break;
747d874057dim      case CC_X86FastCall: POut << "__fastcall "; break;
748d874057dim      case CC_X86ThisCall: POut << "__thiscall "; break;
749d874057dim      case CC_X86VectorCall: POut << "__vectorcall "; break;
750d874057dim      case CC_X86RegCall: POut << "__regcall "; break;
751d874057dim      // Only bother printing the conventions that MSVC knows about.
752d874057dim      default: break;
753d874057dim      }
754d874057dim    }
755d874057dim
756d874057dim    FD->printQualifiedName(POut, Policy);
757d874057dim
758d874057dim    POut << "(";
759d874057dim    if (FT) {
760d874057dim      for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
761d874057dim        if (i) POut << ", ";
762d874057dim        POut << Decl->getParamDecl(i)->getType().stream(Policy);
763d874057dim      }
764d874057dim
765d874057dim      if (FT->isVariadic()) {
766d874057dim        if (FD->getNumParams()) POut << ", ";
767d874057dim        POut << "...";
768d874057dim      } else if ((IK == FuncSig || IK == LFuncSig ||
769d874057dim                  !Context.getLangOpts().CPlusPlus) &&
770d874057dim                 !Decl->getNumParams()) {
771d874057dim        POut << "void";
772d874057dim      }
773d874057dim    }
774d874057dim    POut << ")";
775d874057dim
776d874057dim    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
777d874057dim      assert(FT && "We must have a written prototype in this case.");
778d874057dim      if (FT->isConst())
779d874057dim        POut << " const";
780d874057dim      if (FT->isVolatile())
781d874057dim        POut << " volatile";
782d874057dim      RefQualifierKind Ref = MD->getRefQualifier();
783d874057dim      if (Ref == RQ_LValue)
784d874057dim        POut << " &";
785d874057dim      else if (Ref == RQ_RValue)
786d874057dim        POut << " &&";
787d874057dim    }
788d874057dim
789d874057dim    typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
790d874057dim    SpecsTy Specs;
791d874057dim    const DeclContext *Ctx = FD->getDeclContext();
792d874057dim    while (Ctx && isa<NamedDecl>(Ctx)) {
793d874057dim      const ClassTemplateSpecializationDecl *Spec
794d874057dim                               = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
795d874057dim      if (Spec && !Spec->isExplicitSpecialization())
796d874057dim        Specs.push_back(Spec);
797d874057dim      Ctx = Ctx->getParent();
798d874057dim    }
799d874057dim
800d874057dim    std::string TemplateParams;
801d874057dim    llvm::raw_string_ostream TOut(TemplateParams);
802d874057dim    for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
803d874057dim         I != E; ++I) {
804d874057dim      const TemplateParameterList *Params
805d874057dim                  = (*I)->getSpecializedTemplate()->getTemplateParameters();
806d874057dim      const TemplateArgumentList &Args = (*I)->getTemplateArgs();
807d874057dim      assert(Params->size() == Args.size());
808d874057dim      for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
809d874057dim        StringRef Param = Params->getParam(i)->getName();
810d874057dim        if (Param.empty()) continue;
811d874057dim        TOut << Param << " = ";
812d874057dim        Args.get(i).print(Policy, TOut);
813d874057dim        TOut << ", ";
814d874057dim      }
815d874057dim    }
816d874057dim
817d874057dim    FunctionTemplateSpecializationInfo *FSI
818d874057dim                                          = FD->getTemplateSpecializationInfo();
819d874057dim    if (FSI && !FSI->isExplicitSpecialization()) {
820d874057dim      const TemplateParameterList* Params
821d874057dim                                  = FSI->getTemplate()->getTemplateParameters();
822d874057dim      const TemplateArgumentList* Args = FSI->TemplateArguments;
823d874057dim      assert(Params->size() == Args->size());
824d874057dim      for (unsigned i = 0, e = Params->size(); i != e; ++i) {
825d874057dim        StringRef Param = Params->getParam(i)->getName();
826d874057dim        if (Param.empty()) continue;
827d874057dim        TOut << Param << " = ";
828d874057dim        Args->get(i).print(Policy, TOut);
829d874057dim        TOut << ", ";
830d874057dim      }
831d874057dim    }
832d874057dim
833d874057dim    TOut.flush();
834d874057dim    if (!TemplateParams.empty()) {
835d874057dim      // remove the trailing comma and space
836d874057dim      TemplateParams.resize(TemplateParams.size() - 2);
837d874057dim      POut << " [" << TemplateParams << "]";
838d874057dim    }
839d874057dim
840d874057dim    POut.flush();
841d874057dim
842d874057dim    // Print "auto" for all deduced return types. This includes C++1y return
843d874057dim    // type deduction and lambdas. For trailing return types resolve the
844d874057dim    // decltype expression. Otherwise print the real type when this is
845d874057dim    // not a constructor or destructor.
846d874057dim    if (isa<CXXMethodDecl>(FD) &&
847d874057dim         cast<CXXMethodDecl>(FD)->getParent()->isLambda())
848d874057dim      Proto = "auto " + Proto;
849d874057dim    else if (FT && FT->getReturnType()->getAs<DecltypeType>())
850d874057dim      FT->getReturnType()
851d874057dim          ->getAs<DecltypeType>()
852d874057dim          ->getUnderlyingType()
853d874057dim          .getAsStringInternal(Proto, Policy);
854d874057dim    else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
855d874057dim      AFT->getReturnType().getAsStringInternal(Proto, Policy);
856d874057dim
857d874057dim    Out << Proto;
858d874057dim
859d874057dim    return Name.str().str();
860d874057dim  }
861d874057dim  if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
862d874057dim    for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
863d874057dim      // Skip to its enclosing function or method, but not its enclosing
864d874057dim      // CapturedDecl.
865d874057dim      if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
866d874057dim        const Decl *D = Decl::castFromDeclContext(DC);
867d874057dim        return ComputeName(IK, D);
868d874057dim      }
869d874057dim    llvm_unreachable("CapturedDecl not inside a function or method");
870d874057dim  }
871d874057dim  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
872d874057dim    SmallString<256> Name;
873d874057dim    llvm::raw_svector_ostream Out(Name);
874d874057dim    Out << (MD->isInstanceMethod() ? '-' : '+');
875d874057dim    Out << '[';
876d874057dim
877d874057dim    // For incorrect code, there might not be an ObjCInterfaceDecl.  Do
878d874057dim    // a null check to avoid a crash.
879d874057dim    if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
880d874057dim      Out << *ID;
881d874057dim
882d874057dim    if (const ObjCCategoryImplDecl *CID =
883d874057dim        dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
884d874057dim      Out << '(' << *CID << ')';
885d874057dim
886d874057dim    Out <<  ' ';
887d874057dim    MD->getSelector().print(Out);
888d874057dim    Out <<  ']';
889d874057dim
890d874057dim    return Name.str().str();
891d874057dim  }
892d874057dim  if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
893d874057dim    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
894d874057dim    return "top level";
895d874057dim  }
896d874057dim  return "";
897d874057dim}
898d874057dim
899d874057dimvoid APNumericStorage::setIntValue(const ASTContext &C,
900d874057dim                                   const llvm::APInt &Val) {
901d874057dim  if (hasAllocation())
902d874057dim    C.Deallocate(pVal);
903d874057dim
904d874057dim  BitWidth = Val.getBitWidth();
905d874057dim  unsigned NumWords = Val.getNumWords();
906d874057dim  const uint64_t* Words = Val.getRawData();
907d874057dim  if (NumWords > 1) {
908d874057dim    pVal = new (C) uint64_t[NumWords];
909d874057dim    std::copy(Words, Words + NumWords, pVal);
910d874057dim  } else if (NumWords == 1)
911d874057dim    VAL = Words[0];
912d874057dim  else
913d874057dim    VAL = 0;
914d874057dim}
915d874057dim
916d874057dimIntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
917d874057dim                               QualType type, SourceLocation l)
918d874057dim  : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
919d874057dim         false, false),
920d874057dim    Loc(l) {
921d874057dim  assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
922d874057dim  assert(V.getBitWidth() == C.getIntWidth(type) &&
923d874057dim         "Integer type is not the correct size for constant.");
924d874057dim  setValue(C, V);
925d874057dim}
926d874057dim
927d874057dimIntegerLiteral *
928d874057dimIntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
929d874057dim                       QualType type, SourceLocation l) {
930d874057dim  return new (C) IntegerLiteral(C, V, type, l);
931d874057dim}
932d874057dim
933d874057dimIntegerLiteral *
934d874057dimIntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
935d874057dim  return new (C) IntegerLiteral(Empty);
936d874057dim}
937d874057dim
938d874057dimFixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
939d874057dim                                     QualType type, SourceLocation l,
940d874057dim                                     unsigned Scale)
941d874057dim    : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
942d874057dim           false, false),
943d874057dim      Loc(l), Scale(Scale) {
944d874057dim  assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
945d874057dim  assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
946d874057dim         "Fixed point type is not the correct size for constant.");
947d874057dim  setValue(C, V);
948d874057dim}
949d874057dim
950d874057dimFixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
951d874057dim                                                       const llvm::APInt &V,
952d874057dim                                                       QualType type,
953d874057dim                                                       SourceLocation l,
954d874057dim                                                       unsigned Scale) {
955d874057dim  return new (C) FixedPointLiteral(C, V, type, l, Scale);
956d874057dim}
957d874057dim
958d874057dimstd::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
959d874057dim  // Currently the longest decimal number that can be printed is the max for an
960d874057dim  // unsigned long _Accum: 4294967295.99999999976716935634613037109375
961d874057dim  // which is 43 characters.
962d874057dim  SmallString<64> S;
963d874057dim  FixedPointValueToString(
964d874057dim      S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
965d874057dim  return S.str();
966d874057dim}
967d874057dim
968d874057dimFloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
969d874057dim                                 bool isexact, QualType Type, SourceLocation L)
970d874057dim  : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
971d874057dim         false, false), Loc(L) {
972d874057dim  setSemantics(V.getSemantics());
973d874057dim  FloatingLiteralBits.IsExact = isexact;
974d874057dim  setValue(C, V);
975d874057dim}
976d874057dim
977d874057dimFloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
978d874057dim  : Expr(FloatingLiteralClass, Empty) {
979d874057dim  setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
980d874057dim  FloatingLiteralBits.IsExact = false;
981d874057dim}
982d874057dim
983d874057dimFloatingLiteral *
984d874057dimFloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
985d874057dim                        bool isexact, QualType Type, SourceLocation L) {
986d874057dim  return new (C) FloatingLiteral(C, V, isexact, Type, L);
987d874057dim}
988d874057dim
989d874057dimFloatingLiteral *
990d874057dimFloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
991d874057dim  return new (C) FloatingLiteral(C, Empty);
992d874057dim}
993d874057dim
994d874057dim/// getValueAsApproximateDouble - This returns the value as an inaccurate
995d874057dim/// double.  Note that this may cause loss of precision, but is useful for
996d874057dim/// debugging dumps, etc.
997d874057dimdouble FloatingLiteral::getValueAsApproximateDouble() const {
998d874057dim  llvm::APFloat V = getValue();
999d874057dim  bool ignored;
1000d874057dim  V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
1001d874057dim            &ignored);
1002d874057dim  return V.convertToDouble();
1003d874057dim}
1004d874057dim
1005d874057dimunsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1006d874057dim                                         StringKind SK) {
1007d874057dim  unsigned CharByteWidth = 0;
1008d874057dim  switch (SK) {
1009d874057dim  case Ascii:
1010d874057dim  case UTF8:
1011d874057dim    CharByteWidth = Target.getCharWidth();
1012d874057dim    break;
1013d874057dim  case Wide:
1014d874057dim    CharByteWidth = Target.getWCharWidth();
1015d874057dim    break;
1016d874057dim  case UTF16:
1017d874057dim    CharByteWidth = Target.getChar16Width();
1018d874057dim    break;
1019d874057dim  case UTF32:
1020d874057dim    CharByteWidth = Target.getChar32Width();
1021d874057dim    break;
1022d874057dim  }
1023d874057dim  assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1024d874057dim  CharByteWidth /= 8;
1025d874057dim  assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1026d874057dim         "The only supported character byte widths are 1,2 and 4!");
1027d874057dim  return CharByteWidth;
1028d874057dim}
1029d874057dim
1030d874057dimStringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1031d874057dim                             StringKind Kind, bool Pascal, QualType Ty,
1032d874057dim                             const SourceLocation *Loc,
1033d874057dim                             unsigned NumConcatenated)
1034d874057dim    : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1035d874057dim           false) {
1036d874057dim  assert(Ctx.getAsConstantArrayType(Ty) &&
1037d874057dim         "StringLiteral must be of constant array type!");
1038d874057dim  unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1039d874057dim  unsigned ByteLength = Str.size();
1040d874057dim  assert((ByteLength % CharByteWidth == 0) &&
1041d874057dim         "The size of the data must be a multiple of CharByteWidth!");
1042d874057dim
1043d874057dim  // Avoid the expensive division. The compiler should be able to figure it
1044d874057dim  // out by itself. However as of clang 7, even with the appropriate
1045d874057dim  // llvm_unreachable added just here, it is not able to do so.
1046d874057dim  unsigned Length;
1047d874057dim  switch (CharByteWidth) {
1048d874057dim  case 1:
1049d874057dim    Length = ByteLength;
1050d874057dim    break;
1051d874057dim  case 2:
1052d874057dim    Length = ByteLength / 2;
1053d874057dim    break;
1054d874057dim  case 4:
1055d874057dim    Length = ByteLength / 4;
1056d874057dim    break;
1057d874057dim  default:
1058d874057dim    llvm_unreachable("Unsupported character width!");
1059d874057dim  }
1060d874057dim
1061d874057dim  StringLiteralBits.Kind = Kind;
1062d874057dim  StringLiteralBits.CharByteWidth = CharByteWidth;
1063d874057dim  StringLiteralBits.IsPascal = Pascal;
1064d874057dim  StringLiteralBits.NumConcatenated = NumConcatenated;
1065d874057dim  *getTrailingObjects<unsigned>() = Length;
1066d874057dim
1067d874057dim  // Initialize the trailing array of SourceLocation.
1068d874057dim  // This is safe since SourceLocation is POD-like.
1069d874057dim  std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1070d874057dim              NumConcatenated * sizeof(SourceLocation));
1071d874057dim
1072d874057dim  // Initialize the trailing array of char holding the string data.
1073d874057dim  std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
1074d874057dim}
1075d874057dim
1076d874057dimStringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1077d874057dim                             unsigned Length, unsigned CharByteWidth)
1078d874057dim    : Expr(StringLiteralClass, Empty) {
1079d874057dim  StringLiteralBits.CharByteWidth = CharByteWidth;
1080d874057dim  StringLiteralBits.NumConcatenated = NumConcatenated;
1081d874057dim  *getTrailingObjects<unsigned>() = Length;
1082d874057dim}
1083d874057dim
1084d874057dimStringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1085d874057dim                                     StringKind Kind, bool Pascal, QualType Ty,
1086d874057dim                                     const SourceLocation *Loc,
1087d874057dim                                     unsigned NumConcatenated) {
1088d874057dim  void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1089d874057dim                               1, NumConcatenated, Str.size()),
1090d874057dim                           alignof(StringLiteral));
1091d874057dim  return new (Mem)
1092d874057dim      StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1093d874057dim}
1094d874057dim
1095d874057dimStringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1096d874057dim                                          unsigned NumConcatenated,
1097d874057dim                                          unsigned Length,
1098d874057dim                                          unsigned CharByteWidth) {
1099d874057dim  void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1100d874057dim                               1, NumConcatenated, Length * CharByteWidth),
1101d874057dim                           alignof(StringLiteral));
1102d874057dim  return new (Mem)
1103d874057dim      StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1104d874057dim}
1105d874057dim
1106d874057dimvoid StringLiteral::outputString(raw_ostream &OS) const {
1107d874057dim  switch (getKind()) {
1108d874057dim  case Ascii: break; // no prefix.
1109d874057dim  case Wide:  OS << 'L'; break;
1110d874057dim  case UTF8:  OS << "u8"; break;
1111d874057dim  case UTF16: OS << 'u'; break;
1112d874057dim  case UTF32: OS << 'U'; break;
1113d874057dim  }
1114d874057dim  OS << '"';
1115d874057dim  static const char Hex[] = "0123456789ABCDEF";
1116d874057dim
1117d874057dim  unsigned LastSlashX = getLength();
1118d874057dim  for (unsigned I = 0, N = getLength(); I != N; ++I) {
1119d874057dim    switch (uint32_t Char = getCodeUnit(I)) {
1120d874057dim    default:
1121d874057dim      // FIXME: Convert UTF-8 back to codepoints before rendering.
1122d874057dim
1123d874057dim      // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1124d874057dim      // Leave invalid surrogates alone; we'll use \x for those.
1125d874057dim      if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
1126d874057dim          Char <= 0xdbff) {
1127d874057dim        uint32_t Trail = getCodeUnit(I + 1);
1128d874057dim        if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1129d874057dim          Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1130d874057dim          ++I;
1131d874057dim        }
1132d874057dim      }
1133d874057dim
1134d874057dim      if (Char > 0xff) {
1135d874057dim        // If this is a wide string, output characters over 0xff using \x
1136d874057dim        // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1137d874057dim        // codepoint: use \x escapes for invalid codepoints.
1138d874057dim        if (getKind() == Wide ||
1139d874057dim            (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1140d874057dim          // FIXME: Is this the best way to print wchar_t?
1141d874057dim          OS << "\\x";
1142d874057dim          int Shift = 28;
1143d874057dim          while ((Char >> Shift) == 0)
1144d874057dim            Shift -= 4;
1145d874057dim          for (/**/; Shift >= 0; Shift -= 4)
1146d874057dim            OS << Hex[(Char >> Shift) & 15];
1147d874057dim          LastSlashX = I;
1148d874057dim          break;
1149d874057dim        }
1150d874057dim
1151d874057dim        if (Char > 0xffff)
1152d874057dim          OS << "\\U00"
1153d874057dim             << Hex[(Char >> 20) & 15]
1154d874057dim             << Hex[(Char >> 16) & 15];
1155d874057dim        else
1156d874057dim          OS << "\\u";
1157d874057dim        OS << Hex[(Char >> 12) & 15]
1158d874057dim           << Hex[(Char >>  8) & 15]
1159d874057dim           << Hex[(Char >>  4) & 15]
1160d874057dim           << Hex[(Char >>  0) & 15];
1161d874057dim        break;
1162d874057dim      }
1163d874057dim
1164d874057dim      // If we used \x... for the previous character, and this character is a
1165d874057dim      // hexadecimal digit, prevent it being slurped as part of the \x.
1166d874057dim      if (LastSlashX + 1 == I) {
1167d874057dim        switch (Char) {
1168d874057dim          case '0': case '1': case '2': case '3': case '4':
1169d874057dim          case '5': case '6': case '7': case '8': case '9':
1170d874057dim          case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1171d874057dim          case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1172d874057dim            OS << "\"\"";
1173d874057dim        }
1174d874057dim      }
1175d874057dim
1176d874057dim      assert(Char <= 0xff &&
1177d874057dim             "Characters above 0xff should already have been handled.");
1178d874057dim
1179d874057dim      if (isPrintable(Char))
1180d874057dim        OS << (char)Char;
1181d874057dim      else  // Output anything hard as an octal escape.
1182d874057dim        OS << '\\'
1183d874057dim           << (char)('0' + ((Char >> 6) & 7))
1184d874057dim           << (char)('0' + ((Char >> 3) & 7))
1185d874057dim           << (char)('0' + ((Char >> 0) & 7));
1186d874057dim      break;
1187d874057dim    // Handle some common non-printable cases to make dumps prettier.
1188d874057dim    case '\\': OS << "\\\\"; break;
1189d874057dim    case '"': OS << "\\\""; break;
1190d874057dim    case '\a': OS << "\\a"; break;
1191d874057dim    case '\b': OS << "\\b"; break;
1192d874057dim    case '\f': OS << "\\f"; break;
1193d874057dim    case '\n': OS << "\\n"; break;
1194d874057dim    case '\r': OS << "\\r"; break;
1195d874057dim    case '\t': OS << "\\t"; break;
1196d874057dim    case '\v': OS << "\\v"; break;
1197d874057dim    }
1198d874057dim  }
1199d874057dim  OS << '"';
1200d874057dim}
1201d874057dim
1202d874057dim/// getLocationOfByte - Return a source location that points to the specified
1203d874057dim/// byte of this string literal.
1204d874057dim///
1205d874057dim/// Strings are amazingly complex.  They can be formed from multiple tokens and
1206d874057dim/// can have escape sequences in them in addition to the usual trigraph and
1207d874057dim/// escaped newline business.  This routine handles this complexity.
1208d874057dim///
1209d874057dim/// The *StartToken sets the first token to be searched in this function and
1210d874057dim/// the *StartTokenByteOffset is the byte offset of the first token. Before
1211d874057dim/// returning, it updates the *StartToken to the TokNo of the token being found
1212d874057dim/// and sets *StartTokenByteOffset to the byte offset of the token in the
1213d874057dim/// string.
1214d874057dim/// Using these two parameters can reduce the time complexity from O(n^2) to
1215d874057dim/// O(n) if one wants to get the location of byte for all the tokens in a
1216d874057dim/// string.
1217d874057dim///
1218d874057dimSourceLocation
1219d874057dimStringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1220d874057dim                                 const LangOptions &Features,
1221d874057dim                                 const TargetInfo &Target, unsigned *StartToken,
1222d874057dim                                 unsigned *StartTokenByteOffset) const {
1223d874057dim  assert((getKind() == StringLiteral::Ascii ||
1224d874057dim          getKind() == StringLiteral::UTF8) &&
1225d874057dim         "Only narrow string literals are currently supported");
1226d874057dim
1227d874057dim  // Loop over all of the tokens in this string until we find the one that
1228d874057dim  // contains the byte we're looking for.
1229d874057dim  unsigned TokNo = 0;
1230d874057dim  unsigned StringOffset = 0;
1231d874057dim  if (StartToken)
1232d874057dim    TokNo = *StartToken;
1233d874057dim  if (StartTokenByteOffset) {
1234d874057dim    StringOffset = *StartTokenByteOffset;
1235d874057dim    ByteNo -= StringOffset;
1236d874057dim  }
1237d874057dim  while (1) {
1238d874057dim    assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1239d874057dim    SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1240d874057dim
1241d874057dim    // Get the spelling of the string so that we can get the data that makes up
1242d874057dim    // the string literal, not the identifier for the macro it is potentially
1243d874057dim    // expanded through.
1244d874057dim    SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1245d874057dim
1246d874057dim    // Re-lex the token to get its length and original spelling.
1247d874057dim    std::pair<FileID, unsigned> LocInfo =
1248d874057dim        SM.getDecomposedLoc(StrTokSpellingLoc);
1249d874057dim    bool Invalid = false;
1250d874057dim    StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1251d874057dim    if (Invalid) {
1252d874057dim      if (StartTokenByteOffset != nullptr)
1253d874057dim        *StartTokenByteOffset = StringOffset;
1254d874057dim      if (StartToken != nullptr)
1255d874057dim        *StartToken = TokNo;
1256d874057dim      return StrTokSpellingLoc;
1257d874057dim    }
1258d874057dim
1259d874057dim    const char *StrData = Buffer.data()+LocInfo.second;
1260d874057dim
1261d874057dim    // Create a lexer starting at the beginning of this token.
1262d874057dim    Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1263d874057dim                   Buffer.begin(), StrData, Buffer.end());
1264d874057dim    Token TheTok;
1265d874057dim    TheLexer.LexFromRawLexer(TheTok);
1266d874057dim
1267d874057dim    // Use the StringLiteralParser to compute the length of the string in bytes.
1268d874057dim    StringLiteralParser SLP(TheTok, SM, Features, Target);
1269d874057dim    unsigned TokNumBytes = SLP.GetStringLength();
1270d874057dim
1271d874057dim    // If the byte is in this token, return the location of the byte.
1272d874057dim    if (ByteNo < TokNumBytes ||
1273d874057dim        (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1274d874057dim      unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1275d874057dim
1276d874057dim      // Now that we know the offset of the token in the spelling, use the
1277d874057dim      // preprocessor to get the offset in the original source.
1278d874057dim      if (StartTokenByteOffset != nullptr)
1279d874057dim        *StartTokenByteOffset = StringOffset;
1280d874057dim      if (StartToken != nullptr)
1281d874057dim        *StartToken = TokNo;
1282d874057dim      return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1283d874057dim    }
1284d874057dim
1285d874057dim    // Move to the next string token.
1286d874057dim    StringOffset += TokNumBytes;
1287d874057dim    ++TokNo;
1288d874057dim    ByteNo -= TokNumBytes;
1289d874057dim  }
1290d874057dim}
1291d874057dim
1292d874057dim/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1293d874057dim/// corresponds to, e.g. "sizeof" or "[pre]++".
1294d874057dimStringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1295d874057dim  switch (Op) {
1296d874057dim#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1297d874057dim#include "clang/AST/OperationKinds.def"
1298d874057dim  }
1299d874057dim  llvm_unreachable("Unknown unary operator");
1300d874057dim}
1301d874057dim
1302d874057dimUnaryOperatorKind
1303d874057dimUnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1304d874057dim  switch (OO) {
1305d874057dim  default: llvm_unreachable("No unary operator for overloaded function");
1306d874057dim  case OO_PlusPlus:   return Postfix ? UO_PostInc : UO_PreInc;
1307d874057dim  case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1308d874057dim  case OO_Amp:        return UO_AddrOf;
1309d874057dim  case OO_Star:       return UO_Deref;
1310d874057dim  case OO_Plus:       return UO_Plus;
1311d874057dim  case OO_Minus:      return UO_Minus;
1312d874057dim  case OO_Tilde:      return UO_Not;
1313d874057dim  case OO_Exclaim:    return UO_LNot;
1314d874057dim  case OO_Coawait:    return UO_Coawait;
1315d874057dim  }
1316d874057dim}
1317d874057dim
1318d874057dimOverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1319d874057dim  switch (Opc) {
1320d874057dim  case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1321d874057dim  case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1322d874057dim  case UO_AddrOf: return OO_Amp;
1323d874057dim  case UO_Deref: return OO_Star;
1324d874057dim  case UO_Plus: return OO_Plus;
1325d874057dim  case UO_Minus: return OO_Minus;
1326d874057dim  case UO_Not: return OO_Tilde;
1327d874057dim  case UO_LNot: return OO_Exclaim;
1328d874057dim  case UO_Coawait: return OO_Coawait;
1329d874057dim  default: return OO_None;
1330d874057dim  }
1331d874057dim}
1332d874057dim
1333d874057dim
1334d874057dim//===----------------------------------------------------------------------===//
1335d874057dim// Postfix Operators.
1336d874057dim//===----------------------------------------------------------------------===//
1337d874057dim
1338d874057dimCallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1339d874057dim                   ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1340d874057dim                   SourceLocation RParenLoc, unsigned MinNumArgs,
1341d874057dim                   ADLCallKind UsesADL)
1342d874057dim    : Expr(SC, Ty, VK, OK_Ordinary, Fn->isTypeDependent(),
1343d874057dim           Fn->isValueDependent(), Fn->isInstantiationDependent(),
1344d874057dim           Fn->containsUnexpandedParameterPack()),
1345d874057dim      RParenLoc(RParenLoc) {
1346d874057dim  NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1347d874057dim  unsigned NumPreArgs = PreArgs.size();
1348d874057dim  CallExprBits.NumPreArgs = NumPreArgs;
1349d874057dim  assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1350d874057dim
1351d874057dim  unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1352d874057dim  CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1353d874057dim  assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1354d874057dim         "OffsetToTrailingObjects overflow!");
1355d874057dim
1356d874057dim  CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1357d874057dim
1358d874057dim  setCallee(Fn);
1359d874057dim  for (unsigned I = 0; I != NumPreArgs; ++I) {
1360d874057dim    updateDependenciesFromArg(PreArgs[I]);
1361d874057dim    setPreArg(I, PreArgs[I]);
1362d874057dim  }
1363d874057dim  for (unsigned I = 0; I != Args.size(); ++I) {
1364d874057dim    updateDependenciesFromArg(Args[I]);
1365d874057dim    setArg(I, Args[I]);
1366d874057dim  }
1367d874057dim  for (unsigned I = Args.size(); I != NumArgs; ++I) {
1368d874057dim    setArg(I, nullptr);
1369d874057dim  }
1370d874057dim}
1371d874057dim
1372d874057dimCallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1373d874057dim                   EmptyShell Empty)
1374d874057dim    : Expr(SC, Empty), NumArgs(NumArgs) {
1375d874057dim  CallExprBits.NumPreArgs = NumPreArgs;
1376d874057dim  assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1377d874057dim
1378d874057dim  unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1379d874057dim  CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1380d874057dim  assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1381d874057dim         "OffsetToTrailingObjects overflow!");
1382d874057dim}
1383d874057dim
1384d874057dimCallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1385d874057dim                           ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1386d874057dim                           SourceLocation RParenLoc, unsigned MinNumArgs,
1387d874057dim                           ADLCallKind UsesADL) {
1388d874057dim  unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1389d874057dim  unsigned SizeOfTrailingObjects =
1390d874057dim      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1391d874057dim  void *Mem =
1392d874057dim      Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1393d874057dim  return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1394d874057dim                            RParenLoc, MinNumArgs, UsesADL);
1395d874057dim}
1396d874057dim
1397d874057dimCallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1398d874057dim                                    ExprValueKind VK, SourceLocation RParenLoc,
1399d874057dim                                    ADLCallKind UsesADL) {
1400d874057dim  assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1401d874057dim         "Misaligned memory in CallExpr::CreateTemporary!");
1402d874057dim  return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1403d874057dim                            VK, RParenLoc, /*MinNumArgs=*/0, UsesADL);
1404d874057dim}
1405d874057dim
1406d874057dimCallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1407d874057dim                                EmptyShell Empty) {
1408d874057dim  unsigned SizeOfTrailingObjects =
1409d874057dim      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1410d874057dim  void *Mem =
1411d874057dim      Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1412d874057dim  return new (Mem) CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, Empty);
1413d874057dim}
1414d874057dim
1415d874057dimunsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1416d874057dim  switch (SC) {
1417d874057dim  case CallExprClass:
1418d874057dim    return sizeof(CallExpr);
1419d874057dim  case CXXOperatorCallExprClass:
1420d874057dim    return sizeof(CXXOperatorCallExpr);
1421d874057dim  case CXXMemberCallExprClass:
1422d874057dim    return sizeof(CXXMemberCallExpr);
1423d874057dim  case UserDefinedLiteralClass:
1424d874057dim    return sizeof(UserDefinedLiteral);
1425d874057dim  case CUDAKernelCallExprClass:
1426d874057dim    return sizeof(CUDAKernelCallExpr);
1427d874057dim  default:
1428d874057dim    llvm_unreachable("unexpected class deriving from CallExpr!");
1429d874057dim  }
1430d874057dim}
1431d874057dim
1432d874057dimvoid CallExpr::updateDependenciesFromArg(Expr *Arg) {
1433d874057dim  if (Arg->isTypeDependent())
1434d874057dim    ExprBits.TypeDependent = true;
1435d874057dim  if (Arg->isValueDependent())
1436d874057dim    ExprBits.ValueDependent = true;
1437d874057dim  if (Arg->isInstantiationDependent())
1438d874057dim    ExprBits.InstantiationDependent = true;
1439d874057dim  if (Arg->containsUnexpandedParameterPack())
1440d874057dim    ExprBits.ContainsUnexpandedParameterPack = true;
1441d874057dim}
1442d874057dim
1443d874057dimDecl *Expr::getReferencedDeclOfCallee() {
1444d874057dim  Expr *CEE = IgnoreParenImpCasts();
1445d874057dim
1446d874057dim  while (SubstNonTypeTemplateParmExpr *NTTP
1447d874057dim                                = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1448d874057dim    CEE = NTTP->getReplacement()->IgnoreParenCasts();
1449d874057dim  }
1450d874057dim
1451d874057dim  // If we're calling a dereference, look at the pointer instead.
1452d874057dim  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1453d874057dim    if (BO->isPtrMemOp())
1454d874057dim      CEE = BO->getRHS()->IgnoreParenCasts();
1455d874057dim  } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1456d874057dim    if (UO->getOpcode() == UO_Deref)
1457d874057dim      CEE = UO->getSubExpr()->IgnoreParenCasts();
1458d874057dim  }
1459d874057dim  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
1460d874057dim    return DRE->getDecl();
1461d874057dim  if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1462d874057dim    return ME->getMemberDecl();
1463d874057dim  if (auto *BE = dyn_cast<BlockExpr>(CEE))
1464d874057dim    return BE->getBlockDecl();
1465d874057dim
1466d874057dim  return nullptr;
1467d874057dim}
1468d874057dim
1469d874057dim/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
1470d874057dim/// not, return 0.
1471d874057dimunsigned CallExpr::getBuiltinCallee() const {
1472d874057dim  // All simple function calls (e.g. func()) are implicitly cast to pointer to
1473d874057dim  // function. As a result, we try and obtain the DeclRefExpr from the
1474d874057dim  // ImplicitCastExpr.
1475d874057dim  const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1476d874057dim  if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
1477d874057dim    return 0;
1478d874057dim
1479d874057dim  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1480d874057dim  if (!DRE)
1481d874057dim    return 0;
1482d874057dim
1483d874057dim  const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1484d874057dim  if (!FDecl)
1485d874057dim    return 0;
1486d874057dim
1487d874057dim  if (!FDecl->getIdentifier())
1488d874057dim    return 0;
1489d874057dim
1490d874057dim  return FDecl->getBuiltinID();
1491d874057dim}
1492d874057dim
1493d874057dimbool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1494d874057dim  if (unsigned BI = getBuiltinCallee())
1495d874057dim    return Ctx.BuiltinInfo.isUnevaluated(BI);
1496d874057dim  return false;
1497d874057dim}
1498d874057dim
1499d874057dimQualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1500d874057dim  const Expr *Callee = getCallee();
1501d874057dim  QualType CalleeType = Callee->getType();
1502d874057dim  if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1503d874057dim    CalleeType = FnTypePtr->getPointeeType();
1504d874057dim  } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1505d874057dim    CalleeType = BPT->getPointeeType();
1506d874057dim  } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1507d874057dim    if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1508d874057dim      return Ctx.VoidTy;
1509d874057dim
1510d874057dim    // This should never be overloaded and so should never return null.
1511d874057dim    CalleeType = Expr::findBoundMemberType(Callee);
1512d874057dim  }
1513d874057dim
1514d874057dim  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1515d874057dim  return FnType->getReturnType();
1516d874057dim}
1517d874057dim
1518d874057dimconst Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1519d874057dim  // If the return type is a struct, union, or enum that is marked nodiscard,
1520d874057dim  // then return the return type attribute.
1521d874057dim  if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1522d874057dim    if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1523d874057dim      return A;
1524d874057dim
1525d874057dim  // Otherwise, see if the callee is marked nodiscard and return that attribute
1526d874057dim  // instead.
1527d874057dim  const Decl *D = getCalleeDecl();
1528d874057dim  return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1529d874057dim}
1530d874057dim
1531d874057dimSourceLocation CallExpr::getBeginLoc() const {
1532d874057dim  if (isa<CXXOperatorCallExpr>(this))
1533d874057dim    return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
1534d874057dim
1535d874057dim  SourceLocation begin = getCallee()->getBeginLoc();
1536d874057dim  if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1537d874057dim    begin = getArg(0)->getBeginLoc();
1538d874057dim  return begin;
1539d874057dim}
1540d874057dimSourceLocation CallExpr::getEndLoc() const {
1541d874057dim  if (isa<CXXOperatorCallExpr>(this))
1542d874057dim    return cast<CXXOperatorCallExpr>(this)->getEndLoc();
1543d874057dim
1544d874057dim  SourceLocation end = getRParenLoc();
1545d874057dim  if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1546d874057dim    end = getArg(getNumArgs() - 1)->getEndLoc();
1547d874057dim  return end;
1548d874057dim}
1549d874057dim
1550d874057dimOffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1551d874057dim                                   SourceLocation OperatorLoc,
1552d874057dim                                   TypeSourceInfo *tsi,
1553d874057dim                                   ArrayRef<OffsetOfNode> comps,
1554d874057dim                                   ArrayRef<Expr*> exprs,
1555d874057dim                                   SourceLocation RParenLoc) {
1556d874057dim  void *Mem = C.Allocate(
1557d874057dim      totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1558d874057dim
1559d874057dim  return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1560d874057dim                                RParenLoc);
1561d874057dim}
1562d874057dim
1563d874057dimOffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1564d874057dim                                        unsigned numComps, unsigned numExprs) {
1565d874057dim  void *Mem =
1566d874057dim      C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1567d874057dim  return new (Mem) OffsetOfExpr(numComps, numExprs);
1568d874057dim}
1569d874057dim
1570d874057dimOffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1571d874057dim                           SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1572d874057dim                           ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1573d874057dim                           SourceLocation RParenLoc)
1574d874057dim  : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1575d874057dim         /*TypeDependent=*/false,
1576d874057dim         /*ValueDependent=*/tsi->getType()->isDependentType(),
1577d874057dim         tsi->getType()->isInstantiationDependentType(),
1578d874057dim         tsi->getType()->containsUnexpandedParameterPack()),
1579d874057dim    OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1580d874057dim    NumComps(comps.size()), NumExprs(exprs.size())
1581d874057dim{
1582d874057dim  for (unsigned i = 0; i != comps.size(); ++i) {
1583d874057dim    setComponent(i, comps[i]);
1584d874057dim  }
1585d874057dim
1586d874057dim  for (unsigned i = 0; i != exprs.size(); ++i) {
1587d874057dim    if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
1588d874057dim      ExprBits.ValueDependent = true;
1589d874057dim    if (exprs[i]->containsUnexpandedParameterPack())
1590d874057dim      ExprBits.ContainsUnexpandedParameterPack = true;
1591d874057dim
1592d874057dim    setIndexExpr(i, exprs[i]);
1593d874057dim  }
1594d874057dim}
1595d874057dim
1596d874057dimIdentifierInfo *OffsetOfNode::getFieldName() const {
1597d874057dim  assert(getKind() == Field || getKind() == Identifier);
1598d874057dim  if (getKind() == Field)
1599d874057dim    return getField()->getIdentifier();
1600d874057dim
1601d874057dim  return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1602d874057dim}
1603d874057dim
1604d874057dimUnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1605d874057dim    UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1606d874057dim    SourceLocation op, SourceLocation rp)
1607d874057dim    : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1608d874057dim           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1609d874057dim           // Value-dependent if the argument is type-dependent.
1610d874057dim           E->isTypeDependent(), E->isInstantiationDependent(),
1611d874057dim           E->containsUnexpandedParameterPack()),
1612d874057dim      OpLoc(op), RParenLoc(rp) {
1613d874057dim  UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1614d874057dim  UnaryExprOrTypeTraitExprBits.IsType = false;
1615d874057dim  Argument.Ex = E;
1616d874057dim
1617d874057dim  // Check to see if we are in the situation where alignof(decl) should be
1618d874057dim  // dependent because decl's alignment is dependent.
1619d874057dim  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
1620d874057dim    if (!isValueDependent() || !isInstantiationDependent()) {
1621d874057dim      E = E->IgnoreParens();
1622d874057dim
1623d874057dim      const ValueDecl *D = nullptr;
1624d874057dim      if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1625d874057dim        D = DRE->getDecl();
1626d874057dim      else if (const auto *ME = dyn_cast<MemberExpr>(E))
1627d874057dim        D = ME->getMemberDecl();
1628d874057dim
1629d874057dim      if (D) {
1630d874057dim        for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1631d874057dim          if (I->isAlignmentDependent()) {
1632d874057dim            setValueDependent(true);
1633d874057dim            setInstantiationDependent(true);
1634d874057dim            break;
1635d874057dim          }
1636d874057dim        }
1637d874057dim      }
1638d874057dim    }
1639d874057dim  }
1640d874057dim}
1641d874057dim
1642d874057dimMemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1643d874057dim                       ValueDecl *MemberDecl,
1644d874057dim                       const DeclarationNameInfo &NameInfo, QualType T,
1645d874057dim                       ExprValueKind VK, ExprObjectKind OK,
1646d874057dim                       NonOdrUseReason NOUR)
1647d874057dim    : Expr(MemberExprClass, T, VK, OK, Base->isTypeDependent(),
1648d874057dim           Base->isValueDependent(), Base->isInstantiationDependent(),
1649d874057dim           Base->containsUnexpandedParameterPack()),
1650d874057dim      Base(Base), MemberDecl(MemberDecl), MemberDNLoc(NameInfo.getInfo()),
1651d874057dim      MemberLoc(NameInfo.getLoc()) {
1652d874057dim  assert(!NameInfo.getName() ||
1653d874057dim         MemberDecl->getDeclName() == NameInfo.getName());
1654d874057dim  MemberExprBits.IsArrow = IsArrow;
1655d874057dim  MemberExprBits.HasQualifierOrFoundDecl = false;
1656d874057dim  MemberExprBits.HasTemplateKWAndArgsInfo = false;
1657d874057dim  MemberExprBits.HadMultipleCandidates = false;
1658d874057dim  MemberExprBits.NonOdrUseReason = NOUR;
1659d874057dim  MemberExprBits.OperatorLoc = OperatorLoc;
1660d874057dim}
1661d874057dim
1662d874057dimMemberExpr *MemberExpr::Create(
1663d874057dim    const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1664d874057dim    NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1665d874057dim    ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1666d874057dim    DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1667d874057dim    QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
1668d874057dim  bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1669d874057dim                        FoundDecl.getAccess() != MemberDecl->getAccess();
1670d874057dim  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1671d874057dim  std::size_t Size =
1672d874057dim      totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1673d874057dim                       TemplateArgumentLoc>(
1674d874057dim          HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1675d874057dim          TemplateArgs ? TemplateArgs->size() : 0);
1676d874057dim
1677d874057dim  void *Mem = C.Allocate(Size, alignof(MemberExpr));
1678d874057dim  MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1679d874057dim                                       NameInfo, T, VK, OK, NOUR);
1680d874057dim
1681332da66dim  if (isa<FieldDecl>(MemberDecl)) {
1682332da66dim    DeclContext *DC = MemberDecl->getDeclContext();
1683332da66dim    // dyn_cast_or_null is used to handle objC variables which do not
1684332da66dim    // have a declaration context.
1685332da66dim    CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(DC);
1686332da66dim    if (RD && RD->isDependentContext() && RD->isCurrentInstantiation(DC))
1687332da66dim      E->setTypeDependent(T->isDependentType());
168858400c8dim
168958400c8dim    // Bitfield with value-dependent width is type-dependent.
169058400c8dim    FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl);
169158400c8dim    if (FD && FD->isBitField() && FD->getBitWidth()->isValueDependent())
169258400c8dim      E->setTypeDependent(true);
1693332da66dim  }
1694332da66dim
1695d874057dim  if (HasQualOrFound) {
1696d874057dim    // FIXME: Wrong. We should be looking at the member declaration we found.
1697d874057dim    if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1698d874057dim      E->setValueDependent(true);
1699d874057dim      E->setTypeDependent(true);
1700d874057dim      E->setInstantiationDependent(true);
1701d874057dim    }
1702d874057dim    else if (QualifierLoc &&
1703d874057dim             QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1704d874057dim      E->setInstantiationDependent(true);
1705d874057dim
1706d874057dim    E->MemberExprBits.HasQualifierOrFoundDecl = true;
1707d874057dim
1708d874057dim    MemberExprNameQualifier *NQ =
1709d874057dim        E->getTrailingObjects<MemberExprNameQualifier>();
1710d874057dim    NQ->QualifierLoc = QualifierLoc;
1711d874057dim    NQ->FoundDecl = FoundDecl;
1712d874057dim  }
1713d874057dim
1714d874057dim  E->MemberExprBits.HasTemplateKWAndArgsInfo =
1715d874057dim      TemplateArgs || TemplateKWLoc.isValid();
1716d874057dim
1717d874057dim  if (TemplateArgs) {
1718d874057dim    bool Dependent = false;
1719d874057dim    bool InstantiationDependent = false;
1720d874057dim    bool ContainsUnexpandedParameterPack = false;
1721d874057dim    E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1722d874057dim        TemplateKWLoc, *TemplateArgs,
1723d874057dim        E->getTrailingObjects<TemplateArgumentLoc>(), Dependent,
1724d874057dim        InstantiationDependent, ContainsUnexpandedParameterPack);
1725d874057dim    if (InstantiationDependent)
1726d874057dim      E->setInstantiationDependent(true);
1727d874057dim  } else if (TemplateKWLoc.isValid()) {
1728d874057dim    E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1729d874057dim        TemplateKWLoc);
1730d874057dim  }
1731d874057dim
1732d874057dim  return E;
1733d874057dim}
1734d874057dim
1735d874057dimMemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1736d874057dim                                    bool HasQualifier, bool HasFoundDecl,
1737d874057dim                                    bool HasTemplateKWAndArgsInfo,
1738d874057dim                                    unsigned NumTemplateArgs) {
1739d874057dim  assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1740d874057dim         "template args but no template arg info?");
1741d874057dim  bool HasQualOrFound = HasQualifier || HasFoundDecl;
1742d874057dim  std::size_t Size =
1743d874057dim      totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1744d874057dim                       TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1745d874057dim                                            HasTemplateKWAndArgsInfo ? 1 : 0,
1746d874057dim                                            NumTemplateArgs);
1747d874057dim  void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1748d874057dim  return new (Mem) MemberExpr(EmptyShell());
1749d874057dim}
1750d874057dim
1751d874057dimSourceLocation MemberExpr::getBeginLoc() const {
1752d874057dim  if (isImplicitAccess()) {
1753d874057dim    if (hasQualifier())
1754d874057dim      return getQualifierLoc().getBeginLoc();
1755d874057dim    return MemberLoc;
1756d874057dim  }
1757d874057dim
1758d874057dim  // FIXME: We don't want this to happen. Rather, we should be able to
1759d874057dim  // detect all kinds of implicit accesses more cleanly.
1760d874057dim  SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1761d874057dim  if (BaseStartLoc.isValid())
1762d874057dim    return BaseStartLoc;
1763d874057dim  return MemberLoc;
1764d874057dim}
1765d874057dimSourceLocation MemberExpr::getEndLoc() const {
1766d874057dim  SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1767d874057dim  if (hasExplicitTemplateArgs())
1768d874057dim    EndLoc = getRAngleLoc();
1769d874057dim  else if (EndLoc.isInvalid())
1770d874057dim    EndLoc = getBase()->getEndLoc();
1771d874057dim  return EndLoc;
1772d874057dim}
1773d874057dim
1774d874057dimbool CastExpr::CastConsistency() const {
1775d874057dim  switch (getCastKind()) {
1776d874057dim  case CK_DerivedToBase:
1777d874057dim  case CK_UncheckedDerivedToBase:
1778d874057dim  case CK_DerivedToBaseMemberPointer:
1779d874057dim  case CK_BaseToDerived:
1780d874057dim  case CK_BaseToDerivedMemberPointer:
1781d874057dim    assert(!path_empty() && "Cast kind should have a base path!");
1782d874057dim    break;
1783d874057dim
1784d874057dim  case CK_CPointerToObjCPointerCast:
1785d874057dim    assert(getType()->isObjCObjectPointerType());
1786d874057dim    assert(getSubExpr()->getType()->isPointerType());
1787d874057dim    goto CheckNoBasePath;
1788d874057dim
1789d874057dim  case CK_BlockPointerToObjCPointerCast:
1790d874057dim    assert(getType()->isObjCObjectPointerType());
1791d874057dim    assert(getSubExpr()->getType()->isBlockPointerType());
1792d874057dim    goto CheckNoBasePath;
1793d874057dim
1794d874057dim  case CK_ReinterpretMemberPointer:
1795d874057dim    assert(getType()->isMemberPointerType());
1796d874057dim    assert(getSubExpr()->getType()->isMemberPointerType());
1797d874057dim    goto CheckNoBasePath;
1798d874057dim
1799d874057dim  case CK_BitCast:
1800d874057dim    // Arbitrary casts to C pointer types count as bitcasts.
1801d874057dim    // Otherwise, we should only have block and ObjC pointer casts
1802d874057dim    // here if they stay within the type kind.
1803d874057dim    if (!getType()->isPointerType()) {
1804d874057dim      assert(getType()->isObjCObjectPointerType() ==
1805d874057dim             getSubExpr()->getType()->isObjCObjectPointerType());
1806d874057dim      assert(getType()->isBlockPointerType() ==
1807d874057dim             getSubExpr()->getType()->isBlockPointerType());
1808d874057dim    }
1809d874057dim    goto CheckNoBasePath;
1810d874057dim
1811d874057dim  case CK_AnyPointerToBlockPointerCast:
1812d874057dim    assert(getType()->isBlockPointerType());
1813d874057dim    assert(getSubExpr()->getType()->isAnyPointerType() &&
1814d874057dim           !getSubExpr()->getType()->isBlockPointerType());
1815d874057dim    goto CheckNoBasePath;
1816d874057dim
1817d874057dim  case CK_CopyAndAutoreleaseBlockObject:
1818d874057dim    assert(getType()->isBlockPointerType());
1819d874057dim    assert(getSubExpr()->getType()->isBlockPointerType());
1820d874057dim    goto CheckNoBasePath;
1821d874057dim
1822d874057dim  case CK_FunctionToPointerDecay:
1823d874057dim    assert(getType()->isPointerType());
1824d874057dim    assert(getSubExpr()->getType()->isFunctionType());
1825d874057dim    goto CheckNoBasePath;
1826d874057dim
1827d874057dim  case CK_AddressSpaceConversion: {
1828d874057dim    auto Ty = getType();
1829d874057dim    auto SETy = getSubExpr()->getType();
1830d874057dim    assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1831332da66dim    if (isRValue()) {
1832d874057dim      Ty = Ty->getPointeeType();
1833d874057dim      SETy = SETy->getPointeeType();
1834d874057dim    }
1835d874057dim    assert(!Ty.isNull() && !SETy.isNull() &&
1836d874057dim           Ty.getAddressSpace() != SETy.getAddressSpace());
1837d874057dim    goto CheckNoBasePath;
1838d874057dim  }
1839d874057dim  // These should not have an inheritance path.
1840d874057dim  case CK_Dynamic:
1841d874057dim  case CK_ToUnion:
1842d874057dim  case CK_ArrayToPointerDecay:
1843d874057dim  case CK_NullToMemberPointer:
1844d874057dim  case CK_NullToPointer:
1845d874057dim  case CK_ConstructorConversion:
1846d874057dim  case CK_IntegralToPointer:
1847d874057dim  case CK_PointerToIntegral:
1848d874057dim  case CK_ToVoid:
1849d874057dim  case CK_VectorSplat:
1850d874057dim  case CK_IntegralCast:
1851d874057dim  case CK_BooleanToSignedIntegral:
1852d874057dim  case CK_IntegralToFloating:
1853d874057dim  case CK_FloatingToIntegral:
1854d874057dim  case CK_FloatingCast:
1855d874057dim  case CK_ObjCObjectLValueCast:
1856d874057dim  case CK_FloatingRealToComplex:
1857d874057dim  case CK_FloatingComplexToReal:
1858d874057dim  case CK_FloatingComplexCast:
1859d874057dim  case CK_FloatingComplexToIntegralComplex:
1860d874057dim  case CK_IntegralRealToComplex:
1861d874057dim  case CK_IntegralComplexToReal:
1862d874057dim  case CK_IntegralComplexCast:
1863d874057dim  case CK_IntegralComplexToFloatingComplex:
1864d874057dim  case CK_ARCProduceObject:
1865d874057dim  case CK_ARCConsumeObject:
1866d874057dim  case CK_ARCReclaimReturnedObject:
1867d874057dim  case CK_ARCExtendBlockObject:
1868d874057dim  case CK_ZeroToOCLOpaqueType:
1869d874057dim  case CK_IntToOCLSampler:
1870d874057dim  case CK_FixedPointCast:
1871d874057dim  case CK_FixedPointToIntegral:
1872d874057dim  case CK_IntegralToFixedPoint:
1873d874057dim    assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1874d874057dim    goto CheckNoBasePath;
1875d874057dim
1876d874057dim  case CK_Dependent:
1877d874057dim  case CK_LValueToRValue:
1878d874057dim  case CK_NoOp:
1879d874057dim  case CK_AtomicToNonAtomic:
1880d874057dim  case CK_NonAtomicToAtomic:
1881d874057dim  case CK_PointerToBoolean:
1882d874057dim  case CK_IntegralToBoolean:
1883d874057dim  case CK_FloatingToBoolean:
1884d874057dim  case CK_MemberPointerToBoolean:
1885d874057dim  case CK_FloatingComplexToBoolean:
1886d874057dim  case CK_IntegralComplexToBoolean:
1887d874057dim  case CK_LValueBitCast:            // -> bool&
1888d874057dim  case CK_LValueToRValueBitCast:
1889d874057dim  case CK_UserDefinedConversion:    // operator bool()
1890d874057dim  case CK_BuiltinFnToFnPtr:
1891d874057dim  case CK_FixedPointToBoolean:
1892d874057dim  CheckNoBasePath:
1893d874057dim    assert(path_empty() && "Cast kind should not have a base path!");
1894d874057dim    break;
1895d874057dim  }
1896d874057dim  return true;
1897d874057dim}
1898d874057dim
1899d874057dimconst char *CastExpr::getCastKindName(CastKind CK) {
1900d874057dim  switch (CK) {
1901d874057dim#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1902d874057dim#include "clang/AST/OperationKinds.def"
1903d874057dim  }
1904d874057dim  llvm_unreachable("Unhandled cast kind!");
1905d874057dim}
1906d874057dim
1907d874057dimnamespace {
1908d874057dim  const Expr *skipImplicitTemporary(const Expr *E) {
1909d874057dim    // Skip through reference binding to temporary.
1910d874057dim    if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1911332da66dim      E = Materialize->getSubExpr();
1912d874057dim
1913d874057dim    // Skip any temporary bindings; they're implicit.
1914d874057dim    if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1915d874057dim      E = Binder->getSubExpr();
1916d874057dim
1917d874057dim    return E;
1918d874057dim  }
1919d874057dim}
1920d874057dim
1921d874057dimExpr *CastExpr::getSubExprAsWritten() {
1922d874057dim  const Expr *SubExpr = nullptr;
1923d874057dim  const CastExpr *E = this;
1924d874057dim  do {
1925d874057dim    SubExpr = skipImplicitTemporary(E->getSubExpr());
1926d874057dim
1927d874057dim    // Conversions by constructor and conversion functions have a
1928d874057dim    // subexpression describing the call; strip it off.
1929d874057dim    if (E->getCastKind() == CK_ConstructorConversion)
1930d874057dim      SubExpr =
1931d874057dim        skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
1932d874057dim    else if (E->getCastKind() == CK_UserDefinedConversion) {
1933d874057dim      assert((isa<CXXMemberCallExpr>(SubExpr) ||
1934d874057dim              isa<BlockExpr>(SubExpr)) &&
1935d874057dim             "Unexpected SubExpr for CK_UserDefinedConversion.");
1936d874057dim      if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1937d874057dim        SubExpr = MCE->getImplicitObjectArgument();
1938d874057dim    }
1939d874057dim
1940d874057dim    // If the subexpression we're left with is an implicit cast, look
1941d874057dim    // through that, too.
1942d874057dim  } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1943d874057dim
1944d874057dim  return const_cast<Expr*>(SubExpr);
1945d874057dim}
1946d874057dim
1947d874057dimNamedDecl *CastExpr::getConversionFunction() const {
1948d874057dim  const Expr *SubExpr = nullptr;
1949d874057dim
1950d874057dim  for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1951d874057dim    SubExpr = skipImplicitTemporary(E->getSubExpr());
1952d874057dim
1953d874057dim    if (E->getCastKind() == CK_ConstructorConversion)
1954d874057dim      return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1955d874057dim
1956d874057dim    if (E->getCastKind() == CK_UserDefinedConversion) {
1957d874057dim      if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1958d874057dim        return MCE->getMethodDecl();
1959d874057dim    }
1960d874057dim  }
1961d874057dim
1962d874057dim  return nullptr;
1963d874057dim}
1964d874057dim
1965d874057dimCXXBaseSpecifier **CastExpr::path_buffer() {
1966d874057dim  switch (getStmtClass()) {
1967d874057dim#define ABSTRACT_STMT(x)
1968d874057dim#define CASTEXPR(Type, Base)                                                   \
1969d874057dim  case Stmt::Type##Class:                                                      \
1970d874057dim    return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1971d874057dim#define STMT(Type, Base)
1972d874057dim#include "clang/AST/StmtNodes.inc"
1973d874057dim  default:
1974d874057dim    llvm_unreachable("non-cast expressions not possible here");
1975d874057dim  }
1976d874057dim}
1977d874057dim
1978d874057dimconst FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1979d874057dim                                                        QualType opType) {
1980d874057dim  auto RD = unionType->castAs<RecordType>()->getDecl();
1981d874057dim  return getTargetFieldForToUnionCast(RD, opType);
1982d874057dim}
1983d874057dim
1984d874057dimconst FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1985d874057dim                                                        QualType OpType) {
1986d874057dim  auto &Ctx = RD->getASTContext();
1987d874057dim  RecordDecl::field_iterator Field, FieldEnd;
1988d874057dim  for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1989d874057dim       Field != FieldEnd; ++Field) {
1990d874057dim    if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1991d874057dim        !Field->isUnnamedBitfield()) {
1992d874057dim      return *Field;
1993d874057dim    }
1994d874057dim  }
1995d874057dim  return nullptr;
1996d874057dim}
1997d874057dim
1998d874057dimImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
1999d874057dim                                           CastKind Kind, Expr *Operand,
2000d874057dim                                           const CXXCastPath *BasePath,
2001d874057dim                                           ExprValueKind VK) {
2002d874057dim  unsigned PathSize = (BasePath ? BasePath->size() : 0);
2003d874057dim  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
2004d874057dim  // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
2005d874057dim  // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
2006d874057dim  assert((Kind != CK_LValueToRValue ||
2007d874057dim          !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
2008d874057dim         "invalid type for lvalue-to-rvalue conversion");
2009d874057dim  ImplicitCastExpr *E =
2010d874057dim    new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
2011d874057dim  if (PathSize)
2012d874057dim    std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2013d874057dim                              E->getTrailingObjects<CXXBaseSpecifier *>());
2014d874057dim  return E;
2015d874057dim}
2016d874057dim
2017d874057dimImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
2018d874057dim                                                unsigned PathSize) {
2019d874057dim  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
2020d874057dim  return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
2021d874057dim}
2022d874057dim
2023d874057dim
2024d874057dimCStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
2025d874057dim                                       ExprValueKind VK, CastKind K, Expr *Op,
2026d874057dim                                       const CXXCastPath *BasePath,
2027d874057dim                                       TypeSourceInfo *WrittenTy,
2028d874057dim                                       SourceLocation L, SourceLocation R) {
2029d874057dim  unsigned PathSize = (BasePath ? BasePath->size() : 0);
2030d874057dim  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
2031d874057dim  CStyleCastExpr *E =
2032d874057dim    new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
2033d874057dim  if (PathSize)
2034d874057dim    std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2035d874057dim                              E->getTrailingObjects<CXXBaseSpecifier *>());
2036d874057dim  return E;
2037d874057dim}
2038d874057dim
2039d874057dimCStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
2040d874057dim                                            unsigned PathSize) {
2041d874057dim  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
2042d874057dim  return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
2043d874057dim}
2044d874057dim
2045d874057dim/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2046d874057dim/// corresponds to, e.g. "<<=".
2047d874057dimStringRef BinaryOperator::getOpcodeStr(Opcode Op) {
2048d874057dim  switch (Op) {
2049d874057dim#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2050d874057dim#include "clang/AST/OperationKinds.def"
2051d874057dim  }
2052d874057dim  llvm_unreachable("Invalid OpCode!");
2053d874057dim}
2054d874057dim
2055d874057dimBinaryOperatorKind
2056d874057dimBinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2057d874057dim  switch (OO) {
2058d874057dim  default: llvm_unreachable("Not an overloadable binary operator");
2059d874057dim  case OO_Plus: return BO_Add;
2060d874057dim  case OO_Minus: return BO_Sub;
2061d874057dim  case OO_Star: return BO_Mul;
2062d874057dim  case OO_Slash: return BO_Div;
2063d874057dim  case OO_Percent: return BO_Rem;
2064d874057dim  case OO_Caret: return BO_Xor;
2065d874057dim  case OO_Amp: return BO_And;
2066d874057dim  case OO_Pipe: return BO_Or;
2067d874057dim  case OO_Equal: return BO_Assign;
2068d874057dim  case OO_Spaceship: return BO_Cmp;
2069d874057dim  case OO_Less: return BO_LT;
2070d874057dim  case OO_Greater: return BO_GT;
2071d874057dim  case OO_PlusEqual: return BO_AddAssign;
2072d874057dim  case OO_MinusEqual: return BO_SubAssign;
2073d874057dim  case OO_StarEqual: return BO_MulAssign;
2074d874057dim  case OO_SlashEqual: return BO_DivAssign;
2075d874057dim  case OO_PercentEqual: return BO_RemAssign;
2076d874057dim  case OO_CaretEqual: return BO_XorAssign;
2077d874057dim  case OO_AmpEqual: return BO_AndAssign;
2078d874057dim  case OO_PipeEqual: return BO_OrAssign;
2079d874057dim  case OO_LessLess: return BO_Shl;
2080d874057dim  case OO_GreaterGreater: return BO_Shr;
2081d874057dim  case OO_LessLessEqual: return BO_ShlAssign;
2082d874057dim  case OO_GreaterGreaterEqual: return BO_ShrAssign;
2083d874057dim  case OO_EqualEqual: return BO_EQ;
2084d874057dim  case OO_ExclaimEqual: return BO_NE;
2085d874057dim  case OO_LessEqual: return BO_LE;
2086d874057dim  case OO_GreaterEqual: return BO_GE;
2087d874057dim  case OO_AmpAmp: return BO_LAnd;
2088d874057dim  case OO_PipePipe: return BO_LOr;
2089d874057dim  case OO_Comma: return BO_Comma;
2090d874057dim  case OO_ArrowStar: return BO_PtrMemI;
2091d874057dim  }
2092d874057dim}
2093d874057dim
2094d874057dimOverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2095d874057dim  static const OverloadedOperatorKind OverOps[] = {
2096d874057dim    /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2097d874057dim    OO_Star, OO_Slash, OO_Percent,
2098d874057dim    OO_Plus, OO_Minus,
2099d874057dim    OO_LessLess, OO_GreaterGreater,
2100d874057dim    OO_Spaceship,
2101d874057dim    OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2102d874057dim    OO_EqualEqual, OO_ExclaimEqual,
2103d874057dim    OO_Amp,
2104d874057dim    OO_Caret,
2105d874057dim    OO_Pipe,
2106d874057dim    OO_AmpAmp,
2107d874057dim    OO_PipePipe,
2108d874057dim    OO_Equal, OO_StarEqual,
2109d874057dim    OO_SlashEqual, OO_PercentEqual,
2110d874057dim    OO_PlusEqual, OO_MinusEqual,
2111d874057dim    OO_LessLessEqual, OO_GreaterGreaterEqual,
2112d874057dim    OO_AmpEqual, OO_CaretEqual,
2113d874057dim    OO_PipeEqual,
2114d874057dim    OO_Comma
2115d874057dim  };
2116d874057dim  return OverOps[Opc];
2117d874057dim}
2118d874057dim
2119d874057dimbool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2120d874057dim                                                      Opcode Opc,
2121d874057dim                                                      Expr *LHS, Expr *RHS) {
2122d874057dim  if (Opc != BO_Add)
2123d874057dim    return false;
2124d874057dim
2125d874057dim  // Check that we have one pointer and one integer operand.
2126d874057dim  Expr *PExp;
2127d874057dim  if (LHS->getType()->isPointerType()) {
2128d874057dim    if (!RHS->getType()->isIntegerType())
2129d874057dim      return false;
2130d874057dim    PExp = LHS;
2131d874057dim  } else if (RHS->getType()->isPointerType()) {
2132d874057dim    if (!LHS->getType()->isIntegerType())
2133d874057dim      return false;
2134d874057dim    PExp = RHS;
2135d874057dim  } else {
2136d874057dim    return false;
2137d874057dim  }
2138d874057dim
2139d874057dim  // Check that the pointer is a nullptr.
2140d874057dim  if (!PExp->IgnoreParenCasts()
2141d874057dim          ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2142d874057dim    return false;
2143d874057dim
2144d874057dim  // Check that the pointee type is char-sized.
2145d874057dim  const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2146d874057dim  if (!PTy || !PTy->getPointeeType()->isCharType())
2147d874057dim    return false;
2148d874057dim
2149d874057dim  return true;
2150d874057dim}
2151d874057dim
2152d874057dimstatic QualType getDecayedSourceLocExprType(const ASTContext &Ctx,
2153d874057dim                                            SourceLocExpr::IdentKind Kind) {
2154d874057dim  switch (Kind) {
2155d874057dim  case SourceLocExpr::File:
2156d874057dim  case SourceLocExpr::Function: {
2157d874057dim    QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2158d874057dim    return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2159d874057dim  }
2160d874057dim  case SourceLocExpr::Line:
2161d874057dim  case SourceLocExpr::Column:
2162d874057dim    return Ctx.UnsignedIntTy;
2163d874057dim  }
2164d874057dim  llvm_unreachable("unhandled case");
2165d874057dim}
2166d874057dim
2167d874057dimSourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
2168d874057dim                             SourceLocation BLoc, SourceLocation RParenLoc,
2169d874057dim                             DeclContext *ParentContext)
2170d874057dim    : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2171d874057dim           VK_RValue, OK_Ordinary, false, false, false, false),
2172d874057dim      BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2173d874057dim  SourceLocExprBits.Kind = Kind;
2174d874057dim}
2175d874057dim
2176d874057dimStringRef SourceLocExpr::getBuiltinStr() const {
2177d874057dim  switch (getIdentKind()) {
2178d874057dim  case File:
2179d874057dim    return "__builtin_FILE";
2180d874057dim  case Function:
2181d874057dim    return "__builtin_FUNCTION";
2182d874057dim  case Line:
2183d874057dim    return "__builtin_LINE";
2184d874057dim  case Column:
2185d874057dim    return "__builtin_COLUMN";
2186d874057dim  }
2187d874057dim  llvm_unreachable("unexpected IdentKind!");
2188d874057dim}
2189d874057dim
2190d874057dimAPValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2191d874057dim                                         const Expr *DefaultExpr) const {
2192d874057dim  SourceLocation Loc;
2193d874057dim  const DeclContext *Context;
2194d874057dim
2195d874057dim  std::tie(Loc,
2196d874057dim           Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2197d874057dim    if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2198d874057dim      return {DIE->getUsedLocation(), DIE->getUsedContext()};
2199d874057dim    if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2200d874057dim      return {DAE->getUsedLocation(), DAE->getUsedContext()};
2201d874057dim    return {this->getLocation(), this->getParentContext()};
2202d874057dim  }();
2203d874057dim
2204d874057dim  PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2205d874057dim      Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2206d874057dim
2207d874057dim  auto MakeStringLiteral = [&](StringRef Tmp) {
2208d874057dim    using LValuePathEntry = APValue::LValuePathEntry;
2209d874057dim    StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2210d874057dim    // Decay the string to a pointer to the first character.
2211d874057dim    LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2212d874057dim    return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2213d874057dim  };
2214d874057dim
2215d874057dim  switch (getIdentKind()) {
2216d874057dim  case SourceLocExpr::File:
2217d874057dim    return MakeStringLiteral(PLoc.getFilename());
2218d874057dim  case SourceLocExpr::Function: {
2219d874057dim    const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2220d874057dim    return MakeStringLiteral(
2221d874057dim        CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
2222d874057dim                : std::string(""));
2223d874057dim  }
2224d874057dim  case SourceLocExpr::Line:
2225d874057dim  case SourceLocExpr::Column: {
2226d874057dim    llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
2227d874057dim                        /*isUnsigned=*/true);
2228d874057dim    IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2229d874057dim                                                   : PLoc.getColumn();
2230d874057dim    return APValue(IntVal);
2231d874057dim  }
2232d874057dim  }
2233d874057dim  llvm_unreachable("unhandled case");
2234d874057dim}
2235d874057dim
2236d874057dimInitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
2237d874057dim                           ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
2238d874057dim  : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
2239d874057dim         false, false),
2240d874057dim    InitExprs(C, initExprs.size()),
2241d874057dim    LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
2242d874057dim{
2243d874057dim  sawArrayRangeDesignator(false);
2244d874057dim  for (unsigned I = 0; I != initExprs.size(); ++I) {
2245d874057dim    if (initExprs[I]->isTypeDependent())
2246d874057dim      ExprBits.TypeDependent = true;
2247d874057dim    if (initExprs[I]->isValueDependent())
2248d874057dim      ExprBits.ValueDependent = true;
2249d874057dim    if (initExprs[I]->isInstantiationDependent())
2250d874057dim      ExprBits.InstantiationDependent = true;
2251d874057dim    if (initExprs[I]->containsUnexpandedParameterPack())
2252d874057dim      ExprBits.ContainsUnexpandedParameterPack = true;
2253d874057dim  }
2254d874057dim
2255d874057dim  InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2256d874057dim}
2257d874057dim
2258d874057dimvoid InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2259d874057dim  if (NumInits > InitExprs.size())
2260d874057dim    InitExprs.reserve(C, NumInits);
2261d874057dim}
2262d874057dim
2263d874057dimvoid InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2264d874057dim  InitExprs.resize(C, NumInits, nullptr);
2265d874057dim}
2266d874057dim
2267d874057dimExpr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2268d874057dim  if (Init >= InitExprs.size()) {
2269d874057dim    InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2270d874057dim    setInit(Init, expr);
2271d874057dim    return nullptr;
2272d874057dim  }
2273d874057dim
2274d874057dim  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2275d874057dim  setInit(Init, expr);
2276d874057dim  return Result;
2277d874057dim}
2278d874057dim
2279d874057dimvoid InitListExpr::setArrayFiller(Expr *filler) {
2280d874057dim  assert(!hasArrayFiller() && "Filler already set!");
2281d874057dim  ArrayFillerOrUnionFieldInit = filler;
2282d874057dim  // Fill out any "holes" in the array due to designated initializers.
2283d874057dim  Expr **inits = getInits();
2284d874057dim  for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2285d874057dim    if (inits[i] == nullptr)
2286d874057dim      inits[i] = filler;
2287d874057dim}
2288d874057dim
2289d874057dimbool InitListExpr::isStringLiteralInit() const {
2290d874057dim  if (getNumInits() != 1)
2291d874057dim    return false;
2292d874057dim  const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2293d874057dim  if (!AT || !AT->getElementType()->isIntegerType())
2294d874057dim    return false;
2295d874057dim  // It is possible for getInit() to return null.
2296d874057dim  const Expr *Init = getInit(0);
2297d874057dim  if (!Init)
2298d874057dim    return false;
2299d874057dim  Init = Init->IgnoreParens();
2300d874057dim  return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2301d874057dim}
2302d874057dim
2303d874057dimbool InitListExpr::isTransparent() const {
2304d874057dim  assert(isSemanticForm() && "syntactic form never semantically transparent");
2305d874057dim
2306d874057dim  // A glvalue InitListExpr is always just sugar.
2307d874057dim  if (isGLValue()) {
2308d874057dim    assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2309d874057dim    return true;
2310d874057dim  }
2311d874057dim
2312d874057dim  // Otherwise, we're sugar if and only if we have exactly one initializer that
2313d874057dim  // is of the same type.
2314d874057dim  if (getNumInits() != 1 || !getInit(0))
2315d874057dim    return false;
2316d874057dim
2317d874057dim  // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2318d874057dim  // transparent struct copy.
2319d874057dim  if (!getInit(0)->isRValue() && getType()->isRecordType())
2320d874057dim    return false;
2321d874057dim
2322d874057dim  return getType().getCanonicalType() ==
2323d874057dim         getInit(0)->getType().getCanonicalType();
2324d874057dim}
2325d874057dim
2326d874057dimbool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2327d874057dim  assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2328d874057dim
2329d874057dim  if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2330d874057dim    return false;
2331d874057dim  }
2332d874057dim
2333d874057dim  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2334d874057dim  return Lit && Lit->getValue() == 0;
2335d874057dim}
2336d874057dim
2337d874057dimSourceLocation InitListExpr::getBeginLoc() const {
2338d874057dim  if (InitListExpr *SyntacticForm = getSyntacticForm())
2339d874057dim    return SyntacticForm->getBeginLoc();
2340d874057dim  SourceLocation Beg = LBraceLoc;
2341d874057dim  if (Beg.isInvalid()) {
2342d874057dim    // Find the first non-null initializer.
2343d874057dim    for (InitExprsTy::const_iterator I = InitExprs.begin(),
2344d874057dim                                     E = InitExprs.end();
2345d874057dim      I != E; ++I) {
2346d874057dim      if (Stmt *S = *I) {
2347d874057dim        Beg = S->getBeginLoc();
2348d874057dim        break;
2349d874057dim      }
2350d874057dim    }
2351d874057dim  }
2352d874057dim  return Beg;
2353d874057dim}
2354d874057dim
2355d874057dimSourceLocation InitListExpr::getEndLoc() const {
2356d874057dim  if (InitListExpr *SyntacticForm = getSyntacticForm())
2357d874057dim    return SyntacticForm->getEndLoc();
2358d874057dim  SourceLocation End = RBraceLoc;
2359d874057dim  if (End.isInvalid()) {
2360d874057dim    // Find the first non-null initializer from the end.
2361d874057dim    for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
2362d874057dim         E = InitExprs.rend();
2363d874057dim         I != E; ++I) {
2364d874057dim      if (Stmt *S = *I) {
2365d874057dim        End = S->getEndLoc();
2366d874057dim        break;
2367d874057dim      }
2368d874057dim    }
2369d874057dim  }
2370d874057dim  return End;
2371d874057dim}
2372d874057dim
2373d874057dim/// getFunctionType - Return the underlying function type for this block.
2374d874057dim///
2375d874057dimconst FunctionProtoType *BlockExpr::getFunctionType() const {
2376d874057dim  // The block pointer is never sugared, but the function type might be.
2377d874057dim  return cast<BlockPointerType>(getType())
2378d874057dim           ->getPointeeType()->castAs<FunctionProtoType>();
2379d874057dim}
2380d874057dim
2381d874057dimSourceLocation BlockExpr::getCaretLocation() const {
2382d874057dim  return TheBlock->getCaretLocation();
2383d874057dim}
2384d874057dimconst Stmt *BlockExpr::getBody() const {
2385d874057dim  return TheBlock->getBody();
2386d874057dim}
2387d874057dimStmt *BlockExpr::getBody() {
2388d874057dim  return TheBlock->getBody();
2389d874057dim}
2390d874057dim
2391d874057dim
2392d874057dim//===----------------------------------------------------------------------===//
2393d874057dim// Generic Expression Routines
2394d874057dim//===----------------------------------------------------------------------===//
2395d874057dim
2396d874057dim/// isUnusedResultAWarning - Return true if this immediate expression should
2397d874057dim/// be warned about if the result is unused.  If so, fill in Loc and Ranges
2398d874057dim/// with location to warn on and the source range[s] to report with the
2399d874057dim/// warning.
2400d874057dimbool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2401d874057dim                                  SourceRange &R1, SourceRange &R2,
2402d874057dim                                  ASTContext &Ctx) const {
2403d874057dim  // Don't warn if the expr is type dependent. The type could end up
2404d874057dim  // instantiating to void.
2405d874057dim  if (isTypeDependent())
2406d874057dim    return false;
2407d874057dim
2408d874057dim  switch (getStmtClass()) {
2409d874057dim  default:
2410d874057dim    if (getType()->isVoidType())
2411d874057dim      return false;
2412d874057dim    WarnE = this;
2413d874057dim    Loc = getExprLoc();
2414d874057dim    R1 = getSourceRange();
2415d874057dim    return true;
2416d874057dim  case ParenExprClass:
2417d874057dim    return cast<ParenExpr>(this)->getSubExpr()->
2418d874057dim      isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2419d874057dim  case GenericSelectionExprClass:
2420d874057dim    return cast<GenericSelectionExpr>(this)->getResultExpr()->
2421d874057dim      isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2422d874057dim  case CoawaitExprClass:
2423d874057dim  case CoyieldExprClass:
2424d874057dim    return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2425d874057dim      isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2426d874057dim  case ChooseExprClass:
2427d874057dim    return cast<ChooseExpr>(this)->getChosenSubExpr()->
2428d874057dim      isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2429d874057dim  case UnaryOperatorClass: {
2430d874057dim    const UnaryOperator *UO = cast<UnaryOperator>(this);
2431d874057dim
2432d874057dim    switch (UO->getOpcode()) {
2433d874057dim    case UO_Plus:
2434d874057dim    case UO_Minus:
2435d874057dim    case UO_AddrOf:
2436d874057dim    case UO_Not:
2437d874057dim    case UO_LNot:
2438d874057dim    case UO_Deref:
2439d874057dim      break;
2440d874057dim    case UO_Coawait:
2441d874057dim      // This is just the 'operator co_await' call inside the guts of a
2442d874057dim      // dependent co_await call.
2443d874057dim    case UO_PostInc:
2444d874057dim    case UO_PostDec:
2445d874057dim    case UO_PreInc:
2446d874057dim    case UO_PreDec:                 // ++/--
2447d874057dim      return false;  // Not a warning.
2448d874057dim    case UO_Real:
2449d874057dim    case UO_Imag:
2450d874057dim      // accessing a piece of a volatile complex is a side-effect.
2451d874057dim      if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2452d874057dim          .isVolatileQualified())
2453d874057dim        return false;
2454d874057dim      break;
2455d874057dim    case UO_Extension:
2456d874057dim      return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2457d874057dim    }
2458d874057dim    WarnE = this;
2459d874057dim    Loc = UO->getOperatorLoc();
2460d874057dim    R1 = UO->getSubExpr()->getSourceRange();
2461d874057dim    return true;
2462d874057dim  }
2463d874057dim  case BinaryOperatorClass: {
2464d874057dim    const BinaryOperator *BO = cast<BinaryOperator>(this);
2465d874057dim    switch (BO->getOpcode()) {
2466d874057dim      default:
2467d874057dim        break;
2468d874057dim      // Consider the RHS of comma for side effects. LHS was checked by
2469d874057dim      // Sema::CheckCommaOperands.
2470d874057dim      case BO_Comma:
2471d874057dim        // ((foo = <blah>), 0) is an idiom for hiding the result (and
2472d874057dim        // lvalue-ness) of an assignment written in a macro.
2473d874057dim        if (IntegerLiteral *IE =
2474d874057dim              dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2475d874057dim          if (IE->getValue() == 0)
2476d874057dim            return false;
2477d874057dim        return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2478d874057dim      // Consider '||', '&&' to have side effects if the LHS or RHS does.
2479d874057dim      case BO_LAnd:
2480d874057dim      case BO_LOr:
2481d874057dim        if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2482d874057dim            !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2483d874057dim          return false;
2484d874057dim        break;
2485d874057dim    }
2486d874057dim    if (BO->isAssignmentOp())
2487d874057dim      return false;
2488d874057dim    WarnE = this;
2489d874057dim    Loc = BO->getOperatorLoc();
2490d874057dim    R1 = BO->getLHS()->getSourceRange();
2491d874057dim    R2 = BO->getRHS()->getSourceRange();
2492d874057dim    return true;
2493d874057dim  }
2494d874057dim  case CompoundAssignOperatorClass:
2495d874057dim  case VAArgExprClass:
2496d874057dim  case AtomicExprClass:
2497d874057dim    return false;
2498d874057dim
2499d874057dim  case ConditionalOperatorClass: {
2500d874057dim    // If only one of the LHS or RHS is a warning, the operator might
2501d874057dim    // be being used for control flow. Only warn if both the LHS and
2502d874057dim    // RHS are warnings.
2503d874057dim    const auto *Exp = cast<ConditionalOperator>(this);
2504d874057dim    return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2505d874057dim           Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2506d874057dim  }
2507d874057dim  case BinaryConditionalOperatorClass: {
2508d874057dim    const auto *Exp = cast<BinaryConditionalOperator>(this);
2509d874057dim    return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2510d874057dim  }
2511d874057dim
2512d874057dim  case MemberExprClass:
2513d874057dim    WarnE = this;
2514d874057dim    Loc = cast<MemberExpr>(this)->getMemberLoc();
2515d874057dim    R1 = SourceRange(Loc, Loc);
2516d874057dim    R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2517d874057dim    return true;
2518d874057dim
2519d874057dim  case ArraySubscriptExprClass:
2520d874057dim    WarnE = this;
2521d874057dim    Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2522d874057dim    R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2523d874057dim    R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2524d874057dim    return true;
2525d874057dim
2526d874057dim  case CXXOperatorCallExprClass: {
2527d874057dim    // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2528d874057dim    // overloads as there is no reasonable way to define these such that they
2529d874057dim    // have non-trivial, desirable side-effects. See the -Wunused-comparison
2530d874057dim    // warning: operators == and != are commonly typo'ed, and so warning on them
2531d874057dim    // provides additional value as well. If this list is updated,
2532d874057dim    // DiagnoseUnusedComparison should be as well.
2533d874057dim    const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2534d874057dim    switch (Op->getOperator()) {
2535d874057dim    default:
2536d874057dim      break;
2537d874057dim    case OO_EqualEqual:
2538d874057dim    case OO_ExclaimEqual:
2539d874057dim    case OO_Less:
2540d874057dim    case OO_Greater:
2541d874057dim    case OO_GreaterEqual:
2542d874057dim    case OO_LessEqual:
2543d874057dim      if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2544d874057dim          Op->getCallReturnType(Ctx)->isVoidType())
2545d874057dim        break;
2546d874057