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