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