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