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