xref: /llvm-project-15.0.7/clang/lib/AST/Expr.cpp (revision e67cee09)
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 =
1482       dyn_cast_or_null<FunctionDecl>(getCallee()->getReferencedDeclOfCallee());
1483   return FDecl ? FDecl->getBuiltinID() : 0;
1484 }
1485 
1486 bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1487   if (unsigned BI = getBuiltinCallee())
1488     return Ctx.BuiltinInfo.isUnevaluated(BI);
1489   return false;
1490 }
1491 
1492 QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1493   const Expr *Callee = getCallee();
1494   QualType CalleeType = Callee->getType();
1495   if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1496     CalleeType = FnTypePtr->getPointeeType();
1497   } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1498     CalleeType = BPT->getPointeeType();
1499   } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1500     if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1501       return Ctx.VoidTy;
1502 
1503     if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))
1504       return Ctx.DependentTy;
1505 
1506     // This should never be overloaded and so should never return null.
1507     CalleeType = Expr::findBoundMemberType(Callee);
1508     assert(!CalleeType.isNull());
1509   } else if (CalleeType->isDependentType() ||
1510              CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
1511     return Ctx.DependentTy;
1512   }
1513 
1514   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1515   return FnType->getReturnType();
1516 }
1517 
1518 const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1519   // If the return type is a struct, union, or enum that is marked nodiscard,
1520   // then return the return type attribute.
1521   if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1522     if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1523       return A;
1524 
1525   // Otherwise, see if the callee is marked nodiscard and return that attribute
1526   // instead.
1527   const Decl *D = getCalleeDecl();
1528   return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1529 }
1530 
1531 SourceLocation CallExpr::getBeginLoc() const {
1532   if (isa<CXXOperatorCallExpr>(this))
1533     return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
1534 
1535   SourceLocation begin = getCallee()->getBeginLoc();
1536   if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1537     begin = getArg(0)->getBeginLoc();
1538   return begin;
1539 }
1540 SourceLocation CallExpr::getEndLoc() const {
1541   if (isa<CXXOperatorCallExpr>(this))
1542     return cast<CXXOperatorCallExpr>(this)->getEndLoc();
1543 
1544   SourceLocation end = getRParenLoc();
1545   if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1546     end = getArg(getNumArgs() - 1)->getEndLoc();
1547   return end;
1548 }
1549 
1550 OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1551                                    SourceLocation OperatorLoc,
1552                                    TypeSourceInfo *tsi,
1553                                    ArrayRef<OffsetOfNode> comps,
1554                                    ArrayRef<Expr*> exprs,
1555                                    SourceLocation RParenLoc) {
1556   void *Mem = C.Allocate(
1557       totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1558 
1559   return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1560                                 RParenLoc);
1561 }
1562 
1563 OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1564                                         unsigned numComps, unsigned numExprs) {
1565   void *Mem =
1566       C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1567   return new (Mem) OffsetOfExpr(numComps, numExprs);
1568 }
1569 
1570 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1571                            SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1572                            ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,
1573                            SourceLocation RParenLoc)
1574     : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),
1575       OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1576       NumComps(comps.size()), NumExprs(exprs.size()) {
1577   for (unsigned i = 0; i != comps.size(); ++i)
1578     setComponent(i, comps[i]);
1579   for (unsigned i = 0; i != exprs.size(); ++i)
1580     setIndexExpr(i, exprs[i]);
1581 
1582   setDependence(computeDependence(this));
1583 }
1584 
1585 IdentifierInfo *OffsetOfNode::getFieldName() const {
1586   assert(getKind() == Field || getKind() == Identifier);
1587   if (getKind() == Field)
1588     return getField()->getIdentifier();
1589 
1590   return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1591 }
1592 
1593 UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1594     UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1595     SourceLocation op, SourceLocation rp)
1596     : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
1597       OpLoc(op), RParenLoc(rp) {
1598   assert(ExprKind <= UETT_Last && "invalid enum value!");
1599   UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1600   assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&
1601          "UnaryExprOrTypeTraitExprBits.Kind overflow!");
1602   UnaryExprOrTypeTraitExprBits.IsType = false;
1603   Argument.Ex = E;
1604   setDependence(computeDependence(this));
1605 }
1606 
1607 MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1608                        ValueDecl *MemberDecl,
1609                        const DeclarationNameInfo &NameInfo, QualType T,
1610                        ExprValueKind VK, ExprObjectKind OK,
1611                        NonOdrUseReason NOUR)
1612     : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1613       MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
1614   assert(!NameInfo.getName() ||
1615          MemberDecl->getDeclName() == NameInfo.getName());
1616   MemberExprBits.IsArrow = IsArrow;
1617   MemberExprBits.HasQualifierOrFoundDecl = false;
1618   MemberExprBits.HasTemplateKWAndArgsInfo = false;
1619   MemberExprBits.HadMultipleCandidates = false;
1620   MemberExprBits.NonOdrUseReason = NOUR;
1621   MemberExprBits.OperatorLoc = OperatorLoc;
1622   setDependence(computeDependence(this));
1623 }
1624 
1625 MemberExpr *MemberExpr::Create(
1626     const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1627     NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1628     ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1629     DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1630     QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
1631   bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1632                         FoundDecl.getAccess() != MemberDecl->getAccess();
1633   bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1634   std::size_t Size =
1635       totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1636                        TemplateArgumentLoc>(
1637           HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1638           TemplateArgs ? TemplateArgs->size() : 0);
1639 
1640   void *Mem = C.Allocate(Size, alignof(MemberExpr));
1641   MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1642                                        NameInfo, T, VK, OK, NOUR);
1643 
1644   // FIXME: remove remaining dependence computation to computeDependence().
1645   auto Deps = E->getDependence();
1646   if (HasQualOrFound) {
1647     // FIXME: Wrong. We should be looking at the member declaration we found.
1648     if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent())
1649       Deps |= ExprDependence::TypeValueInstantiation;
1650     else if (QualifierLoc &&
1651              QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1652       Deps |= ExprDependence::Instantiation;
1653 
1654     E->MemberExprBits.HasQualifierOrFoundDecl = true;
1655 
1656     MemberExprNameQualifier *NQ =
1657         E->getTrailingObjects<MemberExprNameQualifier>();
1658     NQ->QualifierLoc = QualifierLoc;
1659     NQ->FoundDecl = FoundDecl;
1660   }
1661 
1662   E->MemberExprBits.HasTemplateKWAndArgsInfo =
1663       TemplateArgs || TemplateKWLoc.isValid();
1664 
1665   if (TemplateArgs) {
1666     auto TemplateArgDeps = TemplateArgumentDependence::None;
1667     E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1668         TemplateKWLoc, *TemplateArgs,
1669         E->getTrailingObjects<TemplateArgumentLoc>(), TemplateArgDeps);
1670     if (TemplateArgDeps & TemplateArgumentDependence::Instantiation)
1671       Deps |= ExprDependence::Instantiation;
1672   } else if (TemplateKWLoc.isValid()) {
1673     E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1674         TemplateKWLoc);
1675   }
1676   E->setDependence(Deps);
1677 
1678   return E;
1679 }
1680 
1681 MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1682                                     bool HasQualifier, bool HasFoundDecl,
1683                                     bool HasTemplateKWAndArgsInfo,
1684                                     unsigned NumTemplateArgs) {
1685   assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1686          "template args but no template arg info?");
1687   bool HasQualOrFound = HasQualifier || HasFoundDecl;
1688   std::size_t Size =
1689       totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1690                        TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1691                                             HasTemplateKWAndArgsInfo ? 1 : 0,
1692                                             NumTemplateArgs);
1693   void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1694   return new (Mem) MemberExpr(EmptyShell());
1695 }
1696 
1697 void MemberExpr::setMemberDecl(ValueDecl *NewD) {
1698   MemberDecl = NewD;
1699   if (getType()->isUndeducedType())
1700     setType(NewD->getType());
1701   setDependence(computeDependence(this));
1702 }
1703 
1704 SourceLocation MemberExpr::getBeginLoc() const {
1705   if (isImplicitAccess()) {
1706     if (hasQualifier())
1707       return getQualifierLoc().getBeginLoc();
1708     return MemberLoc;
1709   }
1710 
1711   // FIXME: We don't want this to happen. Rather, we should be able to
1712   // detect all kinds of implicit accesses more cleanly.
1713   SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1714   if (BaseStartLoc.isValid())
1715     return BaseStartLoc;
1716   return MemberLoc;
1717 }
1718 SourceLocation MemberExpr::getEndLoc() const {
1719   SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1720   if (hasExplicitTemplateArgs())
1721     EndLoc = getRAngleLoc();
1722   else if (EndLoc.isInvalid())
1723     EndLoc = getBase()->getEndLoc();
1724   return EndLoc;
1725 }
1726 
1727 bool CastExpr::CastConsistency() const {
1728   switch (getCastKind()) {
1729   case CK_DerivedToBase:
1730   case CK_UncheckedDerivedToBase:
1731   case CK_DerivedToBaseMemberPointer:
1732   case CK_BaseToDerived:
1733   case CK_BaseToDerivedMemberPointer:
1734     assert(!path_empty() && "Cast kind should have a base path!");
1735     break;
1736 
1737   case CK_CPointerToObjCPointerCast:
1738     assert(getType()->isObjCObjectPointerType());
1739     assert(getSubExpr()->getType()->isPointerType());
1740     goto CheckNoBasePath;
1741 
1742   case CK_BlockPointerToObjCPointerCast:
1743     assert(getType()->isObjCObjectPointerType());
1744     assert(getSubExpr()->getType()->isBlockPointerType());
1745     goto CheckNoBasePath;
1746 
1747   case CK_ReinterpretMemberPointer:
1748     assert(getType()->isMemberPointerType());
1749     assert(getSubExpr()->getType()->isMemberPointerType());
1750     goto CheckNoBasePath;
1751 
1752   case CK_BitCast:
1753     // Arbitrary casts to C pointer types count as bitcasts.
1754     // Otherwise, we should only have block and ObjC pointer casts
1755     // here if they stay within the type kind.
1756     if (!getType()->isPointerType()) {
1757       assert(getType()->isObjCObjectPointerType() ==
1758              getSubExpr()->getType()->isObjCObjectPointerType());
1759       assert(getType()->isBlockPointerType() ==
1760              getSubExpr()->getType()->isBlockPointerType());
1761     }
1762     goto CheckNoBasePath;
1763 
1764   case CK_AnyPointerToBlockPointerCast:
1765     assert(getType()->isBlockPointerType());
1766     assert(getSubExpr()->getType()->isAnyPointerType() &&
1767            !getSubExpr()->getType()->isBlockPointerType());
1768     goto CheckNoBasePath;
1769 
1770   case CK_CopyAndAutoreleaseBlockObject:
1771     assert(getType()->isBlockPointerType());
1772     assert(getSubExpr()->getType()->isBlockPointerType());
1773     goto CheckNoBasePath;
1774 
1775   case CK_FunctionToPointerDecay:
1776     assert(getType()->isPointerType());
1777     assert(getSubExpr()->getType()->isFunctionType());
1778     goto CheckNoBasePath;
1779 
1780   case CK_AddressSpaceConversion: {
1781     auto Ty = getType();
1782     auto SETy = getSubExpr()->getType();
1783     assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1784     if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1785       Ty = Ty->getPointeeType();
1786       SETy = SETy->getPointeeType();
1787     }
1788     assert((Ty->isDependentType() || SETy->isDependentType()) ||
1789            (!Ty.isNull() && !SETy.isNull() &&
1790             Ty.getAddressSpace() != SETy.getAddressSpace()));
1791     goto CheckNoBasePath;
1792   }
1793   // These should not have an inheritance path.
1794   case CK_Dynamic:
1795   case CK_ToUnion:
1796   case CK_ArrayToPointerDecay:
1797   case CK_NullToMemberPointer:
1798   case CK_NullToPointer:
1799   case CK_ConstructorConversion:
1800   case CK_IntegralToPointer:
1801   case CK_PointerToIntegral:
1802   case CK_ToVoid:
1803   case CK_VectorSplat:
1804   case CK_IntegralCast:
1805   case CK_BooleanToSignedIntegral:
1806   case CK_IntegralToFloating:
1807   case CK_FloatingToIntegral:
1808   case CK_FloatingCast:
1809   case CK_ObjCObjectLValueCast:
1810   case CK_FloatingRealToComplex:
1811   case CK_FloatingComplexToReal:
1812   case CK_FloatingComplexCast:
1813   case CK_FloatingComplexToIntegralComplex:
1814   case CK_IntegralRealToComplex:
1815   case CK_IntegralComplexToReal:
1816   case CK_IntegralComplexCast:
1817   case CK_IntegralComplexToFloatingComplex:
1818   case CK_ARCProduceObject:
1819   case CK_ARCConsumeObject:
1820   case CK_ARCReclaimReturnedObject:
1821   case CK_ARCExtendBlockObject:
1822   case CK_ZeroToOCLOpaqueType:
1823   case CK_IntToOCLSampler:
1824   case CK_FloatingToFixedPoint:
1825   case CK_FixedPointToFloating:
1826   case CK_FixedPointCast:
1827   case CK_FixedPointToIntegral:
1828   case CK_IntegralToFixedPoint:
1829   case CK_MatrixCast:
1830     assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1831     goto CheckNoBasePath;
1832 
1833   case CK_Dependent:
1834   case CK_LValueToRValue:
1835   case CK_NoOp:
1836   case CK_AtomicToNonAtomic:
1837   case CK_NonAtomicToAtomic:
1838   case CK_PointerToBoolean:
1839   case CK_IntegralToBoolean:
1840   case CK_FloatingToBoolean:
1841   case CK_MemberPointerToBoolean:
1842   case CK_FloatingComplexToBoolean:
1843   case CK_IntegralComplexToBoolean:
1844   case CK_LValueBitCast:            // -> bool&
1845   case CK_LValueToRValueBitCast:
1846   case CK_UserDefinedConversion:    // operator bool()
1847   case CK_BuiltinFnToFnPtr:
1848   case CK_FixedPointToBoolean:
1849   CheckNoBasePath:
1850     assert(path_empty() && "Cast kind should not have a base path!");
1851     break;
1852   }
1853   return true;
1854 }
1855 
1856 const char *CastExpr::getCastKindName(CastKind CK) {
1857   switch (CK) {
1858 #define CAST_OPERATION(Name) case CK_##Name: return #Name;
1859 #include "clang/AST/OperationKinds.def"
1860   }
1861   llvm_unreachable("Unhandled cast kind!");
1862 }
1863 
1864 namespace {
1865 // Skip over implicit nodes produced as part of semantic analysis.
1866 // Designed for use with IgnoreExprNodes.
1867 Expr *ignoreImplicitSemaNodes(Expr *E) {
1868   if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1869     return Materialize->getSubExpr();
1870 
1871   if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1872     return Binder->getSubExpr();
1873 
1874   if (auto *Full = dyn_cast<FullExpr>(E))
1875     return Full->getSubExpr();
1876 
1877   return E;
1878 }
1879 } // namespace
1880 
1881 Expr *CastExpr::getSubExprAsWritten() {
1882   const Expr *SubExpr = nullptr;
1883 
1884   for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1885     SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
1886 
1887     // Conversions by constructor and conversion functions have a
1888     // subexpression describing the call; strip it off.
1889     if (E->getCastKind() == CK_ConstructorConversion) {
1890       SubExpr = IgnoreExprNodes(cast<CXXConstructExpr>(SubExpr)->getArg(0),
1891                                 ignoreImplicitSemaNodes);
1892     } else if (E->getCastKind() == CK_UserDefinedConversion) {
1893       assert((isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) &&
1894              "Unexpected SubExpr for CK_UserDefinedConversion.");
1895       if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1896         SubExpr = MCE->getImplicitObjectArgument();
1897     }
1898   }
1899 
1900   return const_cast<Expr *>(SubExpr);
1901 }
1902 
1903 NamedDecl *CastExpr::getConversionFunction() const {
1904   const Expr *SubExpr = nullptr;
1905 
1906   for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1907     SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
1908 
1909     if (E->getCastKind() == CK_ConstructorConversion)
1910       return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1911 
1912     if (E->getCastKind() == CK_UserDefinedConversion) {
1913       if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1914         return MCE->getMethodDecl();
1915     }
1916   }
1917 
1918   return nullptr;
1919 }
1920 
1921 CXXBaseSpecifier **CastExpr::path_buffer() {
1922   switch (getStmtClass()) {
1923 #define ABSTRACT_STMT(x)
1924 #define CASTEXPR(Type, Base)                                                   \
1925   case Stmt::Type##Class:                                                      \
1926     return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1927 #define STMT(Type, Base)
1928 #include "clang/AST/StmtNodes.inc"
1929   default:
1930     llvm_unreachable("non-cast expressions not possible here");
1931   }
1932 }
1933 
1934 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1935                                                         QualType opType) {
1936   auto RD = unionType->castAs<RecordType>()->getDecl();
1937   return getTargetFieldForToUnionCast(RD, opType);
1938 }
1939 
1940 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1941                                                         QualType OpType) {
1942   auto &Ctx = RD->getASTContext();
1943   RecordDecl::field_iterator Field, FieldEnd;
1944   for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1945        Field != FieldEnd; ++Field) {
1946     if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1947         !Field->isUnnamedBitfield()) {
1948       return *Field;
1949     }
1950   }
1951   return nullptr;
1952 }
1953 
1954 FPOptionsOverride *CastExpr::getTrailingFPFeatures() {
1955   assert(hasStoredFPFeatures());
1956   switch (getStmtClass()) {
1957   case ImplicitCastExprClass:
1958     return static_cast<ImplicitCastExpr *>(this)
1959         ->getTrailingObjects<FPOptionsOverride>();
1960   case CStyleCastExprClass:
1961     return static_cast<CStyleCastExpr *>(this)
1962         ->getTrailingObjects<FPOptionsOverride>();
1963   case CXXFunctionalCastExprClass:
1964     return static_cast<CXXFunctionalCastExpr *>(this)
1965         ->getTrailingObjects<FPOptionsOverride>();
1966   case CXXStaticCastExprClass:
1967     return static_cast<CXXStaticCastExpr *>(this)
1968         ->getTrailingObjects<FPOptionsOverride>();
1969   default:
1970     llvm_unreachable("Cast does not have FPFeatures");
1971   }
1972 }
1973 
1974 ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
1975                                            CastKind Kind, Expr *Operand,
1976                                            const CXXCastPath *BasePath,
1977                                            ExprValueKind VK,
1978                                            FPOptionsOverride FPO) {
1979   unsigned PathSize = (BasePath ? BasePath->size() : 0);
1980   void *Buffer =
1981       C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
1982           PathSize, FPO.requiresTrailingStorage()));
1983   // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
1984   // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
1985   assert((Kind != CK_LValueToRValue ||
1986           !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
1987          "invalid type for lvalue-to-rvalue conversion");
1988   ImplicitCastExpr *E =
1989       new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);
1990   if (PathSize)
1991     std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1992                               E->getTrailingObjects<CXXBaseSpecifier *>());
1993   return E;
1994 }
1995 
1996 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
1997                                                 unsigned PathSize,
1998                                                 bool HasFPFeatures) {
1999   void *Buffer =
2000       C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2001           PathSize, HasFPFeatures));
2002   return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2003 }
2004 
2005 CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
2006                                        ExprValueKind VK, CastKind K, Expr *Op,
2007                                        const CXXCastPath *BasePath,
2008                                        FPOptionsOverride FPO,
2009                                        TypeSourceInfo *WrittenTy,
2010                                        SourceLocation L, SourceLocation R) {
2011   unsigned PathSize = (BasePath ? BasePath->size() : 0);
2012   void *Buffer =
2013       C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2014           PathSize, FPO.requiresTrailingStorage()));
2015   CStyleCastExpr *E =
2016       new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);
2017   if (PathSize)
2018     std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2019                               E->getTrailingObjects<CXXBaseSpecifier *>());
2020   return E;
2021 }
2022 
2023 CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
2024                                             unsigned PathSize,
2025                                             bool HasFPFeatures) {
2026   void *Buffer =
2027       C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2028           PathSize, HasFPFeatures));
2029   return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2030 }
2031 
2032 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2033 /// corresponds to, e.g. "<<=".
2034 StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
2035   switch (Op) {
2036 #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2037 #include "clang/AST/OperationKinds.def"
2038   }
2039   llvm_unreachable("Invalid OpCode!");
2040 }
2041 
2042 BinaryOperatorKind
2043 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2044   switch (OO) {
2045   default: llvm_unreachable("Not an overloadable binary operator");
2046   case OO_Plus: return BO_Add;
2047   case OO_Minus: return BO_Sub;
2048   case OO_Star: return BO_Mul;
2049   case OO_Slash: return BO_Div;
2050   case OO_Percent: return BO_Rem;
2051   case OO_Caret: return BO_Xor;
2052   case OO_Amp: return BO_And;
2053   case OO_Pipe: return BO_Or;
2054   case OO_Equal: return BO_Assign;
2055   case OO_Spaceship: return BO_Cmp;
2056   case OO_Less: return BO_LT;
2057   case OO_Greater: return BO_GT;
2058   case OO_PlusEqual: return BO_AddAssign;
2059   case OO_MinusEqual: return BO_SubAssign;
2060   case OO_StarEqual: return BO_MulAssign;
2061   case OO_SlashEqual: return BO_DivAssign;
2062   case OO_PercentEqual: return BO_RemAssign;
2063   case OO_CaretEqual: return BO_XorAssign;
2064   case OO_AmpEqual: return BO_AndAssign;
2065   case OO_PipeEqual: return BO_OrAssign;
2066   case OO_LessLess: return BO_Shl;
2067   case OO_GreaterGreater: return BO_Shr;
2068   case OO_LessLessEqual: return BO_ShlAssign;
2069   case OO_GreaterGreaterEqual: return BO_ShrAssign;
2070   case OO_EqualEqual: return BO_EQ;
2071   case OO_ExclaimEqual: return BO_NE;
2072   case OO_LessEqual: return BO_LE;
2073   case OO_GreaterEqual: return BO_GE;
2074   case OO_AmpAmp: return BO_LAnd;
2075   case OO_PipePipe: return BO_LOr;
2076   case OO_Comma: return BO_Comma;
2077   case OO_ArrowStar: return BO_PtrMemI;
2078   }
2079 }
2080 
2081 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2082   static const OverloadedOperatorKind OverOps[] = {
2083     /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2084     OO_Star, OO_Slash, OO_Percent,
2085     OO_Plus, OO_Minus,
2086     OO_LessLess, OO_GreaterGreater,
2087     OO_Spaceship,
2088     OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2089     OO_EqualEqual, OO_ExclaimEqual,
2090     OO_Amp,
2091     OO_Caret,
2092     OO_Pipe,
2093     OO_AmpAmp,
2094     OO_PipePipe,
2095     OO_Equal, OO_StarEqual,
2096     OO_SlashEqual, OO_PercentEqual,
2097     OO_PlusEqual, OO_MinusEqual,
2098     OO_LessLessEqual, OO_GreaterGreaterEqual,
2099     OO_AmpEqual, OO_CaretEqual,
2100     OO_PipeEqual,
2101     OO_Comma
2102   };
2103   return OverOps[Opc];
2104 }
2105 
2106 bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2107                                                       Opcode Opc,
2108                                                       Expr *LHS, Expr *RHS) {
2109   if (Opc != BO_Add)
2110     return false;
2111 
2112   // Check that we have one pointer and one integer operand.
2113   Expr *PExp;
2114   if (LHS->getType()->isPointerType()) {
2115     if (!RHS->getType()->isIntegerType())
2116       return false;
2117     PExp = LHS;
2118   } else if (RHS->getType()->isPointerType()) {
2119     if (!LHS->getType()->isIntegerType())
2120       return false;
2121     PExp = RHS;
2122   } else {
2123     return false;
2124   }
2125 
2126   // Check that the pointer is a nullptr.
2127   if (!PExp->IgnoreParenCasts()
2128           ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2129     return false;
2130 
2131   // Check that the pointee type is char-sized.
2132   const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2133   if (!PTy || !PTy->getPointeeType()->isCharType())
2134     return false;
2135 
2136   return true;
2137 }
2138 
2139 SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
2140                              QualType ResultTy, SourceLocation BLoc,
2141                              SourceLocation RParenLoc,
2142                              DeclContext *ParentContext)
2143     : Expr(SourceLocExprClass, ResultTy, VK_PRValue, OK_Ordinary),
2144       BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2145   SourceLocExprBits.Kind = Kind;
2146   setDependence(ExprDependence::None);
2147 }
2148 
2149 StringRef SourceLocExpr::getBuiltinStr() const {
2150   switch (getIdentKind()) {
2151   case File:
2152     return "__builtin_FILE";
2153   case Function:
2154     return "__builtin_FUNCTION";
2155   case Line:
2156     return "__builtin_LINE";
2157   case Column:
2158     return "__builtin_COLUMN";
2159   case SourceLocStruct:
2160     return "__builtin_source_location";
2161   }
2162   llvm_unreachable("unexpected IdentKind!");
2163 }
2164 
2165 APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2166                                          const Expr *DefaultExpr) const {
2167   SourceLocation Loc;
2168   const DeclContext *Context;
2169 
2170   std::tie(Loc,
2171            Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2172     if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2173       return {DIE->getUsedLocation(), DIE->getUsedContext()};
2174     if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2175       return {DAE->getUsedLocation(), DAE->getUsedContext()};
2176     return {this->getLocation(), this->getParentContext()};
2177   }();
2178 
2179   PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2180       Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2181 
2182   auto MakeStringLiteral = [&](StringRef Tmp) {
2183     using LValuePathEntry = APValue::LValuePathEntry;
2184     StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2185     // Decay the string to a pointer to the first character.
2186     LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2187     return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2188   };
2189 
2190   switch (getIdentKind()) {
2191   case SourceLocExpr::File: {
2192     SmallString<256> Path(PLoc.getFilename());
2193     Ctx.getLangOpts().remapPathPrefix(Path);
2194     return MakeStringLiteral(Path);
2195   }
2196   case SourceLocExpr::Function: {
2197     const auto *CurDecl = dyn_cast<Decl>(Context);
2198     return MakeStringLiteral(
2199         CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
2200                 : std::string(""));
2201   }
2202   case SourceLocExpr::Line:
2203   case SourceLocExpr::Column: {
2204     llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
2205                         /*isUnsigned=*/true);
2206     IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2207                                                    : PLoc.getColumn();
2208     return APValue(IntVal);
2209   }
2210   case SourceLocExpr::SourceLocStruct: {
2211     // Fill in a std::source_location::__impl structure, by creating an
2212     // artificial file-scoped CompoundLiteralExpr, and returning a pointer to
2213     // that.
2214     const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl();
2215     assert(ImplDecl);
2216 
2217     // Construct an APValue for the __impl struct, and get or create a Decl
2218     // corresponding to that. Note that we've already verified that the shape of
2219     // the ImplDecl type is as expected.
2220 
2221     APValue Value(APValue::UninitStruct(), 0, 4);
2222     for (FieldDecl *F : ImplDecl->fields()) {
2223       StringRef Name = F->getName();
2224       if (Name == "_M_file_name") {
2225         SmallString<256> Path(PLoc.getFilename());
2226         Ctx.getLangOpts().remapPathPrefix(Path);
2227         Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(Path);
2228       } else if (Name == "_M_function_name") {
2229         // Note: this emits the PrettyFunction name -- different than what
2230         // __builtin_FUNCTION() above returns!
2231         const auto *CurDecl = dyn_cast<Decl>(Context);
2232         Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(
2233             CurDecl && !isa<TranslationUnitDecl>(CurDecl)
2234                 ? StringRef(PredefinedExpr::ComputeName(
2235                       PredefinedExpr::PrettyFunction, CurDecl))
2236                 : "");
2237       } else if (Name == "_M_line") {
2238         QualType Ty = F->getType();
2239         llvm::APSInt IntVal(Ctx.getIntWidth(Ty),
2240                             Ty->hasUnsignedIntegerRepresentation());
2241         IntVal = PLoc.getLine();
2242         Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2243       } else if (Name == "_M_column") {
2244         QualType Ty = F->getType();
2245         llvm::APSInt IntVal(Ctx.getIntWidth(Ty),
2246                             Ty->hasUnsignedIntegerRepresentation());
2247         IntVal = PLoc.getColumn();
2248         Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2249       }
2250     }
2251 
2252     UnnamedGlobalConstantDecl *GV =
2253         Ctx.getUnnamedGlobalConstantDecl(getType()->getPointeeType(), Value);
2254 
2255     return APValue(GV, CharUnits::Zero(), ArrayRef<APValue::LValuePathEntry>{},
2256                    false);
2257   }
2258   }
2259   llvm_unreachable("unhandled case");
2260 }
2261 
2262 InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
2263                            ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2264     : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
2265       InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2266       RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2267   sawArrayRangeDesignator(false);
2268   InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2269 
2270   setDependence(computeDependence(this));
2271 }
2272 
2273 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2274   if (NumInits > InitExprs.size())
2275     InitExprs.reserve(C, NumInits);
2276 }
2277 
2278 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2279   InitExprs.resize(C, NumInits, nullptr);
2280 }
2281 
2282 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2283   if (Init >= InitExprs.size()) {
2284     InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2285     setInit(Init, expr);
2286     return nullptr;
2287   }
2288 
2289   Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2290   setInit(Init, expr);
2291   return Result;
2292 }
2293 
2294 void InitListExpr::setArrayFiller(Expr *filler) {
2295   assert(!hasArrayFiller() && "Filler already set!");
2296   ArrayFillerOrUnionFieldInit = filler;
2297   // Fill out any "holes" in the array due to designated initializers.
2298   Expr **inits = getInits();
2299   for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2300     if (inits[i] == nullptr)
2301       inits[i] = filler;
2302 }
2303 
2304 bool InitListExpr::isStringLiteralInit() const {
2305   if (getNumInits() != 1)
2306     return false;
2307   const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2308   if (!AT || !AT->getElementType()->isIntegerType())
2309     return false;
2310   // It is possible for getInit() to return null.
2311   const Expr *Init = getInit(0);
2312   if (!Init)
2313     return false;
2314   Init = Init->IgnoreParenImpCasts();
2315   return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2316 }
2317 
2318 bool InitListExpr::isTransparent() const {
2319   assert(isSemanticForm() && "syntactic form never semantically transparent");
2320 
2321   // A glvalue InitListExpr is always just sugar.
2322   if (isGLValue()) {
2323     assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2324     return true;
2325   }
2326 
2327   // Otherwise, we're sugar if and only if we have exactly one initializer that
2328   // is of the same type.
2329   if (getNumInits() != 1 || !getInit(0))
2330     return false;
2331 
2332   // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2333   // transparent struct copy.
2334   if (!getInit(0)->isPRValue() && getType()->isRecordType())
2335     return false;
2336 
2337   return getType().getCanonicalType() ==
2338          getInit(0)->getType().getCanonicalType();
2339 }
2340 
2341 bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2342   assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2343 
2344   if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2345     return false;
2346   }
2347 
2348   const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2349   return Lit && Lit->getValue() == 0;
2350 }
2351 
2352 SourceLocation InitListExpr::getBeginLoc() const {
2353   if (InitListExpr *SyntacticForm = getSyntacticForm())
2354     return SyntacticForm->getBeginLoc();
2355   SourceLocation Beg = LBraceLoc;
2356   if (Beg.isInvalid()) {
2357     // Find the first non-null initializer.
2358     for (InitExprsTy::const_iterator I = InitExprs.begin(),
2359                                      E = InitExprs.end();
2360       I != E; ++I) {
2361       if (Stmt *S = *I) {
2362         Beg = S->getBeginLoc();
2363         break;
2364       }
2365     }
2366   }
2367   return Beg;
2368 }
2369 
2370 SourceLocation InitListExpr::getEndLoc() const {
2371   if (InitListExpr *SyntacticForm = getSyntacticForm())
2372     return SyntacticForm->getEndLoc();
2373   SourceLocation End = RBraceLoc;
2374   if (End.isInvalid()) {
2375     // Find the first non-null initializer from the end.
2376     for (Stmt *S : llvm::reverse(InitExprs)) {
2377       if (S) {
2378         End = S->getEndLoc();
2379         break;
2380       }
2381     }
2382   }
2383   return End;
2384 }
2385 
2386 /// getFunctionType - Return the underlying function type for this block.
2387 ///
2388 const FunctionProtoType *BlockExpr::getFunctionType() const {
2389   // The block pointer is never sugared, but the function type might be.
2390   return cast<BlockPointerType>(getType())
2391            ->getPointeeType()->castAs<FunctionProtoType>();
2392 }
2393 
2394 SourceLocation BlockExpr::getCaretLocation() const {
2395   return TheBlock->getCaretLocation();
2396 }
2397 const Stmt *BlockExpr::getBody() const {
2398   return TheBlock->getBody();
2399 }
2400 Stmt *BlockExpr::getBody() {
2401   return TheBlock->getBody();
2402 }
2403 
2404 
2405 //===----------------------------------------------------------------------===//
2406 // Generic Expression Routines
2407 //===----------------------------------------------------------------------===//
2408 
2409 bool Expr::isReadIfDiscardedInCPlusPlus11() const {
2410   // In C++11, discarded-value expressions of a certain form are special,
2411   // according to [expr]p10:
2412   //   The lvalue-to-rvalue conversion (4.1) is applied only if the
2413   //   expression is a glvalue of volatile-qualified type and it has
2414   //   one of the following forms:
2415   if (!isGLValue() || !getType().isVolatileQualified())
2416     return false;
2417 
2418   const Expr *E = IgnoreParens();
2419 
2420   //   - id-expression (5.1.1),
2421   if (isa<DeclRefExpr>(E))
2422     return true;
2423 
2424   //   - subscripting (5.2.1),
2425   if (isa<ArraySubscriptExpr>(E))
2426     return true;
2427 
2428   //   - class member access (5.2.5),
2429   if (isa<MemberExpr>(E))
2430     return true;
2431 
2432   //   - indirection (5.3.1),
2433   if (auto *UO = dyn_cast<UnaryOperator>(E))
2434     if (UO->getOpcode() == UO_Deref)
2435       return true;
2436 
2437   if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2438     //   - pointer-to-member operation (5.5),
2439     if (BO->isPtrMemOp())
2440       return true;
2441 
2442     //   - comma expression (5.18) where the right operand is one of the above.
2443     if (BO->getOpcode() == BO_Comma)
2444       return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2445   }
2446 
2447   //   - conditional expression (5.16) where both the second and the third
2448   //     operands are one of the above, or
2449   if (auto *CO = dyn_cast<ConditionalOperator>(E))
2450     return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2451            CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2452   // The related edge case of "*x ?: *x".
2453   if (auto *BCO =
2454           dyn_cast<BinaryConditionalOperator>(E)) {
2455     if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
2456       return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2457              BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2458   }
2459 
2460   // Objective-C++ extensions to the rule.
2461   if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
2462     return true;
2463 
2464   return false;
2465 }
2466 
2467 /// isUnusedResultAWarning - Return true if this immediate expression should
2468 /// be warned about if the result is unused.  If so, fill in Loc and Ranges
2469 /// with location to warn on and the source range[s] to report with the
2470 /// warning.
2471 bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2472                                   SourceRange &R1, SourceRange &R2,
2473                                   ASTContext &Ctx) const {
2474   // Don't warn if the expr is type dependent. The type could end up
2475   // instantiating to void.
2476   if (isTypeDependent())
2477     return false;
2478 
2479   switch (getStmtClass()) {
2480   default:
2481     if (getType()->isVoidType())
2482       return false;
2483     WarnE = this;
2484     Loc = getExprLoc();
2485     R1 = getSourceRange();
2486     return true;
2487   case ParenExprClass:
2488     return cast<ParenExpr>(this)->getSubExpr()->
2489       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2490   case GenericSelectionExprClass:
2491     return cast<GenericSelectionExpr>(this)->getResultExpr()->
2492       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2493   case CoawaitExprClass:
2494   case CoyieldExprClass:
2495     return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2496       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2497   case ChooseExprClass:
2498     return cast<ChooseExpr>(this)->getChosenSubExpr()->
2499       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2500   case UnaryOperatorClass: {
2501     const UnaryOperator *UO = cast<UnaryOperator>(this);
2502 
2503     switch (UO->getOpcode()) {
2504     case UO_Plus:
2505     case UO_Minus:
2506     case UO_AddrOf:
2507     case UO_Not:
2508     case UO_LNot:
2509     case UO_Deref:
2510       break;
2511     case UO_Coawait:
2512       // This is just the 'operator co_await' call inside the guts of a
2513       // dependent co_await call.
2514     case UO_PostInc:
2515     case UO_PostDec:
2516     case UO_PreInc:
2517     case UO_PreDec:                 // ++/--
2518       return false;  // Not a warning.
2519     case UO_Real:
2520     case UO_Imag:
2521       // accessing a piece of a volatile complex is a side-effect.
2522       if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2523           .isVolatileQualified())
2524         return false;
2525       break;
2526     case UO_Extension:
2527       return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2528     }
2529     WarnE = this;
2530     Loc = UO->getOperatorLoc();
2531     R1 = UO->getSubExpr()->getSourceRange();
2532     return true;
2533   }
2534   case BinaryOperatorClass: {
2535     const BinaryOperator *BO = cast<BinaryOperator>(this);
2536     switch (BO->getOpcode()) {
2537       default:
2538         break;
2539       // Consider the RHS of comma for side effects. LHS was checked by
2540       // Sema::CheckCommaOperands.
2541       case BO_Comma:
2542         // ((foo = <blah>), 0) is an idiom for hiding the result (and
2543         // lvalue-ness) of an assignment written in a macro.
2544         if (IntegerLiteral *IE =
2545               dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2546           if (IE->getValue() == 0)
2547             return false;
2548         return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2549       // Consider '||', '&&' to have side effects if the LHS or RHS does.
2550       case BO_LAnd:
2551       case BO_LOr:
2552         if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2553             !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2554           return false;
2555         break;
2556     }
2557     if (BO->isAssignmentOp())
2558       return false;
2559     WarnE = this;
2560     Loc = BO->getOperatorLoc();
2561     R1 = BO->getLHS()->getSourceRange();
2562     R2 = BO->getRHS()->getSourceRange();
2563     return true;
2564   }
2565   case CompoundAssignOperatorClass:
2566   case VAArgExprClass:
2567   case AtomicExprClass:
2568     return false;
2569 
2570   case ConditionalOperatorClass: {
2571     // If only one of the LHS or RHS is a warning, the operator might
2572     // be being used for control flow. Only warn if both the LHS and
2573     // RHS are warnings.
2574     const auto *Exp = cast<ConditionalOperator>(this);
2575     return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2576            Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2577   }
2578   case BinaryConditionalOperatorClass: {
2579     const auto *Exp = cast<BinaryConditionalOperator>(this);
2580     return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2581   }
2582 
2583   case MemberExprClass:
2584     WarnE = this;
2585     Loc = cast<MemberExpr>(this)->getMemberLoc();
2586     R1 = SourceRange(Loc, Loc);
2587     R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2588     return true;
2589 
2590   case ArraySubscriptExprClass:
2591     WarnE = this;
2592     Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2593     R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2594     R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2595     return true;
2596 
2597   case CXXOperatorCallExprClass: {
2598     // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2599     // overloads as there is no reasonable way to define these such that they
2600     // have non-trivial, desirable side-effects. See the -Wunused-comparison
2601     // warning: operators == and != are commonly typo'ed, and so warning on them
2602     // provides additional value as well. If this list is updated,
2603     // DiagnoseUnusedComparison should be as well.
2604     const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2605     switch (Op->getOperator()) {
2606     default:
2607       break;
2608     case OO_EqualEqual:
2609     case OO_ExclaimEqual:
2610     case OO_Less:
2611     case OO_Greater:
2612     case OO_GreaterEqual:
2613     case OO_LessEqual:
2614       if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2615           Op->getCallReturnType(Ctx)->isVoidType())
2616         break;
2617       WarnE = this;
2618       Loc = Op->getOperatorLoc();
2619       R1 = Op->getSourceRange();
2620       return true;
2621     }
2622 
2623     // Fallthrough for generic call handling.
2624     LLVM_FALLTHROUGH;
2625   }
2626   case CallExprClass:
2627   case CXXMemberCallExprClass:
2628   case UserDefinedLiteralClass: {
2629     // If this is a direct call, get the callee.
2630     const CallExpr *CE = cast<CallExpr>(this);
2631     if (const Decl *FD = CE->getCalleeDecl()) {
2632       // If the callee has attribute pure, const, or warn_unused_result, warn
2633       // about it. void foo() { strlen("bar"); } should warn.
2634       //
2635       // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2636       // updated to match for QoI.
2637       if (CE->hasUnusedResultAttr(Ctx) ||
2638           FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2639         WarnE = this;
2640         Loc = CE->getCallee()->getBeginLoc();
2641         R1 = CE->getCallee()->getSourceRange();
2642 
2643         if (unsigned NumArgs = CE->getNumArgs())
2644           R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2645                            CE->getArg(NumArgs - 1)->getEndLoc());
2646         return true;
2647       }
2648     }
2649     return false;
2650   }
2651 
2652   // If we don't know precisely what we're looking at, let's not warn.
2653   case UnresolvedLookupExprClass:
2654   case CXXUnresolvedConstructExprClass:
2655   case RecoveryExprClass:
2656     return false;
2657 
2658   case CXXTemporaryObjectExprClass:
2659   case CXXConstructExprClass: {
2660     if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2661       const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2662       if (Type->hasAttr<WarnUnusedAttr>() ||
2663           (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2664         WarnE = this;
2665         Loc = getBeginLoc();
2666         R1 = getSourceRange();
2667         return true;
2668       }
2669     }
2670 
2671     const auto *CE = cast<CXXConstructExpr>(this);
2672     if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2673       const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2674       if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2675         WarnE = this;
2676         Loc = getBeginLoc();
2677         R1 = getSourceRange();
2678 
2679         if (unsigned NumArgs = CE->getNumArgs())
2680           R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2681                            CE->getArg(NumArgs - 1)->getEndLoc());
2682         return true;
2683       }
2684     }
2685 
2686     return false;
2687   }
2688 
2689   case ObjCMessageExprClass: {
2690     const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2691     if (Ctx.getLangOpts().ObjCAutoRefCount &&
2692         ME->isInstanceMessage() &&
2693         !ME->getType()->isVoidType() &&
2694         ME->getMethodFamily() == OMF_init) {
2695       WarnE = this;
2696       Loc = getExprLoc();
2697       R1 = ME->getSourceRange();
2698       return true;
2699     }
2700 
2701     if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2702       if (MD->hasAttr<WarnUnusedResultAttr>()) {
2703         WarnE = this;
2704         Loc = getExprLoc();
2705         return true;
2706       }
2707 
2708     return false;
2709   }
2710 
2711   case ObjCPropertyRefExprClass:
2712     WarnE = this;
2713     Loc = getExprLoc();
2714     R1 = getSourceRange();
2715     return true;
2716 
2717   case PseudoObjectExprClass: {
2718     const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2719 
2720     // Only complain about things that have the form of a getter.
2721     if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2722         isa<BinaryOperator>(PO->getSyntacticForm()))
2723       return false;
2724 
2725     WarnE = this;
2726     Loc = getExprLoc();
2727     R1 = getSourceRange();
2728     return true;
2729   }
2730 
2731   case StmtExprClass: {
2732     // Statement exprs don't logically have side effects themselves, but are
2733     // sometimes used in macros in ways that give them a type that is unused.
2734     // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2735     // however, if the result of the stmt expr is dead, we don't want to emit a
2736     // warning.
2737     const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2738     if (!CS->body_empty()) {
2739       if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2740         return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2741       if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2742         if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2743           return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2744     }
2745 
2746     if (getType()->isVoidType())
2747       return false;
2748     WarnE = this;
2749     Loc = cast<StmtExpr>(this)->getLParenLoc();
2750     R1 = getSourceRange();
2751     return true;
2752   }
2753   case CXXFunctionalCastExprClass:
2754   case CStyleCastExprClass: {
2755     // Ignore an explicit cast to void, except in C++98 if the operand is a
2756     // volatile glvalue for which we would trigger an implicit read in any
2757     // other language mode. (Such an implicit read always happens as part of
2758     // the lvalue conversion in C, and happens in C++ for expressions of all
2759     // forms where it seems likely the user intended to trigger a volatile
2760     // load.)
2761     const CastExpr *CE = cast<CastExpr>(this);
2762     const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2763     if (CE->getCastKind() == CK_ToVoid) {
2764       if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2765           SubE->isReadIfDiscardedInCPlusPlus11()) {
2766         // Suppress the "unused value" warning for idiomatic usage of
2767         // '(void)var;' used to suppress "unused variable" warnings.
2768         if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
2769           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2770             if (!VD->isExternallyVisible())
2771               return false;
2772 
2773         // The lvalue-to-rvalue conversion would have no effect for an array.
2774         // It's implausible that the programmer expected this to result in a
2775         // volatile array load, so don't warn.
2776         if (SubE->getType()->isArrayType())
2777           return false;
2778 
2779         return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2780       }
2781       return false;
2782     }
2783 
2784     // If this is a cast to a constructor conversion, check the operand.
2785     // Otherwise, the result of the cast is unused.
2786     if (CE->getCastKind() == CK_ConstructorConversion)
2787       return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2788     if (CE->getCastKind() == CK_Dependent)
2789       return false;
2790 
2791     WarnE = this;
2792     if (const CXXFunctionalCastExpr *CXXCE =
2793             dyn_cast<CXXFunctionalCastExpr>(this)) {
2794       Loc = CXXCE->getBeginLoc();
2795       R1 = CXXCE->getSubExpr()->getSourceRange();
2796     } else {
2797       const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2798       Loc = CStyleCE->getLParenLoc();
2799       R1 = CStyleCE->getSubExpr()->getSourceRange();
2800     }
2801     return true;
2802   }
2803   case ImplicitCastExprClass: {
2804     const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2805 
2806     // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2807     if (ICE->getCastKind() == CK_LValueToRValue &&
2808         ICE->getSubExpr()->getType().isVolatileQualified())
2809       return false;
2810 
2811     return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2812   }
2813   case CXXDefaultArgExprClass:
2814     return (cast<CXXDefaultArgExpr>(this)
2815             ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2816   case CXXDefaultInitExprClass:
2817     return (cast<CXXDefaultInitExpr>(this)
2818             ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2819 
2820   case CXXNewExprClass:
2821     // FIXME: In theory, there might be new expressions that don't have side
2822     // effects (e.g. a placement new with an uninitialized POD).
2823   case CXXDeleteExprClass:
2824     return false;
2825   case MaterializeTemporaryExprClass:
2826     return cast<MaterializeTemporaryExpr>(this)
2827         ->getSubExpr()
2828         ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2829   case CXXBindTemporaryExprClass:
2830     return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2831                ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2832   case ExprWithCleanupsClass:
2833     return cast<ExprWithCleanups>(this)->getSubExpr()
2834                ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2835   }
2836 }
2837 
2838 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2839 /// returns true, if it is; false otherwise.
2840 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2841   const Expr *E = IgnoreParens();
2842   switch (E->getStmtClass()) {
2843   default:
2844     return false;
2845   case ObjCIvarRefExprClass:
2846     return true;
2847   case Expr::UnaryOperatorClass:
2848     return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2849   case ImplicitCastExprClass:
2850     return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2851   case MaterializeTemporaryExprClass:
2852     return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
2853         Ctx);
2854   case CStyleCastExprClass:
2855     return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2856   case DeclRefExprClass: {
2857     const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2858 
2859     if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2860       if (VD->hasGlobalStorage())
2861         return true;
2862       QualType T = VD->getType();
2863       // dereferencing to a  pointer is always a gc'able candidate,
2864       // unless it is __weak.
2865       return T->isPointerType() &&
2866              (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2867     }
2868     return false;
2869   }
2870   case MemberExprClass: {
2871     const MemberExpr *M = cast<MemberExpr>(E);
2872     return M->getBase()->isOBJCGCCandidate(Ctx);
2873   }
2874   case ArraySubscriptExprClass:
2875     return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2876   }
2877 }
2878 
2879 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2880   if (isTypeDependent())
2881     return false;
2882   return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2883 }
2884 
2885 QualType Expr::findBoundMemberType(const Expr *expr) {
2886   assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2887 
2888   // Bound member expressions are always one of these possibilities:
2889   //   x->m      x.m      x->*y      x.*y
2890   // (possibly parenthesized)
2891 
2892   expr = expr->IgnoreParens();
2893   if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2894     assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2895     return mem->getMemberDecl()->getType();
2896   }
2897 
2898   if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2899     QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2900                       ->getPointeeType();
2901     assert(type->isFunctionType());
2902     return type;
2903   }
2904 
2905   assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
2906   return QualType();
2907 }
2908 
2909 Expr *Expr::IgnoreImpCasts() {
2910   return IgnoreExprNodes(this, IgnoreImplicitCastsSingleStep);
2911 }
2912 
2913 Expr *Expr::IgnoreCasts() {
2914   return IgnoreExprNodes(this, IgnoreCastsSingleStep);
2915 }
2916 
2917 Expr *Expr::IgnoreImplicit() {
2918   return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
2919 }
2920 
2921 Expr *Expr::IgnoreImplicitAsWritten() {
2922   return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);
2923 }
2924 
2925 Expr *Expr::IgnoreParens() {
2926   return IgnoreExprNodes(this, IgnoreParensSingleStep);
2927 }
2928 
2929 Expr *Expr::IgnoreParenImpCasts() {
2930   return IgnoreExprNodes(this, IgnoreParensSingleStep,
2931                          IgnoreImplicitCastsExtraSingleStep);
2932 }
2933 
2934 Expr *Expr::IgnoreParenCasts() {
2935   return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
2936 }
2937 
2938 Expr *Expr::IgnoreConversionOperatorSingleStep() {
2939   if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2940     if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2941       return MCE->getImplicitObjectArgument();
2942   }
2943   return this;
2944 }
2945 
2946 Expr *Expr::IgnoreParenLValueCasts() {
2947   return IgnoreExprNodes(this, IgnoreParensSingleStep,
2948                          IgnoreLValueCastsSingleStep);
2949 }
2950 
2951 Expr *Expr::IgnoreParenBaseCasts() {
2952   return IgnoreExprNodes(this, IgnoreParensSingleStep,
2953                          IgnoreBaseCastsSingleStep);
2954 }
2955 
2956 Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
2957   auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
2958     if (auto *CE = dyn_cast<CastExpr>(E)) {
2959       // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2960       // ptr<->int casts of the same width. We also ignore all identity casts.
2961       Expr *SubExpr = CE->getSubExpr();
2962       bool IsIdentityCast =
2963           Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2964       bool IsSameWidthCast = (E->getType()->isPointerType() ||
2965                               E->getType()->isIntegralType(Ctx)) &&
2966                              (SubExpr->getType()->isPointerType() ||
2967                               SubExpr->getType()->isIntegralType(Ctx)) &&
2968                              (Ctx.getTypeSize(E->getType()) ==
2969                               Ctx.getTypeSize(SubExpr->getType()));
2970 
2971       if (IsIdentityCast || IsSameWidthCast)
2972         return SubExpr;
2973     } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2974       return NTTP->getReplacement();
2975 
2976     return E;
2977   };
2978   return IgnoreExprNodes(this, IgnoreParensSingleStep,
2979                          IgnoreNoopCastsSingleStep);
2980 }
2981 
2982 Expr *Expr::IgnoreUnlessSpelledInSource() {
2983   auto IgnoreImplicitConstructorSingleStep = [](Expr *E) {
2984     if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {
2985       auto *SE = Cast->getSubExpr();
2986       if (SE->getSourceRange() == E->getSourceRange())
2987         return SE;
2988     }
2989 
2990     if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
2991       auto NumArgs = C->getNumArgs();
2992       if (NumArgs == 1 ||
2993           (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
2994         Expr *A = C->getArg(0);
2995         if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
2996           return A;
2997       }
2998     }
2999     return E;
3000   };
3001   auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
3002     if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
3003       Expr *ExprNode = C->getImplicitObjectArgument();
3004       if (ExprNode->getSourceRange() == E->getSourceRange()) {
3005         return ExprNode;
3006       }
3007       if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
3008         if (PE->getSourceRange() == C->getSourceRange()) {
3009           return cast<Expr>(PE);
3010         }
3011       }
3012       ExprNode = ExprNode->IgnoreParenImpCasts();
3013       if (ExprNode->getSourceRange() == E->getSourceRange())
3014         return ExprNode;
3015     }
3016     return E;
3017   };
3018   return IgnoreExprNodes(
3019       this, IgnoreImplicitSingleStep, IgnoreImplicitCastsExtraSingleStep,
3020       IgnoreParensOnlySingleStep, IgnoreImplicitConstructorSingleStep,
3021       IgnoreImplicitMemberCallSingleStep);
3022 }
3023 
3024 bool Expr::isDefaultArgument() const {
3025   const Expr *E = this;
3026   if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3027     E = M->getSubExpr();
3028 
3029   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3030     E = ICE->getSubExprAsWritten();
3031 
3032   return isa<CXXDefaultArgExpr>(E);
3033 }
3034 
3035 /// Skip over any no-op casts and any temporary-binding
3036 /// expressions.
3037 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
3038   if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3039     E = M->getSubExpr();
3040 
3041   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3042     if (ICE->getCastKind() == CK_NoOp)
3043       E = ICE->getSubExpr();
3044     else
3045       break;
3046   }
3047 
3048   while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3049     E = BE->getSubExpr();
3050 
3051   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3052     if (ICE->getCastKind() == CK_NoOp)
3053       E = ICE->getSubExpr();
3054     else
3055       break;
3056   }
3057 
3058   return E->IgnoreParens();
3059 }
3060 
3061 /// isTemporaryObject - Determines if this expression produces a
3062 /// temporary of the given class type.
3063 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3064   if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3065     return false;
3066 
3067   const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
3068 
3069   // Temporaries are by definition pr-values of class type.
3070   if (!E->Classify(C).isPRValue()) {
3071     // In this context, property reference is a message call and is pr-value.
3072     if (!isa<ObjCPropertyRefExpr>(E))
3073       return false;
3074   }
3075 
3076   // Black-list a few cases which yield pr-values of class type that don't
3077   // refer to temporaries of that type:
3078 
3079   // - implicit derived-to-base conversions
3080   if (isa<ImplicitCastExpr>(E)) {
3081     switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3082     case CK_DerivedToBase:
3083     case CK_UncheckedDerivedToBase:
3084       return false;
3085     default:
3086       break;
3087     }
3088   }
3089 
3090   // - member expressions (all)
3091   if (isa<MemberExpr>(E))
3092     return false;
3093 
3094   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3095     if (BO->isPtrMemOp())
3096       return false;
3097 
3098   // - opaque values (all)
3099   if (isa<OpaqueValueExpr>(E))
3100     return false;
3101 
3102   return true;
3103 }
3104 
3105 bool Expr::isImplicitCXXThis() const {
3106   const Expr *E = this;
3107 
3108   // Strip away parentheses and casts we don't care about.
3109   while (true) {
3110     if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3111       E = Paren->getSubExpr();
3112       continue;
3113     }
3114 
3115     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3116       if (ICE->getCastKind() == CK_NoOp ||
3117           ICE->getCastKind() == CK_LValueToRValue ||
3118           ICE->getCastKind() == CK_DerivedToBase ||
3119           ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3120         E = ICE->getSubExpr();
3121         continue;
3122       }
3123     }
3124 
3125     if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3126       if (UnOp->getOpcode() == UO_Extension) {
3127         E = UnOp->getSubExpr();
3128         continue;
3129       }
3130     }
3131 
3132     if (const MaterializeTemporaryExpr *M
3133                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
3134       E = M->getSubExpr();
3135       continue;
3136     }
3137 
3138     break;
3139   }
3140 
3141   if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3142     return This->isImplicit();
3143 
3144   return false;
3145 }
3146 
3147 /// hasAnyTypeDependentArguments - Determines if any of the expressions
3148 /// in Exprs is type-dependent.
3149 bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
3150   for (unsigned I = 0; I < Exprs.size(); ++I)
3151     if (Exprs[I]->isTypeDependent())
3152       return true;
3153 
3154   return false;
3155 }
3156 
3157 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3158                                  const Expr **Culprit) const {
3159   assert(!isValueDependent() &&
3160          "Expression evaluator can't be called on a dependent expression.");
3161 
3162   // This function is attempting whether an expression is an initializer
3163   // which can be evaluated at compile-time. It very closely parallels
3164   // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3165   // will lead to unexpected results.  Like ConstExprEmitter, it falls back
3166   // to isEvaluatable most of the time.
3167   //
3168   // If we ever capture reference-binding directly in the AST, we can
3169   // kill the second parameter.
3170 
3171   if (IsForRef) {
3172     EvalResult Result;
3173     if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3174       return true;
3175     if (Culprit)
3176       *Culprit = this;
3177     return false;
3178   }
3179 
3180   switch (getStmtClass()) {
3181   default: break;
3182   case Stmt::ExprWithCleanupsClass:
3183     return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3184         Ctx, IsForRef, Culprit);
3185   case StringLiteralClass:
3186   case ObjCEncodeExprClass:
3187     return true;
3188   case CXXTemporaryObjectExprClass:
3189   case CXXConstructExprClass: {
3190     const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3191 
3192     if (CE->getConstructor()->isTrivial() &&
3193         CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3194       // Trivial default constructor
3195       if (!CE->getNumArgs()) return true;
3196 
3197       // Trivial copy constructor
3198       assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3199       return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3200     }
3201 
3202     break;
3203   }
3204   case ConstantExprClass: {
3205     // FIXME: We should be able to return "true" here, but it can lead to extra
3206     // error messages. E.g. in Sema/array-init.c.
3207     const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3208     return Exp->isConstantInitializer(Ctx, false, Culprit);
3209   }
3210   case CompoundLiteralExprClass: {
3211     // This handles gcc's extension that allows global initializers like
3212     // "struct x {int x;} x = (struct x) {};".
3213     // FIXME: This accepts other cases it shouldn't!
3214     const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3215     return Exp->isConstantInitializer(Ctx, false, Culprit);
3216   }
3217   case DesignatedInitUpdateExprClass: {
3218     const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3219     return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3220            DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3221   }
3222   case InitListExprClass: {
3223     const InitListExpr *ILE = cast<InitListExpr>(this);
3224     assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3225     if (ILE->getType()->isArrayType()) {
3226       unsigned numInits = ILE->getNumInits();
3227       for (unsigned i = 0; i < numInits; i++) {
3228         if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3229           return false;
3230       }
3231       return true;
3232     }
3233 
3234     if (ILE->getType()->isRecordType()) {
3235       unsigned ElementNo = 0;
3236       RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
3237       for (const auto *Field : RD->fields()) {
3238         // If this is a union, skip all the fields that aren't being initialized.
3239         if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3240           continue;
3241 
3242         // Don't emit anonymous bitfields, they just affect layout.
3243         if (Field->isUnnamedBitfield())
3244           continue;
3245 
3246         if (ElementNo < ILE->getNumInits()) {
3247           const Expr *Elt = ILE->getInit(ElementNo++);
3248           if (Field->isBitField()) {
3249             // Bitfields have to evaluate to an integer.
3250             EvalResult Result;
3251             if (!Elt->EvaluateAsInt(Result, Ctx)) {
3252               if (Culprit)
3253                 *Culprit = Elt;
3254               return false;
3255             }
3256           } else {
3257             bool RefType = Field->getType()->isReferenceType();
3258             if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3259               return false;
3260           }
3261         }
3262       }
3263       return true;
3264     }
3265 
3266     break;
3267   }
3268   case ImplicitValueInitExprClass:
3269   case NoInitExprClass:
3270     return true;
3271   case ParenExprClass:
3272     return cast<ParenExpr>(this)->getSubExpr()
3273       ->isConstantInitializer(Ctx, IsForRef, Culprit);
3274   case GenericSelectionExprClass:
3275     return cast<GenericSelectionExpr>(this)->getResultExpr()
3276       ->isConstantInitializer(Ctx, IsForRef, Culprit);
3277   case ChooseExprClass:
3278     if (cast<ChooseExpr>(this)->isConditionDependent()) {
3279       if (Culprit)
3280         *Culprit = this;
3281       return false;
3282     }
3283     return cast<ChooseExpr>(this)->getChosenSubExpr()
3284       ->isConstantInitializer(Ctx, IsForRef, Culprit);
3285   case UnaryOperatorClass: {
3286     const UnaryOperator* Exp = cast<UnaryOperator>(this);
3287     if (Exp->getOpcode() == UO_Extension)
3288       return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3289     break;
3290   }
3291   case CXXFunctionalCastExprClass:
3292   case CXXStaticCastExprClass:
3293   case ImplicitCastExprClass:
3294   case CStyleCastExprClass:
3295   case ObjCBridgedCastExprClass:
3296   case CXXDynamicCastExprClass:
3297   case CXXReinterpretCastExprClass:
3298   case CXXAddrspaceCastExprClass:
3299   case CXXConstCastExprClass: {
3300     const CastExpr *CE = cast<CastExpr>(this);
3301 
3302     // Handle misc casts we want to ignore.
3303     if (CE->getCastKind() == CK_NoOp ||
3304         CE->getCastKind() == CK_LValueToRValue ||
3305         CE->getCastKind() == CK_ToUnion ||
3306         CE->getCastKind() == CK_ConstructorConversion ||
3307         CE->getCastKind() == CK_NonAtomicToAtomic ||
3308         CE->getCastKind() == CK_AtomicToNonAtomic ||
3309         CE->getCastKind() == CK_IntToOCLSampler)
3310       return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3311 
3312     break;
3313   }
3314   case MaterializeTemporaryExprClass:
3315     return cast<MaterializeTemporaryExpr>(this)
3316         ->getSubExpr()
3317         ->isConstantInitializer(Ctx, false, Culprit);
3318 
3319   case SubstNonTypeTemplateParmExprClass:
3320     return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3321       ->isConstantInitializer(Ctx, false, Culprit);
3322   case CXXDefaultArgExprClass:
3323     return cast<CXXDefaultArgExpr>(this)->getExpr()
3324       ->isConstantInitializer(Ctx, false, Culprit);
3325   case CXXDefaultInitExprClass:
3326     return cast<CXXDefaultInitExpr>(this)->getExpr()
3327       ->isConstantInitializer(Ctx, false, Culprit);
3328   }
3329   // Allow certain forms of UB in constant initializers: signed integer
3330   // overflow and floating-point division by zero. We'll give a warning on
3331   // these, but they're common enough that we have to accept them.
3332   if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
3333     return true;
3334   if (Culprit)
3335     *Culprit = this;
3336   return false;
3337 }
3338 
3339 bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3340   const FunctionDecl* FD = getDirectCallee();
3341   if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3342               FD->getBuiltinID() != Builtin::BI__builtin_assume))
3343     return false;
3344 
3345   const Expr* Arg = getArg(0);
3346   bool ArgVal;
3347   return !Arg->isValueDependent() &&
3348          Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3349 }
3350 
3351 namespace {
3352   /// Look for any side effects within a Stmt.
3353   class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3354     typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
3355     const bool IncludePossibleEffects;
3356     bool HasSideEffects;
3357 
3358   public:
3359     explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3360       : Inherited(Context),
3361         IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3362 
3363     bool hasSideEffects() const { return HasSideEffects; }
3364 
3365     void VisitDecl(const Decl *D) {
3366       if (!D)
3367         return;
3368 
3369       // We assume the caller checks subexpressions (eg, the initializer, VLA
3370       // bounds) for side-effects on our behalf.
3371       if (auto *VD = dyn_cast<VarDecl>(D)) {
3372         // Registering a destructor is a side-effect.
3373         if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3374             VD->needsDestruction(Context))
3375           HasSideEffects = true;
3376       }
3377     }
3378 
3379     void VisitDeclStmt(const DeclStmt *DS) {
3380       for (auto *D : DS->decls())
3381         VisitDecl(D);
3382       Inherited::VisitDeclStmt(DS);
3383     }
3384 
3385     void VisitExpr(const Expr *E) {
3386       if (!HasSideEffects &&
3387           E->HasSideEffects(Context, IncludePossibleEffects))
3388         HasSideEffects = true;
3389     }
3390   };
3391 }
3392 
3393 bool Expr::HasSideEffects(const ASTContext &Ctx,
3394                           bool IncludePossibleEffects) const {
3395   // In circumstances where we care about definite side effects instead of
3396   // potential side effects, we want to ignore expressions that are part of a
3397   // macro expansion as a potential side effect.
3398   if (!IncludePossibleEffects && getExprLoc().isMacroID())
3399     return false;
3400 
3401   switch (getStmtClass()) {
3402   case NoStmtClass:
3403   #define ABSTRACT_STMT(Type)
3404   #define STMT(Type, Base) case Type##Class:
3405   #define EXPR(Type, Base)
3406   #include "clang/AST/StmtNodes.inc"
3407     llvm_unreachable("unexpected Expr kind");
3408 
3409   case DependentScopeDeclRefExprClass:
3410   case CXXUnresolvedConstructExprClass:
3411   case CXXDependentScopeMemberExprClass:
3412   case UnresolvedLookupExprClass:
3413   case UnresolvedMemberExprClass:
3414   case PackExpansionExprClass:
3415   case SubstNonTypeTemplateParmPackExprClass:
3416   case FunctionParmPackExprClass:
3417   case TypoExprClass:
3418   case RecoveryExprClass:
3419   case CXXFoldExprClass:
3420     // Make a conservative assumption for dependent nodes.
3421     return IncludePossibleEffects;
3422 
3423   case DeclRefExprClass:
3424   case ObjCIvarRefExprClass:
3425   case PredefinedExprClass:
3426   case IntegerLiteralClass:
3427   case FixedPointLiteralClass:
3428   case FloatingLiteralClass:
3429   case ImaginaryLiteralClass:
3430   case StringLiteralClass:
3431   case CharacterLiteralClass:
3432   case OffsetOfExprClass:
3433   case ImplicitValueInitExprClass:
3434   case UnaryExprOrTypeTraitExprClass:
3435   case AddrLabelExprClass:
3436   case GNUNullExprClass:
3437   case ArrayInitIndexExprClass:
3438   case NoInitExprClass:
3439   case CXXBoolLiteralExprClass:
3440   case CXXNullPtrLiteralExprClass:
3441   case CXXThisExprClass:
3442   case CXXScalarValueInitExprClass:
3443   case TypeTraitExprClass:
3444   case ArrayTypeTraitExprClass:
3445   case ExpressionTraitExprClass:
3446   case CXXNoexceptExprClass:
3447   case SizeOfPackExprClass:
3448   case ObjCStringLiteralClass:
3449   case ObjCEncodeExprClass:
3450   case ObjCBoolLiteralExprClass:
3451   case ObjCAvailabilityCheckExprClass:
3452   case CXXUuidofExprClass:
3453   case OpaqueValueExprClass:
3454   case SourceLocExprClass:
3455   case ConceptSpecializationExprClass:
3456   case RequiresExprClass:
3457   case SYCLUniqueStableNameExprClass:
3458     // These never have a side-effect.
3459     return false;
3460 
3461   case ConstantExprClass:
3462     // FIXME: Move this into the "return false;" block above.
3463     return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3464         Ctx, IncludePossibleEffects);
3465 
3466   case CallExprClass:
3467   case CXXOperatorCallExprClass:
3468   case CXXMemberCallExprClass:
3469   case CUDAKernelCallExprClass:
3470   case UserDefinedLiteralClass: {
3471     // We don't know a call definitely has side effects, except for calls
3472     // to pure/const functions that definitely don't.
3473     // If the call itself is considered side-effect free, check the operands.
3474     const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3475     bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3476     if (IsPure || !IncludePossibleEffects)
3477       break;
3478     return true;
3479   }
3480 
3481   case BlockExprClass:
3482   case CXXBindTemporaryExprClass:
3483     if (!IncludePossibleEffects)
3484       break;
3485     return true;
3486 
3487   case MSPropertyRefExprClass:
3488   case MSPropertySubscriptExprClass:
3489   case CompoundAssignOperatorClass:
3490   case VAArgExprClass:
3491   case AtomicExprClass:
3492   case CXXThrowExprClass:
3493   case CXXNewExprClass:
3494   case CXXDeleteExprClass:
3495   case CoawaitExprClass:
3496   case DependentCoawaitExprClass:
3497   case CoyieldExprClass:
3498     // These always have a side-effect.
3499     return true;
3500 
3501   case StmtExprClass: {
3502     // StmtExprs have a side-effect if any substatement does.
3503     SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3504     Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3505     return Finder.hasSideEffects();
3506   }
3507 
3508   case ExprWithCleanupsClass:
3509     if (IncludePossibleEffects)
3510       if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3511         return true;
3512     break;
3513 
3514   case ParenExprClass:
3515   case ArraySubscriptExprClass:
3516   case MatrixSubscriptExprClass:
3517   case OMPArraySectionExprClass:
3518   case OMPArrayShapingExprClass:
3519   case OMPIteratorExprClass:
3520   case MemberExprClass:
3521   case ConditionalOperatorClass:
3522   case BinaryConditionalOperatorClass:
3523   case CompoundLiteralExprClass:
3524   case ExtVectorElementExprClass:
3525   case DesignatedInitExprClass:
3526   case DesignatedInitUpdateExprClass:
3527   case ArrayInitLoopExprClass:
3528   case ParenListExprClass:
3529   case CXXPseudoDestructorExprClass:
3530   case CXXRewrittenBinaryOperatorClass:
3531   case CXXStdInitializerListExprClass:
3532   case SubstNonTypeTemplateParmExprClass:
3533   case MaterializeTemporaryExprClass:
3534   case ShuffleVectorExprClass:
3535   case ConvertVectorExprClass:
3536   case AsTypeExprClass:
3537     // These have a side-effect if any subexpression does.
3538     break;
3539 
3540   case UnaryOperatorClass:
3541     if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3542       return true;
3543     break;
3544 
3545   case BinaryOperatorClass:
3546     if (cast<BinaryOperator>(this)->isAssignmentOp())
3547       return true;
3548     break;
3549 
3550   case InitListExprClass:
3551     // FIXME: The children for an InitListExpr doesn't include the array filler.
3552     if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3553       if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3554         return true;
3555     break;
3556 
3557   case GenericSelectionExprClass:
3558     return cast<GenericSelectionExpr>(this)->getResultExpr()->
3559         HasSideEffects(Ctx, IncludePossibleEffects);
3560 
3561   case ChooseExprClass:
3562     return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3563         Ctx, IncludePossibleEffects);
3564 
3565   case CXXDefaultArgExprClass:
3566     return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3567         Ctx, IncludePossibleEffects);
3568 
3569   case CXXDefaultInitExprClass: {
3570     const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3571     if (const Expr *E = FD->getInClassInitializer())
3572       return E->HasSideEffects(Ctx, IncludePossibleEffects);
3573     // If we've not yet parsed the initializer, assume it has side-effects.
3574     return true;
3575   }
3576 
3577   case CXXDynamicCastExprClass: {
3578     // A dynamic_cast expression has side-effects if it can throw.
3579     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3580     if (DCE->getTypeAsWritten()->isReferenceType() &&
3581         DCE->getCastKind() == CK_Dynamic)
3582       return true;
3583     }
3584     LLVM_FALLTHROUGH;
3585   case ImplicitCastExprClass:
3586   case CStyleCastExprClass:
3587   case CXXStaticCastExprClass:
3588   case CXXReinterpretCastExprClass:
3589   case CXXConstCastExprClass:
3590   case CXXAddrspaceCastExprClass:
3591   case CXXFunctionalCastExprClass:
3592   case BuiltinBitCastExprClass: {
3593     // While volatile reads are side-effecting in both C and C++, we treat them
3594     // as having possible (not definite) side-effects. This allows idiomatic
3595     // code to behave without warning, such as sizeof(*v) for a volatile-
3596     // qualified pointer.
3597     if (!IncludePossibleEffects)
3598       break;
3599 
3600     const CastExpr *CE = cast<CastExpr>(this);
3601     if (CE->getCastKind() == CK_LValueToRValue &&
3602         CE->getSubExpr()->getType().isVolatileQualified())
3603       return true;
3604     break;
3605   }
3606 
3607   case CXXTypeidExprClass:
3608     // typeid might throw if its subexpression is potentially-evaluated, so has
3609     // side-effects in that case whether or not its subexpression does.
3610     return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3611 
3612   case CXXConstructExprClass:
3613   case CXXTemporaryObjectExprClass: {
3614     const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3615     if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3616       return true;
3617     // A trivial constructor does not add any side-effects of its own. Just look
3618     // at its arguments.
3619     break;
3620   }
3621 
3622   case CXXInheritedCtorInitExprClass: {
3623     const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3624     if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3625       return true;
3626     break;
3627   }
3628 
3629   case LambdaExprClass: {
3630     const LambdaExpr *LE = cast<LambdaExpr>(this);
3631     for (Expr *E : LE->capture_inits())
3632       if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3633         return true;
3634     return false;
3635   }
3636 
3637   case PseudoObjectExprClass: {
3638     // Only look for side-effects in the semantic form, and look past
3639     // OpaqueValueExpr bindings in that form.
3640     const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3641     for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3642                                                     E = PO->semantics_end();
3643          I != E; ++I) {
3644       const Expr *Subexpr = *I;
3645       if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3646         Subexpr = OVE->getSourceExpr();
3647       if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3648         return true;
3649     }
3650     return false;
3651   }
3652 
3653   case ObjCBoxedExprClass:
3654   case ObjCArrayLiteralClass:
3655   case ObjCDictionaryLiteralClass:
3656   case ObjCSelectorExprClass:
3657   case ObjCProtocolExprClass:
3658   case ObjCIsaExprClass:
3659   case ObjCIndirectCopyRestoreExprClass:
3660   case ObjCSubscriptRefExprClass:
3661   case ObjCBridgedCastExprClass:
3662   case ObjCMessageExprClass:
3663   case ObjCPropertyRefExprClass:
3664   // FIXME: Classify these cases better.
3665     if (IncludePossibleEffects)
3666       return true;
3667     break;
3668   }
3669 
3670   // Recurse to children.
3671   for (const Stmt *SubStmt : children())
3672     if (SubStmt &&
3673         cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3674       return true;
3675 
3676   return false;
3677 }
3678 
3679 FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const {
3680   if (auto Call = dyn_cast<CallExpr>(this))
3681     return Call->getFPFeaturesInEffect(LO);
3682   if (auto UO = dyn_cast<UnaryOperator>(this))
3683     return UO->getFPFeaturesInEffect(LO);
3684   if (auto BO = dyn_cast<BinaryOperator>(this))
3685     return BO->getFPFeaturesInEffect(LO);
3686   if (auto Cast = dyn_cast<CastExpr>(this))
3687     return Cast->getFPFeaturesInEffect(LO);
3688   return FPOptions::defaultWithoutTrailingStorage(LO);
3689 }
3690 
3691 namespace {
3692   /// Look for a call to a non-trivial function within an expression.
3693   class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3694   {
3695     typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3696 
3697     bool NonTrivial;
3698 
3699   public:
3700     explicit NonTrivialCallFinder(const ASTContext &Context)
3701       : Inherited(Context), NonTrivial(false) { }
3702 
3703     bool hasNonTrivialCall() const { return NonTrivial; }
3704 
3705     void VisitCallExpr(const CallExpr *E) {
3706       if (const CXXMethodDecl *Method
3707           = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3708         if (Method->isTrivial()) {
3709           // Recurse to children of the call.
3710           Inherited::VisitStmt(E);
3711           return;
3712         }
3713       }
3714 
3715       NonTrivial = true;
3716     }
3717 
3718     void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3719       if (E->getConstructor()->isTrivial()) {
3720         // Recurse to children of the call.
3721         Inherited::VisitStmt(E);
3722         return;
3723       }
3724 
3725       NonTrivial = true;
3726     }
3727 
3728     void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3729       if (E->getTemporary()->getDestructor()->isTrivial()) {
3730         Inherited::VisitStmt(E);
3731         return;
3732       }
3733 
3734       NonTrivial = true;
3735     }
3736   };
3737 }
3738 
3739 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3740   NonTrivialCallFinder Finder(Ctx);
3741   Finder.Visit(this);
3742   return Finder.hasNonTrivialCall();
3743 }
3744 
3745 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3746 /// pointer constant or not, as well as the specific kind of constant detected.
3747 /// Null pointer constants can be integer constant expressions with the
3748 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3749 /// (a GNU extension).
3750 Expr::NullPointerConstantKind
3751 Expr::isNullPointerConstant(ASTContext &Ctx,
3752                             NullPointerConstantValueDependence NPC) const {
3753   if (isValueDependent() &&
3754       (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3755     // Error-dependent expr should never be a null pointer.
3756     if (containsErrors())
3757       return NPCK_NotNull;
3758     switch (NPC) {
3759     case NPC_NeverValueDependent:
3760       llvm_unreachable("Unexpected value dependent expression!");
3761     case NPC_ValueDependentIsNull:
3762       if (isTypeDependent() || getType()->isIntegralType(Ctx))
3763         return NPCK_ZeroExpression;
3764       else
3765         return NPCK_NotNull;
3766 
3767     case NPC_ValueDependentIsNotNull:
3768       return NPCK_NotNull;
3769     }
3770   }
3771 
3772   // Strip off a cast to void*, if it exists. Except in C++.
3773   if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3774     if (!Ctx.getLangOpts().CPlusPlus) {
3775       // Check that it is a cast to void*.
3776       if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3777         QualType Pointee = PT->getPointeeType();
3778         Qualifiers Qs = Pointee.getQualifiers();
3779         // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3780         // has non-default address space it is not treated as nullptr.
3781         // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3782         // since it cannot be assigned to a pointer to constant address space.
3783         if (Ctx.getLangOpts().OpenCL &&
3784             Pointee.getAddressSpace() == Ctx.getDefaultOpenCLPointeeAddrSpace())
3785           Qs.removeAddressSpace();
3786 
3787         if (Pointee->isVoidType() && Qs.empty() && // to void*
3788             CE->getSubExpr()->getType()->isIntegerType()) // from int
3789           return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3790       }
3791     }
3792   } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3793     // Ignore the ImplicitCastExpr type entirely.
3794     return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3795   } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3796     // Accept ((void*)0) as a null pointer constant, as many other
3797     // implementations do.
3798     return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3799   } else if (const GenericSelectionExpr *GE =
3800                dyn_cast<GenericSelectionExpr>(this)) {
3801     if (GE->isResultDependent())
3802       return NPCK_NotNull;
3803     return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3804   } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3805     if (CE->isConditionDependent())
3806       return NPCK_NotNull;
3807     return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3808   } else if (const CXXDefaultArgExpr *DefaultArg
3809                = dyn_cast<CXXDefaultArgExpr>(this)) {
3810     // See through default argument expressions.
3811     return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3812   } else if (const CXXDefaultInitExpr *DefaultInit
3813                = dyn_cast<CXXDefaultInitExpr>(this)) {
3814     // See through default initializer expressions.
3815     return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3816   } else if (isa<GNUNullExpr>(this)) {
3817     // The GNU __null extension is always a null pointer constant.
3818     return NPCK_GNUNull;
3819   } else if (const MaterializeTemporaryExpr *M
3820                                    = dyn_cast<MaterializeTemporaryExpr>(this)) {
3821     return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3822   } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3823     if (const Expr *Source = OVE->getSourceExpr())
3824       return Source->isNullPointerConstant(Ctx, NPC);
3825   }
3826 
3827   // If the expression has no type information, it cannot be a null pointer
3828   // constant.
3829   if (getType().isNull())
3830     return NPCK_NotNull;
3831 
3832   // C++11 nullptr_t is always a null pointer constant.
3833   if (getType()->isNullPtrType())
3834     return NPCK_CXX11_nullptr;
3835 
3836   if (const RecordType *UT = getType()->getAsUnionType())
3837     if (!Ctx.getLangOpts().CPlusPlus11 &&
3838         UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3839       if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3840         const Expr *InitExpr = CLE->getInitializer();
3841         if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3842           return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3843       }
3844   // This expression must be an integer type.
3845   if (!getType()->isIntegerType() ||
3846       (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3847     return NPCK_NotNull;
3848 
3849   if (Ctx.getLangOpts().CPlusPlus11) {
3850     // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3851     // value zero or a prvalue of type std::nullptr_t.
3852     // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3853     const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3854     if (Lit && !Lit->getValue())
3855       return NPCK_ZeroLiteral;
3856     if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3857       return NPCK_NotNull;
3858   } else {
3859     // If we have an integer constant expression, we need to *evaluate* it and
3860     // test for the value 0.
3861     if (!isIntegerConstantExpr(Ctx))
3862       return NPCK_NotNull;
3863   }
3864 
3865   if (EvaluateKnownConstInt(Ctx) != 0)
3866     return NPCK_NotNull;
3867 
3868   if (isa<IntegerLiteral>(this))
3869     return NPCK_ZeroLiteral;
3870   return NPCK_ZeroExpression;
3871 }
3872 
3873 /// If this expression is an l-value for an Objective C
3874 /// property, find the underlying property reference expression.
3875 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3876   const Expr *E = this;
3877   while (true) {
3878     assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&
3879            "expression is not a property reference");
3880     E = E->IgnoreParenCasts();
3881     if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3882       if (BO->getOpcode() == BO_Comma) {
3883         E = BO->getRHS();
3884         continue;
3885       }
3886     }
3887 
3888     break;
3889   }
3890 
3891   return cast<ObjCPropertyRefExpr>(E);
3892 }
3893 
3894 bool Expr::isObjCSelfExpr() const {
3895   const Expr *E = IgnoreParenImpCasts();
3896 
3897   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3898   if (!DRE)
3899     return false;
3900 
3901   const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3902   if (!Param)
3903     return false;
3904 
3905   const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3906   if (!M)
3907     return false;
3908 
3909   return M->getSelfDecl() == Param;
3910 }
3911 
3912 FieldDecl *Expr::getSourceBitField() {
3913   Expr *E = this->IgnoreParens();
3914 
3915   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3916     if (ICE->getCastKind() == CK_LValueToRValue ||
3917         (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
3918       E = ICE->getSubExpr()->IgnoreParens();
3919     else
3920       break;
3921   }
3922 
3923   if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3924     if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3925       if (Field->isBitField())
3926         return Field;
3927 
3928   if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3929     FieldDecl *Ivar = IvarRef->getDecl();
3930     if (Ivar->isBitField())
3931       return Ivar;
3932   }
3933 
3934   if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3935     if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3936       if (Field->isBitField())
3937         return Field;
3938 
3939     if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3940       if (Expr *E = BD->getBinding())
3941         return E->getSourceBitField();
3942   }
3943 
3944   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3945     if (BinOp->isAssignmentOp() && BinOp->getLHS())
3946       return BinOp->getLHS()->getSourceBitField();
3947 
3948     if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3949       return BinOp->getRHS()->getSourceBitField();
3950   }
3951 
3952   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3953     if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3954       return UnOp->getSubExpr()->getSourceBitField();
3955 
3956   return nullptr;
3957 }
3958 
3959 bool Expr::refersToVectorElement() const {
3960   // FIXME: Why do we not just look at the ObjectKind here?
3961   const Expr *E = this->IgnoreParens();
3962 
3963   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3964     if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
3965       E = ICE->getSubExpr()->IgnoreParens();
3966     else
3967       break;
3968   }
3969 
3970   if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3971     return ASE->getBase()->getType()->isVectorType();
3972 
3973   if (isa<ExtVectorElementExpr>(E))
3974     return true;
3975 
3976   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3977     if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3978       if (auto *E = BD->getBinding())
3979         return E->refersToVectorElement();
3980 
3981   return false;
3982 }
3983 
3984 bool Expr::refersToGlobalRegisterVar() const {
3985   const Expr *E = this->IgnoreParenImpCasts();
3986 
3987   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3988     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3989       if (VD->getStorageClass() == SC_Register &&
3990           VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3991         return true;
3992 
3993   return false;
3994 }
3995 
3996 bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
3997   E1 = E1->IgnoreParens();
3998   E2 = E2->IgnoreParens();
3999 
4000   if (E1->getStmtClass() != E2->getStmtClass())
4001     return false;
4002 
4003   switch (E1->getStmtClass()) {
4004     default:
4005       return false;
4006     case CXXThisExprClass:
4007       return true;
4008     case DeclRefExprClass: {
4009       // DeclRefExpr without an ImplicitCastExpr can happen for integral
4010       // template parameters.
4011       const auto *DRE1 = cast<DeclRefExpr>(E1);
4012       const auto *DRE2 = cast<DeclRefExpr>(E2);
4013       return DRE1->isPRValue() && DRE2->isPRValue() &&
4014              DRE1->getDecl() == DRE2->getDecl();
4015     }
4016     case ImplicitCastExprClass: {
4017       // Peel off implicit casts.
4018       while (true) {
4019         const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4020         const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4021         if (!ICE1 || !ICE2)
4022           return false;
4023         if (ICE1->getCastKind() != ICE2->getCastKind())
4024           return false;
4025         E1 = ICE1->getSubExpr()->IgnoreParens();
4026         E2 = ICE2->getSubExpr()->IgnoreParens();
4027         // The final cast must be one of these types.
4028         if (ICE1->getCastKind() == CK_LValueToRValue ||
4029             ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4030             ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4031           break;
4032         }
4033       }
4034 
4035       const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4036       const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4037       if (DRE1 && DRE2)
4038         return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4039 
4040       const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4041       const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4042       if (Ivar1 && Ivar2) {
4043         return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4044                declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4045       }
4046 
4047       const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4048       const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4049       if (Array1 && Array2) {
4050         if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4051           return false;
4052 
4053         auto Idx1 = Array1->getIdx();
4054         auto Idx2 = Array2->getIdx();
4055         const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4056         const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4057         if (Integer1 && Integer2) {
4058           if (!llvm::APInt::isSameValue(Integer1->getValue(),
4059                                         Integer2->getValue()))
4060             return false;
4061         } else {
4062           if (!isSameComparisonOperand(Idx1, Idx2))
4063             return false;
4064         }
4065 
4066         return true;
4067       }
4068 
4069       // Walk the MemberExpr chain.
4070       while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4071         const auto *ME1 = cast<MemberExpr>(E1);
4072         const auto *ME2 = cast<MemberExpr>(E2);
4073         if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4074           return false;
4075         if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4076           if (D->isStaticDataMember())
4077             return true;
4078         E1 = ME1->getBase()->IgnoreParenImpCasts();
4079         E2 = ME2->getBase()->IgnoreParenImpCasts();
4080       }
4081 
4082       if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4083         return true;
4084 
4085       // A static member variable can end the MemberExpr chain with either
4086       // a MemberExpr or a DeclRefExpr.
4087       auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4088         if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4089           return DRE->getDecl();
4090         if (const auto *ME = dyn_cast<MemberExpr>(E))
4091           return ME->getMemberDecl();
4092         return nullptr;
4093       };
4094 
4095       const ValueDecl *VD1 = getAnyDecl(E1);
4096       const ValueDecl *VD2 = getAnyDecl(E2);
4097       return declaresSameEntity(VD1, VD2);
4098     }
4099   }
4100 }
4101 
4102 /// isArrow - Return true if the base expression is a pointer to vector,
4103 /// return false if the base expression is a vector.
4104 bool ExtVectorElementExpr::isArrow() const {
4105   return getBase()->getType()->isPointerType();
4106 }
4107 
4108 unsigned ExtVectorElementExpr::getNumElements() const {
4109   if (const VectorType *VT = getType()->getAs<VectorType>())
4110     return VT->getNumElements();
4111   return 1;
4112 }
4113 
4114 /// containsDuplicateElements - Return true if any element access is repeated.
4115 bool ExtVectorElementExpr::containsDuplicateElements() const {
4116   // FIXME: Refactor this code to an accessor on the AST node which returns the
4117   // "type" of component access, and share with code below and in Sema.
4118   StringRef Comp = Accessor->getName();
4119 
4120   // Halving swizzles do not contain duplicate elements.
4121   if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4122     return false;
4123 
4124   // Advance past s-char prefix on hex swizzles.
4125   if (Comp[0] == 's' || Comp[0] == 'S')
4126     Comp = Comp.substr(1);
4127 
4128   for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4129     if (Comp.substr(i + 1).contains(Comp[i]))
4130         return true;
4131 
4132   return false;
4133 }
4134 
4135 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4136 void ExtVectorElementExpr::getEncodedElementAccess(
4137     SmallVectorImpl<uint32_t> &Elts) const {
4138   StringRef Comp = Accessor->getName();
4139   bool isNumericAccessor = false;
4140   if (Comp[0] == 's' || Comp[0] == 'S') {
4141     Comp = Comp.substr(1);
4142     isNumericAccessor = true;
4143   }
4144 
4145   bool isHi =   Comp == "hi";
4146   bool isLo =   Comp == "lo";
4147   bool isEven = Comp == "even";
4148   bool isOdd  = Comp == "odd";
4149 
4150   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4151     uint64_t Index;
4152 
4153     if (isHi)
4154       Index = e + i;
4155     else if (isLo)
4156       Index = i;
4157     else if (isEven)
4158       Index = 2 * i;
4159     else if (isOdd)
4160       Index = 2 * i + 1;
4161     else
4162       Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4163 
4164     Elts.push_back(Index);
4165   }
4166 }
4167 
4168 ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,
4169                                      QualType Type, SourceLocation BLoc,
4170                                      SourceLocation RP)
4171     : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
4172       BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {
4173   SubExprs = new (C) Stmt*[args.size()];
4174   for (unsigned i = 0; i != args.size(); i++)
4175     SubExprs[i] = args[i];
4176 
4177   setDependence(computeDependence(this));
4178 }
4179 
4180 void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
4181   if (SubExprs) C.Deallocate(SubExprs);
4182 
4183   this->NumExprs = Exprs.size();
4184   SubExprs = new (C) Stmt*[NumExprs];
4185   memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
4186 }
4187 
4188 GenericSelectionExpr::GenericSelectionExpr(
4189     const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4190     ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4191     SourceLocation DefaultLoc, SourceLocation RParenLoc,
4192     bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4193     : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4194            AssocExprs[ResultIndex]->getValueKind(),
4195            AssocExprs[ResultIndex]->getObjectKind()),
4196       NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4197       DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4198   assert(AssocTypes.size() == AssocExprs.size() &&
4199          "Must have the same number of association expressions"
4200          " and TypeSourceInfo!");
4201   assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4202 
4203   GenericSelectionExprBits.GenericLoc = GenericLoc;
4204   getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4205   std::copy(AssocExprs.begin(), AssocExprs.end(),
4206             getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4207   std::copy(AssocTypes.begin(), AssocTypes.end(),
4208             getTrailingObjects<TypeSourceInfo *>());
4209 
4210   setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4211 }
4212 
4213 GenericSelectionExpr::GenericSelectionExpr(
4214     const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4215     ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4216     SourceLocation DefaultLoc, SourceLocation RParenLoc,
4217     bool ContainsUnexpandedParameterPack)
4218     : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4219            OK_Ordinary),
4220       NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4221       DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4222   assert(AssocTypes.size() == AssocExprs.size() &&
4223          "Must have the same number of association expressions"
4224          " and TypeSourceInfo!");
4225 
4226   GenericSelectionExprBits.GenericLoc = GenericLoc;
4227   getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4228   std::copy(AssocExprs.begin(), AssocExprs.end(),
4229             getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4230   std::copy(AssocTypes.begin(), AssocTypes.end(),
4231             getTrailingObjects<TypeSourceInfo *>());
4232 
4233   setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4234 }
4235 
4236 GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4237     : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4238 
4239 GenericSelectionExpr *GenericSelectionExpr::Create(
4240     const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4241     ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4242     SourceLocation DefaultLoc, SourceLocation RParenLoc,
4243     bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4244   unsigned NumAssocs = AssocExprs.size();
4245   void *Mem = Context.Allocate(
4246       totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4247       alignof(GenericSelectionExpr));
4248   return new (Mem) GenericSelectionExpr(
4249       Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4250       RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4251 }
4252 
4253 GenericSelectionExpr *GenericSelectionExpr::Create(
4254     const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4255     ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4256     SourceLocation DefaultLoc, SourceLocation RParenLoc,
4257     bool ContainsUnexpandedParameterPack) {
4258   unsigned NumAssocs = AssocExprs.size();
4259   void *Mem = Context.Allocate(
4260       totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4261       alignof(GenericSelectionExpr));
4262   return new (Mem) GenericSelectionExpr(
4263       Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4264       RParenLoc, ContainsUnexpandedParameterPack);
4265 }
4266 
4267 GenericSelectionExpr *
4268 GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4269                                   unsigned NumAssocs) {
4270   void *Mem = Context.Allocate(
4271       totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4272       alignof(GenericSelectionExpr));
4273   return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4274 }
4275 
4276 //===----------------------------------------------------------------------===//
4277 //  DesignatedInitExpr
4278 //===----------------------------------------------------------------------===//
4279 
4280 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
4281   assert(Kind == FieldDesignator && "Only valid on a field designator");
4282   if (Field.NameOrField & 0x01)
4283     return reinterpret_cast<IdentifierInfo *>(Field.NameOrField & ~0x01);
4284   return getField()->getIdentifier();
4285 }
4286 
4287 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4288                                        llvm::ArrayRef<Designator> Designators,
4289                                        SourceLocation EqualOrColonLoc,
4290                                        bool GNUSyntax,
4291                                        ArrayRef<Expr *> IndexExprs, Expr *Init)
4292     : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4293            Init->getObjectKind()),
4294       EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4295       NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4296   this->Designators = new (C) Designator[NumDesignators];
4297 
4298   // Record the initializer itself.
4299   child_iterator Child = child_begin();
4300   *Child++ = Init;
4301 
4302   // Copy the designators and their subexpressions, computing
4303   // value-dependence along the way.
4304   unsigned IndexIdx = 0;
4305   for (unsigned I = 0; I != NumDesignators; ++I) {
4306     this->Designators[I] = Designators[I];
4307     if (this->Designators[I].isArrayDesignator()) {
4308       // Copy the index expressions into permanent storage.
4309       *Child++ = IndexExprs[IndexIdx++];
4310     } else if (this->Designators[I].isArrayRangeDesignator()) {
4311       // Copy the start/end expressions into permanent storage.
4312       *Child++ = IndexExprs[IndexIdx++];
4313       *Child++ = IndexExprs[IndexIdx++];
4314     }
4315   }
4316 
4317   assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4318   setDependence(computeDependence(this));
4319 }
4320 
4321 DesignatedInitExpr *
4322 DesignatedInitExpr::Create(const ASTContext &C,
4323                            llvm::ArrayRef<Designator> Designators,
4324                            ArrayRef<Expr*> IndexExprs,
4325                            SourceLocation ColonOrEqualLoc,
4326                            bool UsesColonSyntax, Expr *Init) {
4327   void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4328                          alignof(DesignatedInitExpr));
4329   return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4330                                       ColonOrEqualLoc, UsesColonSyntax,
4331                                       IndexExprs, Init);
4332 }
4333 
4334 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
4335                                                     unsigned NumIndexExprs) {
4336   void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4337                          alignof(DesignatedInitExpr));
4338   return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4339 }
4340 
4341 void DesignatedInitExpr::setDesignators(const ASTContext &C,
4342                                         const Designator *Desigs,
4343                                         unsigned NumDesigs) {
4344   Designators = new (C) Designator[NumDesigs];
4345   NumDesignators = NumDesigs;
4346   for (unsigned I = 0; I != NumDesigs; ++I)
4347     Designators[I] = Desigs[I];
4348 }
4349 
4350 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4351   DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4352   if (size() == 1)
4353     return DIE->getDesignator(0)->getSourceRange();
4354   return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4355                      DIE->getDesignator(size() - 1)->getEndLoc());
4356 }
4357 
4358 SourceLocation DesignatedInitExpr::getBeginLoc() const {
4359   SourceLocation StartLoc;
4360   auto *DIE = const_cast<DesignatedInitExpr *>(this);
4361   Designator &First = *DIE->getDesignator(0);
4362   if (First.isFieldDesignator())
4363     StartLoc = GNUSyntax ? First.Field.FieldLoc : First.Field.DotLoc;
4364   else
4365     StartLoc = First.ArrayOrRange.LBracketLoc;
4366   return StartLoc;
4367 }
4368 
4369 SourceLocation DesignatedInitExpr::getEndLoc() const {
4370   return getInit()->getEndLoc();
4371 }
4372 
4373 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
4374   assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
4375   return getSubExpr(D.ArrayOrRange.Index + 1);
4376 }
4377 
4378 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
4379   assert(D.Kind == Designator::ArrayRangeDesignator &&
4380          "Requires array range designator");
4381   return getSubExpr(D.ArrayOrRange.Index + 1);
4382 }
4383 
4384 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
4385   assert(D.Kind == Designator::ArrayRangeDesignator &&
4386          "Requires array range designator");
4387   return getSubExpr(D.ArrayOrRange.Index + 2);
4388 }
4389 
4390 /// Replaces the designator at index @p Idx with the series
4391 /// of designators in [First, Last).
4392 void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
4393                                           const Designator *First,
4394                                           const Designator *Last) {
4395   unsigned NumNewDesignators = Last - First;
4396   if (NumNewDesignators == 0) {
4397     std::copy_backward(Designators + Idx + 1,
4398                        Designators + NumDesignators,
4399                        Designators + Idx);
4400     --NumNewDesignators;
4401     return;
4402   }
4403   if (NumNewDesignators == 1) {
4404     Designators[Idx] = *First;
4405     return;
4406   }
4407 
4408   Designator *NewDesignators
4409     = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4410   std::copy(Designators, Designators + Idx, NewDesignators);
4411   std::copy(First, Last, NewDesignators + Idx);
4412   std::copy(Designators + Idx + 1, Designators + NumDesignators,
4413             NewDesignators + Idx + NumNewDesignators);
4414   Designators = NewDesignators;
4415   NumDesignators = NumDesignators - 1 + NumNewDesignators;
4416 }
4417 
4418 DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4419                                                    SourceLocation lBraceLoc,
4420                                                    Expr *baseExpr,
4421                                                    SourceLocation rBraceLoc)
4422     : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
4423            OK_Ordinary) {
4424   BaseAndUpdaterExprs[0] = baseExpr;
4425 
4426   InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4427   ILE->setType(baseExpr->getType());
4428   BaseAndUpdaterExprs[1] = ILE;
4429 
4430   // FIXME: this is wrong, set it correctly.
4431   setDependence(ExprDependence::None);
4432 }
4433 
4434 SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
4435   return getBase()->getBeginLoc();
4436 }
4437 
4438 SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
4439   return getBase()->getEndLoc();
4440 }
4441 
4442 ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4443                              SourceLocation RParenLoc)
4444     : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
4445       LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4446   ParenListExprBits.NumExprs = Exprs.size();
4447 
4448   for (unsigned I = 0, N = Exprs.size(); I != N; ++I)
4449     getTrailingObjects<Stmt *>()[I] = Exprs[I];
4450   setDependence(computeDependence(this));
4451 }
4452 
4453 ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4454     : Expr(ParenListExprClass, Empty) {
4455   ParenListExprBits.NumExprs = NumExprs;
4456 }
4457 
4458 ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4459                                      SourceLocation LParenLoc,
4460                                      ArrayRef<Expr *> Exprs,
4461                                      SourceLocation RParenLoc) {
4462   void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4463                            alignof(ParenListExpr));
4464   return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4465 }
4466 
4467 ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4468                                           unsigned NumExprs) {
4469   void *Mem =
4470       Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4471   return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4472 }
4473 
4474 BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4475                                Opcode opc, QualType ResTy, ExprValueKind VK,
4476                                ExprObjectKind OK, SourceLocation opLoc,
4477                                FPOptionsOverride FPFeatures)
4478     : Expr(BinaryOperatorClass, ResTy, VK, OK) {
4479   BinaryOperatorBits.Opc = opc;
4480   assert(!isCompoundAssignmentOp() &&
4481          "Use CompoundAssignOperator for compound assignments");
4482   BinaryOperatorBits.OpLoc = opLoc;
4483   SubExprs[LHS] = lhs;
4484   SubExprs[RHS] = rhs;
4485   BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4486   if (hasStoredFPFeatures())
4487     setStoredFPFeatures(FPFeatures);
4488   setDependence(computeDependence(this));
4489 }
4490 
4491 BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4492                                Opcode opc, QualType ResTy, ExprValueKind VK,
4493                                ExprObjectKind OK, SourceLocation opLoc,
4494                                FPOptionsOverride FPFeatures, bool dead2)
4495     : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
4496   BinaryOperatorBits.Opc = opc;
4497   assert(isCompoundAssignmentOp() &&
4498          "Use CompoundAssignOperator for compound assignments");
4499   BinaryOperatorBits.OpLoc = opLoc;
4500   SubExprs[LHS] = lhs;
4501   SubExprs[RHS] = rhs;
4502   BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4503   if (hasStoredFPFeatures())
4504     setStoredFPFeatures(FPFeatures);
4505   setDependence(computeDependence(this));
4506 }
4507 
4508 BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,
4509                                             bool HasFPFeatures) {
4510   unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4511   void *Mem =
4512       C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4513   return new (Mem) BinaryOperator(EmptyShell());
4514 }
4515 
4516 BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs,
4517                                        Expr *rhs, Opcode opc, QualType ResTy,
4518                                        ExprValueKind VK, ExprObjectKind OK,
4519                                        SourceLocation opLoc,
4520                                        FPOptionsOverride FPFeatures) {
4521   bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4522   unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4523   void *Mem =
4524       C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4525   return new (Mem)
4526       BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
4527 }
4528 
4529 CompoundAssignOperator *
4530 CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {
4531   unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4532   void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4533                          alignof(CompoundAssignOperator));
4534   return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
4535 }
4536 
4537 CompoundAssignOperator *
4538 CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs,
4539                                Opcode opc, QualType ResTy, ExprValueKind VK,
4540                                ExprObjectKind OK, SourceLocation opLoc,
4541                                FPOptionsOverride FPFeatures,
4542                                QualType CompLHSType, QualType CompResultType) {
4543   bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4544   unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4545   void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4546                          alignof(CompoundAssignOperator));
4547   return new (Mem)
4548       CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
4549                              CompLHSType, CompResultType);
4550 }
4551 
4552 UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C,
4553                                           bool hasFPFeatures) {
4554   void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
4555                          alignof(UnaryOperator));
4556   return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
4557 }
4558 
4559 UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc,
4560                              QualType type, ExprValueKind VK, ExprObjectKind OK,
4561                              SourceLocation l, bool CanOverflow,
4562                              FPOptionsOverride FPFeatures)
4563     : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
4564   UnaryOperatorBits.Opc = opc;
4565   UnaryOperatorBits.CanOverflow = CanOverflow;
4566   UnaryOperatorBits.Loc = l;
4567   UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4568   if (hasStoredFPFeatures())
4569     setStoredFPFeatures(FPFeatures);
4570   setDependence(computeDependence(this, Ctx));
4571 }
4572 
4573 UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input,
4574                                      Opcode opc, QualType type,
4575                                      ExprValueKind VK, ExprObjectKind OK,
4576                                      SourceLocation l, bool CanOverflow,
4577                                      FPOptionsOverride FPFeatures) {
4578   bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4579   unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
4580   void *Mem = C.Allocate(Size, alignof(UnaryOperator));
4581   return new (Mem)
4582       UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
4583 }
4584 
4585 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4586   if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4587     e = ewc->getSubExpr();
4588   if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4589     e = m->getSubExpr();
4590   e = cast<CXXConstructExpr>(e)->getArg(0);
4591   while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4592     e = ice->getSubExpr();
4593   return cast<OpaqueValueExpr>(e);
4594 }
4595 
4596 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4597                                            EmptyShell sh,
4598                                            unsigned numSemanticExprs) {
4599   void *buffer =
4600       Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4601                        alignof(PseudoObjectExpr));
4602   return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4603 }
4604 
4605 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4606   : Expr(PseudoObjectExprClass, shell) {
4607   PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4608 }
4609 
4610 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
4611                                            ArrayRef<Expr*> semantics,
4612                                            unsigned resultIndex) {
4613   assert(syntax && "no syntactic expression!");
4614   assert(semantics.size() && "no semantic expressions!");
4615 
4616   QualType type;
4617   ExprValueKind VK;
4618   if (resultIndex == NoResult) {
4619     type = C.VoidTy;
4620     VK = VK_PRValue;
4621   } else {
4622     assert(resultIndex < semantics.size());
4623     type = semantics[resultIndex]->getType();
4624     VK = semantics[resultIndex]->getValueKind();
4625     assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4626   }
4627 
4628   void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4629                             alignof(PseudoObjectExpr));
4630   return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4631                                       resultIndex);
4632 }
4633 
4634 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4635                                    Expr *syntax, ArrayRef<Expr *> semantics,
4636                                    unsigned resultIndex)
4637     : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
4638   PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4639   PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4640 
4641   for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4642     Expr *E = (i == 0 ? syntax : semantics[i-1]);
4643     getSubExprsBuffer()[i] = E;
4644 
4645     if (isa<OpaqueValueExpr>(E))
4646       assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
4647              "opaque-value semantic expressions for pseudo-object "
4648              "operations must have sources");
4649   }
4650 
4651   setDependence(computeDependence(this));
4652 }
4653 
4654 //===----------------------------------------------------------------------===//
4655 //  Child Iterators for iterating over subexpressions/substatements
4656 //===----------------------------------------------------------------------===//
4657 
4658 // UnaryExprOrTypeTraitExpr
4659 Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
4660   const_child_range CCR =
4661       const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4662   return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4663 }
4664 
4665 Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
4666   // If this is of a type and the type is a VLA type (and not a typedef), the
4667   // size expression of the VLA needs to be treated as an executable expression.
4668   // Why isn't this weirdness documented better in StmtIterator?
4669   if (isArgumentType()) {
4670     if (const VariableArrayType *T =
4671             dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4672       return const_child_range(const_child_iterator(T), const_child_iterator());
4673     return const_child_range(const_child_iterator(), const_child_iterator());
4674   }
4675   return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4676 }
4677 
4678 AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,
4679                        AtomicOp op, SourceLocation RP)
4680     : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
4681       NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
4682   assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4683   for (unsigned i = 0; i != args.size(); i++)
4684     SubExprs[i] = args[i];
4685   setDependence(computeDependence(this));
4686 }
4687 
4688 unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4689   switch (Op) {
4690   case AO__c11_atomic_init:
4691   case AO__opencl_atomic_init:
4692   case AO__c11_atomic_load:
4693   case AO__atomic_load_n:
4694     return 2;
4695 
4696   case AO__opencl_atomic_load:
4697   case AO__hip_atomic_load:
4698   case AO__c11_atomic_store:
4699   case AO__c11_atomic_exchange:
4700   case AO__atomic_load:
4701   case AO__atomic_store:
4702   case AO__atomic_store_n:
4703   case AO__atomic_exchange_n:
4704   case AO__c11_atomic_fetch_add:
4705   case AO__c11_atomic_fetch_sub:
4706   case AO__c11_atomic_fetch_and:
4707   case AO__c11_atomic_fetch_or:
4708   case AO__c11_atomic_fetch_xor:
4709   case AO__c11_atomic_fetch_nand:
4710   case AO__c11_atomic_fetch_max:
4711   case AO__c11_atomic_fetch_min:
4712   case AO__atomic_fetch_add:
4713   case AO__atomic_fetch_sub:
4714   case AO__atomic_fetch_and:
4715   case AO__atomic_fetch_or:
4716   case AO__atomic_fetch_xor:
4717   case AO__atomic_fetch_nand:
4718   case AO__atomic_add_fetch:
4719   case AO__atomic_sub_fetch:
4720   case AO__atomic_and_fetch:
4721   case AO__atomic_or_fetch:
4722   case AO__atomic_xor_fetch:
4723   case AO__atomic_nand_fetch:
4724   case AO__atomic_min_fetch:
4725   case AO__atomic_max_fetch:
4726   case AO__atomic_fetch_min:
4727   case AO__atomic_fetch_max:
4728     return 3;
4729 
4730   case AO__hip_atomic_exchange:
4731   case AO__hip_atomic_fetch_add:
4732   case AO__hip_atomic_fetch_and:
4733   case AO__hip_atomic_fetch_or:
4734   case AO__hip_atomic_fetch_xor:
4735   case AO__hip_atomic_fetch_min:
4736   case AO__hip_atomic_fetch_max:
4737   case AO__opencl_atomic_store:
4738   case AO__hip_atomic_store:
4739   case AO__opencl_atomic_exchange:
4740   case AO__opencl_atomic_fetch_add:
4741   case AO__opencl_atomic_fetch_sub:
4742   case AO__opencl_atomic_fetch_and:
4743   case AO__opencl_atomic_fetch_or:
4744   case AO__opencl_atomic_fetch_xor:
4745   case AO__opencl_atomic_fetch_min:
4746   case AO__opencl_atomic_fetch_max:
4747   case AO__atomic_exchange:
4748     return 4;
4749 
4750   case AO__c11_atomic_compare_exchange_strong:
4751   case AO__c11_atomic_compare_exchange_weak:
4752     return 5;
4753   case AO__hip_atomic_compare_exchange_strong:
4754   case AO__opencl_atomic_compare_exchange_strong:
4755   case AO__opencl_atomic_compare_exchange_weak:
4756   case AO__hip_atomic_compare_exchange_weak:
4757   case AO__atomic_compare_exchange:
4758   case AO__atomic_compare_exchange_n:
4759     return 6;
4760   }
4761   llvm_unreachable("unknown atomic op");
4762 }
4763 
4764 QualType AtomicExpr::getValueType() const {
4765   auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4766   if (auto AT = T->getAs<AtomicType>())
4767     return AT->getValueType();
4768   return T;
4769 }
4770 
4771 QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
4772   unsigned ArraySectionCount = 0;
4773   while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4774     Base = OASE->getBase();
4775     ++ArraySectionCount;
4776   }
4777   while (auto *ASE =
4778              dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4779     Base = ASE->getBase();
4780     ++ArraySectionCount;
4781   }
4782   Base = Base->IgnoreParenImpCasts();
4783   auto OriginalTy = Base->getType();
4784   if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4785     if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4786       OriginalTy = PVD->getOriginalType().getNonReferenceType();
4787 
4788   for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4789     if (OriginalTy->isAnyPointerType())
4790       OriginalTy = OriginalTy->getPointeeType();
4791     else {
4792       assert (OriginalTy->isArrayType());
4793       OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4794     }
4795   }
4796   return OriginalTy;
4797 }
4798 
4799 RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
4800                            SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
4801     : Expr(RecoveryExprClass, T.getNonReferenceType(),
4802            T->isDependentType() ? VK_LValue : getValueKindForType(T),
4803            OK_Ordinary),
4804       BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
4805   assert(!T.isNull());
4806   assert(llvm::all_of(SubExprs, [](Expr* E) { return E != nullptr; }));
4807 
4808   llvm::copy(SubExprs, getTrailingObjects<Expr *>());
4809   setDependence(computeDependence(this));
4810 }
4811 
4812 RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T,
4813                                    SourceLocation BeginLoc,
4814                                    SourceLocation EndLoc,
4815                                    ArrayRef<Expr *> SubExprs) {
4816   void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),
4817                            alignof(RecoveryExpr));
4818   return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);
4819 }
4820 
4821 RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {
4822   void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),
4823                            alignof(RecoveryExpr));
4824   return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);
4825 }
4826 
4827 void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {
4828   assert(
4829       NumDims == Dims.size() &&
4830       "Preallocated number of dimensions is different from the provided one.");
4831   llvm::copy(Dims, getTrailingObjects<Expr *>());
4832 }
4833 
4834 void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {
4835   assert(
4836       NumDims == BR.size() &&
4837       "Preallocated number of dimensions is different from the provided one.");
4838   llvm::copy(BR, getTrailingObjects<SourceRange>());
4839 }
4840 
4841 OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,
4842                                          SourceLocation L, SourceLocation R,
4843                                          ArrayRef<Expr *> Dims)
4844     : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),
4845       RPLoc(R), NumDims(Dims.size()) {
4846   setBase(Op);
4847   setDimensions(Dims);
4848   setDependence(computeDependence(this));
4849 }
4850 
4851 OMPArrayShapingExpr *
4852 OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op,
4853                             SourceLocation L, SourceLocation R,
4854                             ArrayRef<Expr *> Dims,
4855                             ArrayRef<SourceRange> BracketRanges) {
4856   assert(Dims.size() == BracketRanges.size() &&
4857          "Different number of dimensions and brackets ranges.");
4858   void *Mem = Context.Allocate(
4859       totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),
4860       alignof(OMPArrayShapingExpr));
4861   auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);
4862   E->setBracketsRanges(BracketRanges);
4863   return E;
4864 }
4865 
4866 OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,
4867                                                       unsigned NumDims) {
4868   void *Mem = Context.Allocate(
4869       totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),
4870       alignof(OMPArrayShapingExpr));
4871   return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);
4872 }
4873 
4874 void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {
4875   assert(I < NumIterators &&
4876          "Idx is greater or equal the number of iterators definitions.");
4877   getTrailingObjects<Decl *>()[I] = D;
4878 }
4879 
4880 void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {
4881   assert(I < NumIterators &&
4882          "Idx is greater or equal the number of iterators definitions.");
4883   getTrailingObjects<
4884       SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4885                         static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;
4886 }
4887 
4888 void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,
4889                                        SourceLocation ColonLoc, Expr *End,
4890                                        SourceLocation SecondColonLoc,
4891                                        Expr *Step) {
4892   assert(I < NumIterators &&
4893          "Idx is greater or equal the number of iterators definitions.");
4894   getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4895                                static_cast<int>(RangeExprOffset::Begin)] =
4896       Begin;
4897   getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4898                                static_cast<int>(RangeExprOffset::End)] = End;
4899   getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4900                                static_cast<int>(RangeExprOffset::Step)] = Step;
4901   getTrailingObjects<
4902       SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4903                         static_cast<int>(RangeLocOffset::FirstColonLoc)] =
4904       ColonLoc;
4905   getTrailingObjects<
4906       SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4907                         static_cast<int>(RangeLocOffset::SecondColonLoc)] =
4908       SecondColonLoc;
4909 }
4910 
4911 Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) {
4912   return getTrailingObjects<Decl *>()[I];
4913 }
4914 
4915 OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) {
4916   IteratorRange Res;
4917   Res.Begin =
4918       getTrailingObjects<Expr *>()[I * static_cast<int>(
4919                                            RangeExprOffset::Total) +
4920                                    static_cast<int>(RangeExprOffset::Begin)];
4921   Res.End =
4922       getTrailingObjects<Expr *>()[I * static_cast<int>(
4923                                            RangeExprOffset::Total) +
4924                                    static_cast<int>(RangeExprOffset::End)];
4925   Res.Step =
4926       getTrailingObjects<Expr *>()[I * static_cast<int>(
4927                                            RangeExprOffset::Total) +
4928                                    static_cast<int>(RangeExprOffset::Step)];
4929   return Res;
4930 }
4931 
4932 SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const {
4933   return getTrailingObjects<
4934       SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4935                         static_cast<int>(RangeLocOffset::AssignLoc)];
4936 }
4937 
4938 SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const {
4939   return getTrailingObjects<
4940       SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4941                         static_cast<int>(RangeLocOffset::FirstColonLoc)];
4942 }
4943 
4944 SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const {
4945   return getTrailingObjects<
4946       SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4947                         static_cast<int>(RangeLocOffset::SecondColonLoc)];
4948 }
4949 
4950 void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {
4951   getTrailingObjects<OMPIteratorHelperData>()[I] = D;
4952 }
4953 
4954 OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) {
4955   return getTrailingObjects<OMPIteratorHelperData>()[I];
4956 }
4957 
4958 const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const {
4959   return getTrailingObjects<OMPIteratorHelperData>()[I];
4960 }
4961 
4962 OMPIteratorExpr::OMPIteratorExpr(
4963     QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,
4964     SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
4965     ArrayRef<OMPIteratorHelperData> Helpers)
4966     : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),
4967       IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),
4968       NumIterators(Data.size()) {
4969   for (unsigned I = 0, E = Data.size(); I < E; ++I) {
4970     const IteratorDefinition &D = Data[I];
4971     setIteratorDeclaration(I, D.IteratorDecl);
4972     setAssignmentLoc(I, D.AssignmentLoc);
4973     setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,
4974                      D.SecondColonLoc, D.Range.Step);
4975     setHelper(I, Helpers[I]);
4976   }
4977   setDependence(computeDependence(this));
4978 }
4979 
4980 OMPIteratorExpr *
4981 OMPIteratorExpr::Create(const ASTContext &Context, QualType T,
4982                         SourceLocation IteratorKwLoc, SourceLocation L,
4983                         SourceLocation R,
4984                         ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
4985                         ArrayRef<OMPIteratorHelperData> Helpers) {
4986   assert(Data.size() == Helpers.size() &&
4987          "Data and helpers must have the same size.");
4988   void *Mem = Context.Allocate(
4989       totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
4990           Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),
4991           Data.size() * static_cast<int>(RangeLocOffset::Total),
4992           Helpers.size()),
4993       alignof(OMPIteratorExpr));
4994   return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);
4995 }
4996 
4997 OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,
4998                                               unsigned NumIterators) {
4999   void *Mem = Context.Allocate(
5000       totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5001           NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),
5002           NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),
5003       alignof(OMPIteratorExpr));
5004   return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);
5005 }
5006