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