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