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