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