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