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