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