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