xref: /llvm-project-15.0.7/clang/lib/AST/Expr.cpp (revision 97eec24b)
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/Expr.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Lex/LiteralSupport.h"
24 #include "clang/Lex/Lexer.h"
25 #include "clang/Sema/SemaDiagnostic.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <algorithm>
32 using namespace clang;
33 
34 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
35 /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
36 /// but also int expressions which are produced by things like comparisons in
37 /// C.
38 bool Expr::isKnownToHaveBooleanValue() const {
39   const Expr *E = IgnoreParens();
40 
41   // If this value has _Bool type, it is obvious 0/1.
42   if (E->getType()->isBooleanType()) return true;
43   // If this is a non-scalar-integer type, we don't care enough to try.
44   if (!E->getType()->isIntegralOrEnumerationType()) return false;
45 
46   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
47     switch (UO->getOpcode()) {
48     case UO_Plus:
49       return UO->getSubExpr()->isKnownToHaveBooleanValue();
50     default:
51       return false;
52     }
53   }
54 
55   // Only look through implicit casts.  If the user writes
56   // '(int) (a && b)' treat it as an arbitrary int.
57   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
58     return CE->getSubExpr()->isKnownToHaveBooleanValue();
59 
60   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
61     switch (BO->getOpcode()) {
62     default: return false;
63     case BO_LT:   // Relational operators.
64     case BO_GT:
65     case BO_LE:
66     case BO_GE:
67     case BO_EQ:   // Equality operators.
68     case BO_NE:
69     case BO_LAnd: // AND operator.
70     case BO_LOr:  // Logical OR operator.
71       return true;
72 
73     case BO_And:  // Bitwise AND operator.
74     case BO_Xor:  // Bitwise XOR operator.
75     case BO_Or:   // Bitwise OR operator.
76       // Handle things like (x==2)|(y==12).
77       return BO->getLHS()->isKnownToHaveBooleanValue() &&
78              BO->getRHS()->isKnownToHaveBooleanValue();
79 
80     case BO_Comma:
81     case BO_Assign:
82       return BO->getRHS()->isKnownToHaveBooleanValue();
83     }
84   }
85 
86   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
87     return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
88            CO->getFalseExpr()->isKnownToHaveBooleanValue();
89 
90   return false;
91 }
92 
93 // Amusing macro metaprogramming hack: check whether a class provides
94 // a more specific implementation of getExprLoc().
95 namespace {
96   /// This implementation is used when a class provides a custom
97   /// implementation of getExprLoc.
98   template <class E, class T>
99   SourceLocation getExprLocImpl(const Expr *expr,
100                                 SourceLocation (T::*v)() const) {
101     return static_cast<const E*>(expr)->getExprLoc();
102   }
103 
104   /// This implementation is used when a class doesn't provide
105   /// a custom implementation of getExprLoc.  Overload resolution
106   /// should pick it over the implementation above because it's
107   /// more specialized according to function template partial ordering.
108   template <class E>
109   SourceLocation getExprLocImpl(const Expr *expr,
110                                 SourceLocation (Expr::*v)() const) {
111     return static_cast<const E*>(expr)->getSourceRange().getBegin();
112   }
113 }
114 
115 SourceLocation Expr::getExprLoc() const {
116   switch (getStmtClass()) {
117   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
118 #define ABSTRACT_STMT(type)
119 #define STMT(type, base) \
120   case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break;
121 #define EXPR(type, base) \
122   case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
123 #include "clang/AST/StmtNodes.inc"
124   }
125   llvm_unreachable("unknown statement kind");
126   return SourceLocation();
127 }
128 
129 //===----------------------------------------------------------------------===//
130 // Primary Expressions.
131 //===----------------------------------------------------------------------===//
132 
133 void ExplicitTemplateArgumentList::initializeFrom(
134                                       const TemplateArgumentListInfo &Info) {
135   LAngleLoc = Info.getLAngleLoc();
136   RAngleLoc = Info.getRAngleLoc();
137   NumTemplateArgs = Info.size();
138 
139   TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
140   for (unsigned i = 0; i != NumTemplateArgs; ++i)
141     new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
142 }
143 
144 void ExplicitTemplateArgumentList::initializeFrom(
145                                           const TemplateArgumentListInfo &Info,
146                                                   bool &Dependent,
147                                                   bool &InstantiationDependent,
148                                        bool &ContainsUnexpandedParameterPack) {
149   LAngleLoc = Info.getLAngleLoc();
150   RAngleLoc = Info.getRAngleLoc();
151   NumTemplateArgs = Info.size();
152 
153   TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
154   for (unsigned i = 0; i != NumTemplateArgs; ++i) {
155     Dependent = Dependent || Info[i].getArgument().isDependent();
156     InstantiationDependent = InstantiationDependent ||
157                              Info[i].getArgument().isInstantiationDependent();
158     ContainsUnexpandedParameterPack
159       = ContainsUnexpandedParameterPack ||
160         Info[i].getArgument().containsUnexpandedParameterPack();
161 
162     new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
163   }
164 }
165 
166 void ExplicitTemplateArgumentList::copyInto(
167                                       TemplateArgumentListInfo &Info) const {
168   Info.setLAngleLoc(LAngleLoc);
169   Info.setRAngleLoc(RAngleLoc);
170   for (unsigned I = 0; I != NumTemplateArgs; ++I)
171     Info.addArgument(getTemplateArgs()[I]);
172 }
173 
174 std::size_t ExplicitTemplateArgumentList::sizeFor(unsigned NumTemplateArgs) {
175   return sizeof(ExplicitTemplateArgumentList) +
176          sizeof(TemplateArgumentLoc) * NumTemplateArgs;
177 }
178 
179 std::size_t ExplicitTemplateArgumentList::sizeFor(
180                                       const TemplateArgumentListInfo &Info) {
181   return sizeFor(Info.size());
182 }
183 
184 /// \brief Compute the type-, value-, and instantiation-dependence of a
185 /// declaration reference
186 /// based on the declaration being referenced.
187 static void computeDeclRefDependence(NamedDecl *D, QualType T,
188                                      bool &TypeDependent,
189                                      bool &ValueDependent,
190                                      bool &InstantiationDependent) {
191   TypeDependent = false;
192   ValueDependent = false;
193   InstantiationDependent = false;
194 
195   // (TD) C++ [temp.dep.expr]p3:
196   //   An id-expression is type-dependent if it contains:
197   //
198   // and
199   //
200   // (VD) C++ [temp.dep.constexpr]p2:
201   //  An identifier is value-dependent if it is:
202 
203   //  (TD)  - an identifier that was declared with dependent type
204   //  (VD)  - a name declared with a dependent type,
205   if (T->isDependentType()) {
206     TypeDependent = true;
207     ValueDependent = true;
208     InstantiationDependent = true;
209     return;
210   } else if (T->isInstantiationDependentType()) {
211     InstantiationDependent = true;
212   }
213 
214   //  (TD)  - a conversion-function-id that specifies a dependent type
215   if (D->getDeclName().getNameKind()
216                                 == DeclarationName::CXXConversionFunctionName) {
217     QualType T = D->getDeclName().getCXXNameType();
218     if (T->isDependentType()) {
219       TypeDependent = true;
220       ValueDependent = true;
221       InstantiationDependent = true;
222       return;
223     }
224 
225     if (T->isInstantiationDependentType())
226       InstantiationDependent = true;
227   }
228 
229   //  (VD)  - the name of a non-type template parameter,
230   if (isa<NonTypeTemplateParmDecl>(D)) {
231     ValueDependent = true;
232     InstantiationDependent = true;
233     return;
234   }
235 
236   //  (VD) - a constant with integral or enumeration type and is
237   //         initialized with an expression that is value-dependent.
238   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
239     if (Var->getType()->isIntegralOrEnumerationType() &&
240         Var->getType().getCVRQualifiers() == Qualifiers::Const) {
241       if (const Expr *Init = Var->getAnyInitializer())
242         if (Init->isValueDependent()) {
243           ValueDependent = true;
244           InstantiationDependent = true;
245         }
246     }
247 
248     // (VD) - FIXME: Missing from the standard:
249     //      -  a member function or a static data member of the current
250     //         instantiation
251     else if (Var->isStaticDataMember() &&
252              Var->getDeclContext()->isDependentContext()) {
253       ValueDependent = true;
254       InstantiationDependent = true;
255     }
256 
257     return;
258   }
259 
260   // (VD) - FIXME: Missing from the standard:
261   //      -  a member function or a static data member of the current
262   //         instantiation
263   if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
264     ValueDependent = true;
265     InstantiationDependent = true;
266     return;
267   }
268 }
269 
270 void DeclRefExpr::computeDependence() {
271   bool TypeDependent = false;
272   bool ValueDependent = false;
273   bool InstantiationDependent = false;
274   computeDeclRefDependence(getDecl(), getType(), TypeDependent, ValueDependent,
275                            InstantiationDependent);
276 
277   // (TD) C++ [temp.dep.expr]p3:
278   //   An id-expression is type-dependent if it contains:
279   //
280   // and
281   //
282   // (VD) C++ [temp.dep.constexpr]p2:
283   //  An identifier is value-dependent if it is:
284   if (!TypeDependent && !ValueDependent &&
285       hasExplicitTemplateArgs() &&
286       TemplateSpecializationType::anyDependentTemplateArguments(
287                                                             getTemplateArgs(),
288                                                        getNumTemplateArgs(),
289                                                       InstantiationDependent)) {
290     TypeDependent = true;
291     ValueDependent = true;
292     InstantiationDependent = true;
293   }
294 
295   ExprBits.TypeDependent = TypeDependent;
296   ExprBits.ValueDependent = ValueDependent;
297   ExprBits.InstantiationDependent = InstantiationDependent;
298 
299   // Is the declaration a parameter pack?
300   if (getDecl()->isParameterPack())
301     ExprBits.ContainsUnexpandedParameterPack = true;
302 }
303 
304 DeclRefExpr::DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
305                          ValueDecl *D, const DeclarationNameInfo &NameInfo,
306                          NamedDecl *FoundD,
307                          const TemplateArgumentListInfo *TemplateArgs,
308                          QualType T, ExprValueKind VK)
309   : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
310     D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
311   DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
312   if (QualifierLoc)
313     getInternalQualifierLoc() = QualifierLoc;
314   DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
315   if (FoundD)
316     getInternalFoundDecl() = FoundD;
317   DeclRefExprBits.HasExplicitTemplateArgs = TemplateArgs ? 1 : 0;
318   if (TemplateArgs) {
319     bool Dependent = false;
320     bool InstantiationDependent = false;
321     bool ContainsUnexpandedParameterPack = false;
322     getExplicitTemplateArgs().initializeFrom(*TemplateArgs, Dependent,
323                                              InstantiationDependent,
324                                              ContainsUnexpandedParameterPack);
325     if (InstantiationDependent)
326       setInstantiationDependent(true);
327   }
328 
329   computeDependence();
330 }
331 
332 DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
333                                  NestedNameSpecifierLoc QualifierLoc,
334                                  ValueDecl *D,
335                                  SourceLocation NameLoc,
336                                  QualType T,
337                                  ExprValueKind VK,
338                                  NamedDecl *FoundD,
339                                  const TemplateArgumentListInfo *TemplateArgs) {
340   return Create(Context, QualifierLoc, D,
341                 DeclarationNameInfo(D->getDeclName(), NameLoc),
342                 T, VK, FoundD, TemplateArgs);
343 }
344 
345 DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
346                                  NestedNameSpecifierLoc QualifierLoc,
347                                  ValueDecl *D,
348                                  const DeclarationNameInfo &NameInfo,
349                                  QualType T,
350                                  ExprValueKind VK,
351                                  NamedDecl *FoundD,
352                                  const TemplateArgumentListInfo *TemplateArgs) {
353   // Filter out cases where the found Decl is the same as the value refenenced.
354   if (D == FoundD)
355     FoundD = 0;
356 
357   std::size_t Size = sizeof(DeclRefExpr);
358   if (QualifierLoc != 0)
359     Size += sizeof(NestedNameSpecifierLoc);
360   if (FoundD)
361     Size += sizeof(NamedDecl *);
362   if (TemplateArgs)
363     Size += ExplicitTemplateArgumentList::sizeFor(*TemplateArgs);
364 
365   void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
366   return new (Mem) DeclRefExpr(QualifierLoc, D, NameInfo, FoundD, TemplateArgs,
367                                T, VK);
368 }
369 
370 DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context,
371                                       bool HasQualifier,
372                                       bool HasFoundDecl,
373                                       bool HasExplicitTemplateArgs,
374                                       unsigned NumTemplateArgs) {
375   std::size_t Size = sizeof(DeclRefExpr);
376   if (HasQualifier)
377     Size += sizeof(NestedNameSpecifierLoc);
378   if (HasFoundDecl)
379     Size += sizeof(NamedDecl *);
380   if (HasExplicitTemplateArgs)
381     Size += ExplicitTemplateArgumentList::sizeFor(NumTemplateArgs);
382 
383   void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
384   return new (Mem) DeclRefExpr(EmptyShell());
385 }
386 
387 SourceRange DeclRefExpr::getSourceRange() const {
388   SourceRange R = getNameInfo().getSourceRange();
389   if (hasQualifier())
390     R.setBegin(getQualifierLoc().getBeginLoc());
391   if (hasExplicitTemplateArgs())
392     R.setEnd(getRAngleLoc());
393   return R;
394 }
395 
396 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
397 // expr" policy instead.
398 std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
399   ASTContext &Context = CurrentDecl->getASTContext();
400 
401   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
402     if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual)
403       return FD->getNameAsString();
404 
405     llvm::SmallString<256> Name;
406     llvm::raw_svector_ostream Out(Name);
407 
408     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
409       if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
410         Out << "virtual ";
411       if (MD->isStatic())
412         Out << "static ";
413     }
414 
415     PrintingPolicy Policy(Context.getLangOptions());
416 
417     std::string Proto = FD->getQualifiedNameAsString(Policy);
418 
419     const FunctionType *AFT = FD->getType()->getAs<FunctionType>();
420     const FunctionProtoType *FT = 0;
421     if (FD->hasWrittenPrototype())
422       FT = dyn_cast<FunctionProtoType>(AFT);
423 
424     Proto += "(";
425     if (FT) {
426       llvm::raw_string_ostream POut(Proto);
427       for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
428         if (i) POut << ", ";
429         std::string Param;
430         FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
431         POut << Param;
432       }
433 
434       if (FT->isVariadic()) {
435         if (FD->getNumParams()) POut << ", ";
436         POut << "...";
437       }
438     }
439     Proto += ")";
440 
441     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
442       Qualifiers ThisQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
443       if (ThisQuals.hasConst())
444         Proto += " const";
445       if (ThisQuals.hasVolatile())
446         Proto += " volatile";
447     }
448 
449     if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
450       AFT->getResultType().getAsStringInternal(Proto, Policy);
451 
452     Out << Proto;
453 
454     Out.flush();
455     return Name.str().str();
456   }
457   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
458     llvm::SmallString<256> Name;
459     llvm::raw_svector_ostream Out(Name);
460     Out << (MD->isInstanceMethod() ? '-' : '+');
461     Out << '[';
462 
463     // For incorrect code, there might not be an ObjCInterfaceDecl.  Do
464     // a null check to avoid a crash.
465     if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
466       Out << ID;
467 
468     if (const ObjCCategoryImplDecl *CID =
469         dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
470       Out << '(' << CID << ')';
471 
472     Out <<  ' ';
473     Out << MD->getSelector().getAsString();
474     Out <<  ']';
475 
476     Out.flush();
477     return Name.str().str();
478   }
479   if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
480     // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
481     return "top level";
482   }
483   return "";
484 }
485 
486 void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) {
487   if (hasAllocation())
488     C.Deallocate(pVal);
489 
490   BitWidth = Val.getBitWidth();
491   unsigned NumWords = Val.getNumWords();
492   const uint64_t* Words = Val.getRawData();
493   if (NumWords > 1) {
494     pVal = new (C) uint64_t[NumWords];
495     std::copy(Words, Words + NumWords, pVal);
496   } else if (NumWords == 1)
497     VAL = Words[0];
498   else
499     VAL = 0;
500 }
501 
502 IntegerLiteral *
503 IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V,
504                        QualType type, SourceLocation l) {
505   return new (C) IntegerLiteral(C, V, type, l);
506 }
507 
508 IntegerLiteral *
509 IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) {
510   return new (C) IntegerLiteral(Empty);
511 }
512 
513 FloatingLiteral *
514 FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V,
515                         bool isexact, QualType Type, SourceLocation L) {
516   return new (C) FloatingLiteral(C, V, isexact, Type, L);
517 }
518 
519 FloatingLiteral *
520 FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
521   return new (C) FloatingLiteral(Empty);
522 }
523 
524 /// getValueAsApproximateDouble - This returns the value as an inaccurate
525 /// double.  Note that this may cause loss of precision, but is useful for
526 /// debugging dumps, etc.
527 double FloatingLiteral::getValueAsApproximateDouble() const {
528   llvm::APFloat V = getValue();
529   bool ignored;
530   V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
531             &ignored);
532   return V.convertToDouble();
533 }
534 
535 StringLiteral *StringLiteral::Create(ASTContext &C, StringRef Str,
536                                      StringKind Kind, bool Pascal, QualType Ty,
537                                      const SourceLocation *Loc,
538                                      unsigned NumStrs) {
539   // Allocate enough space for the StringLiteral plus an array of locations for
540   // any concatenated string tokens.
541   void *Mem = C.Allocate(sizeof(StringLiteral)+
542                          sizeof(SourceLocation)*(NumStrs-1),
543                          llvm::alignOf<StringLiteral>());
544   StringLiteral *SL = new (Mem) StringLiteral(Ty);
545 
546   // OPTIMIZE: could allocate this appended to the StringLiteral.
547   char *AStrData = new (C, 1) char[Str.size()];
548   memcpy(AStrData, Str.data(), Str.size());
549   SL->StrData = AStrData;
550   SL->ByteLength = Str.size();
551   SL->Kind = Kind;
552   SL->IsPascal = Pascal;
553   SL->TokLocs[0] = Loc[0];
554   SL->NumConcatenated = NumStrs;
555 
556   if (NumStrs != 1)
557     memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
558   return SL;
559 }
560 
561 StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
562   void *Mem = C.Allocate(sizeof(StringLiteral)+
563                          sizeof(SourceLocation)*(NumStrs-1),
564                          llvm::alignOf<StringLiteral>());
565   StringLiteral *SL = new (Mem) StringLiteral(QualType());
566   SL->StrData = 0;
567   SL->ByteLength = 0;
568   SL->NumConcatenated = NumStrs;
569   return SL;
570 }
571 
572 void StringLiteral::setString(ASTContext &C, StringRef Str) {
573   char *AStrData = new (C, 1) char[Str.size()];
574   memcpy(AStrData, Str.data(), Str.size());
575   StrData = AStrData;
576   ByteLength = Str.size();
577 }
578 
579 /// getLocationOfByte - Return a source location that points to the specified
580 /// byte of this string literal.
581 ///
582 /// Strings are amazingly complex.  They can be formed from multiple tokens and
583 /// can have escape sequences in them in addition to the usual trigraph and
584 /// escaped newline business.  This routine handles this complexity.
585 ///
586 SourceLocation StringLiteral::
587 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
588                   const LangOptions &Features, const TargetInfo &Target) const {
589   assert(Kind == StringLiteral::Ascii && "This only works for ASCII strings");
590 
591   // Loop over all of the tokens in this string until we find the one that
592   // contains the byte we're looking for.
593   unsigned TokNo = 0;
594   while (1) {
595     assert(TokNo < getNumConcatenated() && "Invalid byte number!");
596     SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
597 
598     // Get the spelling of the string so that we can get the data that makes up
599     // the string literal, not the identifier for the macro it is potentially
600     // expanded through.
601     SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
602 
603     // Re-lex the token to get its length and original spelling.
604     std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
605     bool Invalid = false;
606     StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
607     if (Invalid)
608       return StrTokSpellingLoc;
609 
610     const char *StrData = Buffer.data()+LocInfo.second;
611 
612     // Create a langops struct and enable trigraphs.  This is sufficient for
613     // relexing tokens.
614     LangOptions LangOpts;
615     LangOpts.Trigraphs = true;
616 
617     // Create a lexer starting at the beginning of this token.
618     Lexer TheLexer(StrTokSpellingLoc, Features, Buffer.begin(), StrData,
619                    Buffer.end());
620     Token TheTok;
621     TheLexer.LexFromRawLexer(TheTok);
622 
623     // Use the StringLiteralParser to compute the length of the string in bytes.
624     StringLiteralParser SLP(&TheTok, 1, SM, Features, Target);
625     unsigned TokNumBytes = SLP.GetStringLength();
626 
627     // If the byte is in this token, return the location of the byte.
628     if (ByteNo < TokNumBytes ||
629         (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
630       unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
631 
632       // Now that we know the offset of the token in the spelling, use the
633       // preprocessor to get the offset in the original source.
634       return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
635     }
636 
637     // Move to the next string token.
638     ++TokNo;
639     ByteNo -= TokNumBytes;
640   }
641 }
642 
643 
644 
645 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
646 /// corresponds to, e.g. "sizeof" or "[pre]++".
647 const char *UnaryOperator::getOpcodeStr(Opcode Op) {
648   switch (Op) {
649   default: assert(0 && "Unknown unary operator");
650   case UO_PostInc: return "++";
651   case UO_PostDec: return "--";
652   case UO_PreInc:  return "++";
653   case UO_PreDec:  return "--";
654   case UO_AddrOf:  return "&";
655   case UO_Deref:   return "*";
656   case UO_Plus:    return "+";
657   case UO_Minus:   return "-";
658   case UO_Not:     return "~";
659   case UO_LNot:    return "!";
660   case UO_Real:    return "__real";
661   case UO_Imag:    return "__imag";
662   case UO_Extension: return "__extension__";
663   }
664 }
665 
666 UnaryOperatorKind
667 UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
668   switch (OO) {
669   default: assert(false && "No unary operator for overloaded function");
670   case OO_PlusPlus:   return Postfix ? UO_PostInc : UO_PreInc;
671   case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
672   case OO_Amp:        return UO_AddrOf;
673   case OO_Star:       return UO_Deref;
674   case OO_Plus:       return UO_Plus;
675   case OO_Minus:      return UO_Minus;
676   case OO_Tilde:      return UO_Not;
677   case OO_Exclaim:    return UO_LNot;
678   }
679 }
680 
681 OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
682   switch (Opc) {
683   case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
684   case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
685   case UO_AddrOf: return OO_Amp;
686   case UO_Deref: return OO_Star;
687   case UO_Plus: return OO_Plus;
688   case UO_Minus: return OO_Minus;
689   case UO_Not: return OO_Tilde;
690   case UO_LNot: return OO_Exclaim;
691   default: return OO_None;
692   }
693 }
694 
695 
696 //===----------------------------------------------------------------------===//
697 // Postfix Operators.
698 //===----------------------------------------------------------------------===//
699 
700 CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
701                    Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
702                    SourceLocation rparenloc)
703   : Expr(SC, t, VK, OK_Ordinary,
704          fn->isTypeDependent(),
705          fn->isValueDependent(),
706          fn->isInstantiationDependent(),
707          fn->containsUnexpandedParameterPack()),
708     NumArgs(numargs) {
709 
710   SubExprs = new (C) Stmt*[numargs+PREARGS_START+NumPreArgs];
711   SubExprs[FN] = fn;
712   for (unsigned i = 0; i != numargs; ++i) {
713     if (args[i]->isTypeDependent())
714       ExprBits.TypeDependent = true;
715     if (args[i]->isValueDependent())
716       ExprBits.ValueDependent = true;
717     if (args[i]->isInstantiationDependent())
718       ExprBits.InstantiationDependent = true;
719     if (args[i]->containsUnexpandedParameterPack())
720       ExprBits.ContainsUnexpandedParameterPack = true;
721 
722     SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
723   }
724 
725   CallExprBits.NumPreArgs = NumPreArgs;
726   RParenLoc = rparenloc;
727 }
728 
729 CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs,
730                    QualType t, ExprValueKind VK, SourceLocation rparenloc)
731   : Expr(CallExprClass, t, VK, OK_Ordinary,
732          fn->isTypeDependent(),
733          fn->isValueDependent(),
734          fn->isInstantiationDependent(),
735          fn->containsUnexpandedParameterPack()),
736     NumArgs(numargs) {
737 
738   SubExprs = new (C) Stmt*[numargs+PREARGS_START];
739   SubExprs[FN] = fn;
740   for (unsigned i = 0; i != numargs; ++i) {
741     if (args[i]->isTypeDependent())
742       ExprBits.TypeDependent = true;
743     if (args[i]->isValueDependent())
744       ExprBits.ValueDependent = true;
745     if (args[i]->isInstantiationDependent())
746       ExprBits.InstantiationDependent = true;
747     if (args[i]->containsUnexpandedParameterPack())
748       ExprBits.ContainsUnexpandedParameterPack = true;
749 
750     SubExprs[i+PREARGS_START] = args[i];
751   }
752 
753   CallExprBits.NumPreArgs = 0;
754   RParenLoc = rparenloc;
755 }
756 
757 CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
758   : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
759   // FIXME: Why do we allocate this?
760   SubExprs = new (C) Stmt*[PREARGS_START];
761   CallExprBits.NumPreArgs = 0;
762 }
763 
764 CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs,
765                    EmptyShell Empty)
766   : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
767   // FIXME: Why do we allocate this?
768   SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
769   CallExprBits.NumPreArgs = NumPreArgs;
770 }
771 
772 Decl *CallExpr::getCalleeDecl() {
773   Expr *CEE = getCallee()->IgnoreParenImpCasts();
774 
775   while (SubstNonTypeTemplateParmExpr *NTTP
776                                 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
777     CEE = NTTP->getReplacement()->IgnoreParenCasts();
778   }
779 
780   // If we're calling a dereference, look at the pointer instead.
781   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
782     if (BO->isPtrMemOp())
783       CEE = BO->getRHS()->IgnoreParenCasts();
784   } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
785     if (UO->getOpcode() == UO_Deref)
786       CEE = UO->getSubExpr()->IgnoreParenCasts();
787   }
788   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
789     return DRE->getDecl();
790   if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
791     return ME->getMemberDecl();
792 
793   return 0;
794 }
795 
796 FunctionDecl *CallExpr::getDirectCallee() {
797   return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
798 }
799 
800 /// setNumArgs - This changes the number of arguments present in this call.
801 /// Any orphaned expressions are deleted by this, and any new operands are set
802 /// to null.
803 void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
804   // No change, just return.
805   if (NumArgs == getNumArgs()) return;
806 
807   // If shrinking # arguments, just delete the extras and forgot them.
808   if (NumArgs < getNumArgs()) {
809     this->NumArgs = NumArgs;
810     return;
811   }
812 
813   // Otherwise, we are growing the # arguments.  New an bigger argument array.
814   unsigned NumPreArgs = getNumPreArgs();
815   Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
816   // Copy over args.
817   for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
818     NewSubExprs[i] = SubExprs[i];
819   // Null out new args.
820   for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
821        i != NumArgs+PREARGS_START+NumPreArgs; ++i)
822     NewSubExprs[i] = 0;
823 
824   if (SubExprs) C.Deallocate(SubExprs);
825   SubExprs = NewSubExprs;
826   this->NumArgs = NumArgs;
827 }
828 
829 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
830 /// not, return 0.
831 unsigned CallExpr::isBuiltinCall(const ASTContext &Context) const {
832   // All simple function calls (e.g. func()) are implicitly cast to pointer to
833   // function. As a result, we try and obtain the DeclRefExpr from the
834   // ImplicitCastExpr.
835   const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
836   if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
837     return 0;
838 
839   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
840   if (!DRE)
841     return 0;
842 
843   const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
844   if (!FDecl)
845     return 0;
846 
847   if (!FDecl->getIdentifier())
848     return 0;
849 
850   return FDecl->getBuiltinID();
851 }
852 
853 QualType CallExpr::getCallReturnType() const {
854   QualType CalleeType = getCallee()->getType();
855   if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
856     CalleeType = FnTypePtr->getPointeeType();
857   else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
858     CalleeType = BPT->getPointeeType();
859   else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember))
860     // This should never be overloaded and so should never return null.
861     CalleeType = Expr::findBoundMemberType(getCallee());
862 
863   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
864   return FnType->getResultType();
865 }
866 
867 SourceRange CallExpr::getSourceRange() const {
868   if (isa<CXXOperatorCallExpr>(this))
869     return cast<CXXOperatorCallExpr>(this)->getSourceRange();
870 
871   SourceLocation begin = getCallee()->getLocStart();
872   if (begin.isInvalid() && getNumArgs() > 0)
873     begin = getArg(0)->getLocStart();
874   SourceLocation end = getRParenLoc();
875   if (end.isInvalid() && getNumArgs() > 0)
876     end = getArg(getNumArgs() - 1)->getLocEnd();
877   return SourceRange(begin, end);
878 }
879 
880 OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,
881                                    SourceLocation OperatorLoc,
882                                    TypeSourceInfo *tsi,
883                                    OffsetOfNode* compsPtr, unsigned numComps,
884                                    Expr** exprsPtr, unsigned numExprs,
885                                    SourceLocation RParenLoc) {
886   void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
887                          sizeof(OffsetOfNode) * numComps +
888                          sizeof(Expr*) * numExprs);
889 
890   return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, compsPtr, numComps,
891                                 exprsPtr, numExprs, RParenLoc);
892 }
893 
894 OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C,
895                                         unsigned numComps, unsigned numExprs) {
896   void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
897                          sizeof(OffsetOfNode) * numComps +
898                          sizeof(Expr*) * numExprs);
899   return new (Mem) OffsetOfExpr(numComps, numExprs);
900 }
901 
902 OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type,
903                            SourceLocation OperatorLoc, TypeSourceInfo *tsi,
904                            OffsetOfNode* compsPtr, unsigned numComps,
905                            Expr** exprsPtr, unsigned numExprs,
906                            SourceLocation RParenLoc)
907   : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
908          /*TypeDependent=*/false,
909          /*ValueDependent=*/tsi->getType()->isDependentType(),
910          tsi->getType()->isInstantiationDependentType(),
911          tsi->getType()->containsUnexpandedParameterPack()),
912     OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
913     NumComps(numComps), NumExprs(numExprs)
914 {
915   for(unsigned i = 0; i < numComps; ++i) {
916     setComponent(i, compsPtr[i]);
917   }
918 
919   for(unsigned i = 0; i < numExprs; ++i) {
920     if (exprsPtr[i]->isTypeDependent() || exprsPtr[i]->isValueDependent())
921       ExprBits.ValueDependent = true;
922     if (exprsPtr[i]->containsUnexpandedParameterPack())
923       ExprBits.ContainsUnexpandedParameterPack = true;
924 
925     setIndexExpr(i, exprsPtr[i]);
926   }
927 }
928 
929 IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
930   assert(getKind() == Field || getKind() == Identifier);
931   if (getKind() == Field)
932     return getField()->getIdentifier();
933 
934   return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
935 }
936 
937 MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
938                                NestedNameSpecifierLoc QualifierLoc,
939                                ValueDecl *memberdecl,
940                                DeclAccessPair founddecl,
941                                DeclarationNameInfo nameinfo,
942                                const TemplateArgumentListInfo *targs,
943                                QualType ty,
944                                ExprValueKind vk,
945                                ExprObjectKind ok) {
946   std::size_t Size = sizeof(MemberExpr);
947 
948   bool hasQualOrFound = (QualifierLoc ||
949                          founddecl.getDecl() != memberdecl ||
950                          founddecl.getAccess() != memberdecl->getAccess());
951   if (hasQualOrFound)
952     Size += sizeof(MemberNameQualifier);
953 
954   if (targs)
955     Size += ExplicitTemplateArgumentList::sizeFor(*targs);
956 
957   void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
958   MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo,
959                                        ty, vk, ok);
960 
961   if (hasQualOrFound) {
962     // FIXME: Wrong. We should be looking at the member declaration we found.
963     if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
964       E->setValueDependent(true);
965       E->setTypeDependent(true);
966       E->setInstantiationDependent(true);
967     }
968     else if (QualifierLoc &&
969              QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
970       E->setInstantiationDependent(true);
971 
972     E->HasQualifierOrFoundDecl = true;
973 
974     MemberNameQualifier *NQ = E->getMemberQualifier();
975     NQ->QualifierLoc = QualifierLoc;
976     NQ->FoundDecl = founddecl;
977   }
978 
979   if (targs) {
980     bool Dependent = false;
981     bool InstantiationDependent = false;
982     bool ContainsUnexpandedParameterPack = false;
983     E->HasExplicitTemplateArgumentList = true;
984     E->getExplicitTemplateArgs().initializeFrom(*targs, Dependent,
985                                                 InstantiationDependent,
986                                               ContainsUnexpandedParameterPack);
987     if (InstantiationDependent)
988       E->setInstantiationDependent(true);
989   }
990 
991   return E;
992 }
993 
994 SourceRange MemberExpr::getSourceRange() const {
995   SourceLocation StartLoc;
996   if (isImplicitAccess()) {
997     if (hasQualifier())
998       StartLoc = getQualifierLoc().getBeginLoc();
999     else
1000       StartLoc = MemberLoc;
1001   } else {
1002     // FIXME: We don't want this to happen. Rather, we should be able to
1003     // detect all kinds of implicit accesses more cleanly.
1004     StartLoc = getBase()->getLocStart();
1005     if (StartLoc.isInvalid())
1006       StartLoc = MemberLoc;
1007   }
1008 
1009   SourceLocation EndLoc =
1010     HasExplicitTemplateArgumentList? getRAngleLoc()
1011                                    : getMemberNameInfo().getEndLoc();
1012 
1013   return SourceRange(StartLoc, EndLoc);
1014 }
1015 
1016 void CastExpr::CheckCastConsistency() const {
1017   switch (getCastKind()) {
1018   case CK_DerivedToBase:
1019   case CK_UncheckedDerivedToBase:
1020   case CK_DerivedToBaseMemberPointer:
1021   case CK_BaseToDerived:
1022   case CK_BaseToDerivedMemberPointer:
1023     assert(!path_empty() && "Cast kind should have a base path!");
1024     break;
1025 
1026   case CK_CPointerToObjCPointerCast:
1027     assert(getType()->isObjCObjectPointerType());
1028     assert(getSubExpr()->getType()->isPointerType());
1029     goto CheckNoBasePath;
1030 
1031   case CK_BlockPointerToObjCPointerCast:
1032     assert(getType()->isObjCObjectPointerType());
1033     assert(getSubExpr()->getType()->isBlockPointerType());
1034     goto CheckNoBasePath;
1035 
1036   case CK_BitCast:
1037     // Arbitrary casts to C pointer types count as bitcasts.
1038     // Otherwise, we should only have block and ObjC pointer casts
1039     // here if they stay within the type kind.
1040     if (!getType()->isPointerType()) {
1041       assert(getType()->isObjCObjectPointerType() ==
1042              getSubExpr()->getType()->isObjCObjectPointerType());
1043       assert(getType()->isBlockPointerType() ==
1044              getSubExpr()->getType()->isBlockPointerType());
1045     }
1046     goto CheckNoBasePath;
1047 
1048   case CK_AnyPointerToBlockPointerCast:
1049     assert(getType()->isBlockPointerType());
1050     assert(getSubExpr()->getType()->isAnyPointerType() &&
1051            !getSubExpr()->getType()->isBlockPointerType());
1052     goto CheckNoBasePath;
1053 
1054   // These should not have an inheritance path.
1055   case CK_Dynamic:
1056   case CK_ToUnion:
1057   case CK_ArrayToPointerDecay:
1058   case CK_FunctionToPointerDecay:
1059   case CK_NullToMemberPointer:
1060   case CK_NullToPointer:
1061   case CK_ConstructorConversion:
1062   case CK_IntegralToPointer:
1063   case CK_PointerToIntegral:
1064   case CK_ToVoid:
1065   case CK_VectorSplat:
1066   case CK_IntegralCast:
1067   case CK_IntegralToFloating:
1068   case CK_FloatingToIntegral:
1069   case CK_FloatingCast:
1070   case CK_ObjCObjectLValueCast:
1071   case CK_FloatingRealToComplex:
1072   case CK_FloatingComplexToReal:
1073   case CK_FloatingComplexCast:
1074   case CK_FloatingComplexToIntegralComplex:
1075   case CK_IntegralRealToComplex:
1076   case CK_IntegralComplexToReal:
1077   case CK_IntegralComplexCast:
1078   case CK_IntegralComplexToFloatingComplex:
1079   case CK_ARCProduceObject:
1080   case CK_ARCConsumeObject:
1081   case CK_ARCReclaimReturnedObject:
1082   case CK_ARCExtendBlockObject:
1083     assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1084     goto CheckNoBasePath;
1085 
1086   case CK_Dependent:
1087   case CK_LValueToRValue:
1088   case CK_GetObjCProperty:
1089   case CK_NoOp:
1090   case CK_PointerToBoolean:
1091   case CK_IntegralToBoolean:
1092   case CK_FloatingToBoolean:
1093   case CK_MemberPointerToBoolean:
1094   case CK_FloatingComplexToBoolean:
1095   case CK_IntegralComplexToBoolean:
1096   case CK_LValueBitCast:            // -> bool&
1097   case CK_UserDefinedConversion:    // operator bool()
1098   CheckNoBasePath:
1099     assert(path_empty() && "Cast kind should not have a base path!");
1100     break;
1101   }
1102 }
1103 
1104 const char *CastExpr::getCastKindName() const {
1105   switch (getCastKind()) {
1106   case CK_Dependent:
1107     return "Dependent";
1108   case CK_BitCast:
1109     return "BitCast";
1110   case CK_LValueBitCast:
1111     return "LValueBitCast";
1112   case CK_LValueToRValue:
1113     return "LValueToRValue";
1114   case CK_GetObjCProperty:
1115     return "GetObjCProperty";
1116   case CK_NoOp:
1117     return "NoOp";
1118   case CK_BaseToDerived:
1119     return "BaseToDerived";
1120   case CK_DerivedToBase:
1121     return "DerivedToBase";
1122   case CK_UncheckedDerivedToBase:
1123     return "UncheckedDerivedToBase";
1124   case CK_Dynamic:
1125     return "Dynamic";
1126   case CK_ToUnion:
1127     return "ToUnion";
1128   case CK_ArrayToPointerDecay:
1129     return "ArrayToPointerDecay";
1130   case CK_FunctionToPointerDecay:
1131     return "FunctionToPointerDecay";
1132   case CK_NullToMemberPointer:
1133     return "NullToMemberPointer";
1134   case CK_NullToPointer:
1135     return "NullToPointer";
1136   case CK_BaseToDerivedMemberPointer:
1137     return "BaseToDerivedMemberPointer";
1138   case CK_DerivedToBaseMemberPointer:
1139     return "DerivedToBaseMemberPointer";
1140   case CK_UserDefinedConversion:
1141     return "UserDefinedConversion";
1142   case CK_ConstructorConversion:
1143     return "ConstructorConversion";
1144   case CK_IntegralToPointer:
1145     return "IntegralToPointer";
1146   case CK_PointerToIntegral:
1147     return "PointerToIntegral";
1148   case CK_PointerToBoolean:
1149     return "PointerToBoolean";
1150   case CK_ToVoid:
1151     return "ToVoid";
1152   case CK_VectorSplat:
1153     return "VectorSplat";
1154   case CK_IntegralCast:
1155     return "IntegralCast";
1156   case CK_IntegralToBoolean:
1157     return "IntegralToBoolean";
1158   case CK_IntegralToFloating:
1159     return "IntegralToFloating";
1160   case CK_FloatingToIntegral:
1161     return "FloatingToIntegral";
1162   case CK_FloatingCast:
1163     return "FloatingCast";
1164   case CK_FloatingToBoolean:
1165     return "FloatingToBoolean";
1166   case CK_MemberPointerToBoolean:
1167     return "MemberPointerToBoolean";
1168   case CK_CPointerToObjCPointerCast:
1169     return "CPointerToObjCPointerCast";
1170   case CK_BlockPointerToObjCPointerCast:
1171     return "BlockPointerToObjCPointerCast";
1172   case CK_AnyPointerToBlockPointerCast:
1173     return "AnyPointerToBlockPointerCast";
1174   case CK_ObjCObjectLValueCast:
1175     return "ObjCObjectLValueCast";
1176   case CK_FloatingRealToComplex:
1177     return "FloatingRealToComplex";
1178   case CK_FloatingComplexToReal:
1179     return "FloatingComplexToReal";
1180   case CK_FloatingComplexToBoolean:
1181     return "FloatingComplexToBoolean";
1182   case CK_FloatingComplexCast:
1183     return "FloatingComplexCast";
1184   case CK_FloatingComplexToIntegralComplex:
1185     return "FloatingComplexToIntegralComplex";
1186   case CK_IntegralRealToComplex:
1187     return "IntegralRealToComplex";
1188   case CK_IntegralComplexToReal:
1189     return "IntegralComplexToReal";
1190   case CK_IntegralComplexToBoolean:
1191     return "IntegralComplexToBoolean";
1192   case CK_IntegralComplexCast:
1193     return "IntegralComplexCast";
1194   case CK_IntegralComplexToFloatingComplex:
1195     return "IntegralComplexToFloatingComplex";
1196   case CK_ARCConsumeObject:
1197     return "ARCConsumeObject";
1198   case CK_ARCProduceObject:
1199     return "ARCProduceObject";
1200   case CK_ARCReclaimReturnedObject:
1201     return "ARCReclaimReturnedObject";
1202   case CK_ARCExtendBlockObject:
1203     return "ARCCExtendBlockObject";
1204   }
1205 
1206   llvm_unreachable("Unhandled cast kind!");
1207   return 0;
1208 }
1209 
1210 Expr *CastExpr::getSubExprAsWritten() {
1211   Expr *SubExpr = 0;
1212   CastExpr *E = this;
1213   do {
1214     SubExpr = E->getSubExpr();
1215 
1216     // Skip through reference binding to temporary.
1217     if (MaterializeTemporaryExpr *Materialize
1218                                   = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
1219       SubExpr = Materialize->GetTemporaryExpr();
1220 
1221     // Skip any temporary bindings; they're implicit.
1222     if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1223       SubExpr = Binder->getSubExpr();
1224 
1225     // Conversions by constructor and conversion functions have a
1226     // subexpression describing the call; strip it off.
1227     if (E->getCastKind() == CK_ConstructorConversion)
1228       SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
1229     else if (E->getCastKind() == CK_UserDefinedConversion)
1230       SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1231 
1232     // If the subexpression we're left with is an implicit cast, look
1233     // through that, too.
1234   } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1235 
1236   return SubExpr;
1237 }
1238 
1239 CXXBaseSpecifier **CastExpr::path_buffer() {
1240   switch (getStmtClass()) {
1241 #define ABSTRACT_STMT(x)
1242 #define CASTEXPR(Type, Base) \
1243   case Stmt::Type##Class: \
1244     return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
1245 #define STMT(Type, Base)
1246 #include "clang/AST/StmtNodes.inc"
1247   default:
1248     llvm_unreachable("non-cast expressions not possible here");
1249     return 0;
1250   }
1251 }
1252 
1253 void CastExpr::setCastPath(const CXXCastPath &Path) {
1254   assert(Path.size() == path_size());
1255   memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
1256 }
1257 
1258 ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T,
1259                                            CastKind Kind, Expr *Operand,
1260                                            const CXXCastPath *BasePath,
1261                                            ExprValueKind VK) {
1262   unsigned PathSize = (BasePath ? BasePath->size() : 0);
1263   void *Buffer =
1264     C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1265   ImplicitCastExpr *E =
1266     new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1267   if (PathSize) E->setCastPath(*BasePath);
1268   return E;
1269 }
1270 
1271 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C,
1272                                                 unsigned PathSize) {
1273   void *Buffer =
1274     C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1275   return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1276 }
1277 
1278 
1279 CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T,
1280                                        ExprValueKind VK, CastKind K, Expr *Op,
1281                                        const CXXCastPath *BasePath,
1282                                        TypeSourceInfo *WrittenTy,
1283                                        SourceLocation L, SourceLocation R) {
1284   unsigned PathSize = (BasePath ? BasePath->size() : 0);
1285   void *Buffer =
1286     C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1287   CStyleCastExpr *E =
1288     new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
1289   if (PathSize) E->setCastPath(*BasePath);
1290   return E;
1291 }
1292 
1293 CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
1294   void *Buffer =
1295     C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1296   return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1297 }
1298 
1299 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1300 /// corresponds to, e.g. "<<=".
1301 const char *BinaryOperator::getOpcodeStr(Opcode Op) {
1302   switch (Op) {
1303   case BO_PtrMemD:   return ".*";
1304   case BO_PtrMemI:   return "->*";
1305   case BO_Mul:       return "*";
1306   case BO_Div:       return "/";
1307   case BO_Rem:       return "%";
1308   case BO_Add:       return "+";
1309   case BO_Sub:       return "-";
1310   case BO_Shl:       return "<<";
1311   case BO_Shr:       return ">>";
1312   case BO_LT:        return "<";
1313   case BO_GT:        return ">";
1314   case BO_LE:        return "<=";
1315   case BO_GE:        return ">=";
1316   case BO_EQ:        return "==";
1317   case BO_NE:        return "!=";
1318   case BO_And:       return "&";
1319   case BO_Xor:       return "^";
1320   case BO_Or:        return "|";
1321   case BO_LAnd:      return "&&";
1322   case BO_LOr:       return "||";
1323   case BO_Assign:    return "=";
1324   case BO_MulAssign: return "*=";
1325   case BO_DivAssign: return "/=";
1326   case BO_RemAssign: return "%=";
1327   case BO_AddAssign: return "+=";
1328   case BO_SubAssign: return "-=";
1329   case BO_ShlAssign: return "<<=";
1330   case BO_ShrAssign: return ">>=";
1331   case BO_AndAssign: return "&=";
1332   case BO_XorAssign: return "^=";
1333   case BO_OrAssign:  return "|=";
1334   case BO_Comma:     return ",";
1335   }
1336 
1337   return "";
1338 }
1339 
1340 BinaryOperatorKind
1341 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1342   switch (OO) {
1343   default: assert(false && "Not an overloadable binary operator");
1344   case OO_Plus: return BO_Add;
1345   case OO_Minus: return BO_Sub;
1346   case OO_Star: return BO_Mul;
1347   case OO_Slash: return BO_Div;
1348   case OO_Percent: return BO_Rem;
1349   case OO_Caret: return BO_Xor;
1350   case OO_Amp: return BO_And;
1351   case OO_Pipe: return BO_Or;
1352   case OO_Equal: return BO_Assign;
1353   case OO_Less: return BO_LT;
1354   case OO_Greater: return BO_GT;
1355   case OO_PlusEqual: return BO_AddAssign;
1356   case OO_MinusEqual: return BO_SubAssign;
1357   case OO_StarEqual: return BO_MulAssign;
1358   case OO_SlashEqual: return BO_DivAssign;
1359   case OO_PercentEqual: return BO_RemAssign;
1360   case OO_CaretEqual: return BO_XorAssign;
1361   case OO_AmpEqual: return BO_AndAssign;
1362   case OO_PipeEqual: return BO_OrAssign;
1363   case OO_LessLess: return BO_Shl;
1364   case OO_GreaterGreater: return BO_Shr;
1365   case OO_LessLessEqual: return BO_ShlAssign;
1366   case OO_GreaterGreaterEqual: return BO_ShrAssign;
1367   case OO_EqualEqual: return BO_EQ;
1368   case OO_ExclaimEqual: return BO_NE;
1369   case OO_LessEqual: return BO_LE;
1370   case OO_GreaterEqual: return BO_GE;
1371   case OO_AmpAmp: return BO_LAnd;
1372   case OO_PipePipe: return BO_LOr;
1373   case OO_Comma: return BO_Comma;
1374   case OO_ArrowStar: return BO_PtrMemI;
1375   }
1376 }
1377 
1378 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1379   static const OverloadedOperatorKind OverOps[] = {
1380     /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1381     OO_Star, OO_Slash, OO_Percent,
1382     OO_Plus, OO_Minus,
1383     OO_LessLess, OO_GreaterGreater,
1384     OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1385     OO_EqualEqual, OO_ExclaimEqual,
1386     OO_Amp,
1387     OO_Caret,
1388     OO_Pipe,
1389     OO_AmpAmp,
1390     OO_PipePipe,
1391     OO_Equal, OO_StarEqual,
1392     OO_SlashEqual, OO_PercentEqual,
1393     OO_PlusEqual, OO_MinusEqual,
1394     OO_LessLessEqual, OO_GreaterGreaterEqual,
1395     OO_AmpEqual, OO_CaretEqual,
1396     OO_PipeEqual,
1397     OO_Comma
1398   };
1399   return OverOps[Opc];
1400 }
1401 
1402 InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc,
1403                            Expr **initExprs, unsigned numInits,
1404                            SourceLocation rbraceloc)
1405   : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1406          false, false),
1407     InitExprs(C, numInits),
1408     LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0),
1409     HadArrayRangeDesignator(false)
1410 {
1411   for (unsigned I = 0; I != numInits; ++I) {
1412     if (initExprs[I]->isTypeDependent())
1413       ExprBits.TypeDependent = true;
1414     if (initExprs[I]->isValueDependent())
1415       ExprBits.ValueDependent = true;
1416     if (initExprs[I]->isInstantiationDependent())
1417       ExprBits.InstantiationDependent = true;
1418     if (initExprs[I]->containsUnexpandedParameterPack())
1419       ExprBits.ContainsUnexpandedParameterPack = true;
1420   }
1421 
1422   InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits);
1423 }
1424 
1425 void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) {
1426   if (NumInits > InitExprs.size())
1427     InitExprs.reserve(C, NumInits);
1428 }
1429 
1430 void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) {
1431   InitExprs.resize(C, NumInits, 0);
1432 }
1433 
1434 Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) {
1435   if (Init >= InitExprs.size()) {
1436     InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0);
1437     InitExprs.back() = expr;
1438     return 0;
1439   }
1440 
1441   Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1442   InitExprs[Init] = expr;
1443   return Result;
1444 }
1445 
1446 void InitListExpr::setArrayFiller(Expr *filler) {
1447   ArrayFillerOrUnionFieldInit = filler;
1448   // Fill out any "holes" in the array due to designated initializers.
1449   Expr **inits = getInits();
1450   for (unsigned i = 0, e = getNumInits(); i != e; ++i)
1451     if (inits[i] == 0)
1452       inits[i] = filler;
1453 }
1454 
1455 SourceRange InitListExpr::getSourceRange() const {
1456   if (SyntacticForm)
1457     return SyntacticForm->getSourceRange();
1458   SourceLocation Beg = LBraceLoc, End = RBraceLoc;
1459   if (Beg.isInvalid()) {
1460     // Find the first non-null initializer.
1461     for (InitExprsTy::const_iterator I = InitExprs.begin(),
1462                                      E = InitExprs.end();
1463       I != E; ++I) {
1464       if (Stmt *S = *I) {
1465         Beg = S->getLocStart();
1466         break;
1467       }
1468     }
1469   }
1470   if (End.isInvalid()) {
1471     // Find the first non-null initializer from the end.
1472     for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1473                                              E = InitExprs.rend();
1474       I != E; ++I) {
1475       if (Stmt *S = *I) {
1476         End = S->getSourceRange().getEnd();
1477         break;
1478       }
1479     }
1480   }
1481   return SourceRange(Beg, End);
1482 }
1483 
1484 /// getFunctionType - Return the underlying function type for this block.
1485 ///
1486 const FunctionType *BlockExpr::getFunctionType() const {
1487   return getType()->getAs<BlockPointerType>()->
1488                     getPointeeType()->getAs<FunctionType>();
1489 }
1490 
1491 SourceLocation BlockExpr::getCaretLocation() const {
1492   return TheBlock->getCaretLocation();
1493 }
1494 const Stmt *BlockExpr::getBody() const {
1495   return TheBlock->getBody();
1496 }
1497 Stmt *BlockExpr::getBody() {
1498   return TheBlock->getBody();
1499 }
1500 
1501 
1502 //===----------------------------------------------------------------------===//
1503 // Generic Expression Routines
1504 //===----------------------------------------------------------------------===//
1505 
1506 /// isUnusedResultAWarning - Return true if this immediate expression should
1507 /// be warned about if the result is unused.  If so, fill in Loc and Ranges
1508 /// with location to warn on and the source range[s] to report with the
1509 /// warning.
1510 bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
1511                                   SourceRange &R2, ASTContext &Ctx) const {
1512   // Don't warn if the expr is type dependent. The type could end up
1513   // instantiating to void.
1514   if (isTypeDependent())
1515     return false;
1516 
1517   switch (getStmtClass()) {
1518   default:
1519     if (getType()->isVoidType())
1520       return false;
1521     Loc = getExprLoc();
1522     R1 = getSourceRange();
1523     return true;
1524   case ParenExprClass:
1525     return cast<ParenExpr>(this)->getSubExpr()->
1526       isUnusedResultAWarning(Loc, R1, R2, Ctx);
1527   case GenericSelectionExprClass:
1528     return cast<GenericSelectionExpr>(this)->getResultExpr()->
1529       isUnusedResultAWarning(Loc, R1, R2, Ctx);
1530   case UnaryOperatorClass: {
1531     const UnaryOperator *UO = cast<UnaryOperator>(this);
1532 
1533     switch (UO->getOpcode()) {
1534     default: break;
1535     case UO_PostInc:
1536     case UO_PostDec:
1537     case UO_PreInc:
1538     case UO_PreDec:                 // ++/--
1539       return false;  // Not a warning.
1540     case UO_Deref:
1541       // Dereferencing a volatile pointer is a side-effect.
1542       if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1543         return false;
1544       break;
1545     case UO_Real:
1546     case UO_Imag:
1547       // accessing a piece of a volatile complex is a side-effect.
1548       if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1549           .isVolatileQualified())
1550         return false;
1551       break;
1552     case UO_Extension:
1553       return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1554     }
1555     Loc = UO->getOperatorLoc();
1556     R1 = UO->getSubExpr()->getSourceRange();
1557     return true;
1558   }
1559   case BinaryOperatorClass: {
1560     const BinaryOperator *BO = cast<BinaryOperator>(this);
1561     switch (BO->getOpcode()) {
1562       default:
1563         break;
1564       // Consider the RHS of comma for side effects. LHS was checked by
1565       // Sema::CheckCommaOperands.
1566       case BO_Comma:
1567         // ((foo = <blah>), 0) is an idiom for hiding the result (and
1568         // lvalue-ness) of an assignment written in a macro.
1569         if (IntegerLiteral *IE =
1570               dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1571           if (IE->getValue() == 0)
1572             return false;
1573         return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1574       // Consider '||', '&&' to have side effects if the LHS or RHS does.
1575       case BO_LAnd:
1576       case BO_LOr:
1577         if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) ||
1578             !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1579           return false;
1580         break;
1581     }
1582     if (BO->isAssignmentOp())
1583       return false;
1584     Loc = BO->getOperatorLoc();
1585     R1 = BO->getLHS()->getSourceRange();
1586     R2 = BO->getRHS()->getSourceRange();
1587     return true;
1588   }
1589   case CompoundAssignOperatorClass:
1590   case VAArgExprClass:
1591     return false;
1592 
1593   case ConditionalOperatorClass: {
1594     // If only one of the LHS or RHS is a warning, the operator might
1595     // be being used for control flow. Only warn if both the LHS and
1596     // RHS are warnings.
1597     const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
1598     if (!Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1599       return false;
1600     if (!Exp->getLHS())
1601       return true;
1602     return Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1603   }
1604 
1605   case MemberExprClass:
1606     // If the base pointer or element is to a volatile pointer/field, accessing
1607     // it is a side effect.
1608     if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1609       return false;
1610     Loc = cast<MemberExpr>(this)->getMemberLoc();
1611     R1 = SourceRange(Loc, Loc);
1612     R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
1613     return true;
1614 
1615   case ArraySubscriptExprClass:
1616     // If the base pointer or element is to a volatile pointer/field, accessing
1617     // it is a side effect.
1618     if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1619       return false;
1620     Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
1621     R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
1622     R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
1623     return true;
1624 
1625   case CXXOperatorCallExprClass: {
1626     // We warn about operator== and operator!= even when user-defined operator
1627     // overloads as there is no reasonable way to define these such that they
1628     // have non-trivial, desirable side-effects. See the -Wunused-comparison
1629     // warning: these operators are commonly typo'ed, and so warning on them
1630     // provides additional value as well. If this list is updated,
1631     // DiagnoseUnusedComparison should be as well.
1632     const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
1633     if (Op->getOperator() == OO_EqualEqual ||
1634         Op->getOperator() == OO_ExclaimEqual)
1635       return true;
1636 
1637     // Fallthrough for generic call handling.
1638   }
1639   case CallExprClass:
1640   case CXXMemberCallExprClass: {
1641     // If this is a direct call, get the callee.
1642     const CallExpr *CE = cast<CallExpr>(this);
1643     if (const Decl *FD = CE->getCalleeDecl()) {
1644       // If the callee has attribute pure, const, or warn_unused_result, warn
1645       // about it. void foo() { strlen("bar"); } should warn.
1646       //
1647       // Note: If new cases are added here, DiagnoseUnusedExprResult should be
1648       // updated to match for QoI.
1649       if (FD->getAttr<WarnUnusedResultAttr>() ||
1650           FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
1651         Loc = CE->getCallee()->getLocStart();
1652         R1 = CE->getCallee()->getSourceRange();
1653 
1654         if (unsigned NumArgs = CE->getNumArgs())
1655           R2 = SourceRange(CE->getArg(0)->getLocStart(),
1656                            CE->getArg(NumArgs-1)->getLocEnd());
1657         return true;
1658       }
1659     }
1660     return false;
1661   }
1662 
1663   case CXXTemporaryObjectExprClass:
1664   case CXXConstructExprClass:
1665     return false;
1666 
1667   case ObjCMessageExprClass: {
1668     const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
1669     if (Ctx.getLangOptions().ObjCAutoRefCount &&
1670         ME->isInstanceMessage() &&
1671         !ME->getType()->isVoidType() &&
1672         ME->getSelector().getIdentifierInfoForSlot(0) &&
1673         ME->getSelector().getIdentifierInfoForSlot(0)
1674                                                ->getName().startswith("init")) {
1675       Loc = getExprLoc();
1676       R1 = ME->getSourceRange();
1677       return true;
1678     }
1679 
1680     const ObjCMethodDecl *MD = ME->getMethodDecl();
1681     if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
1682       Loc = getExprLoc();
1683       return true;
1684     }
1685     return false;
1686   }
1687 
1688   case ObjCPropertyRefExprClass:
1689     Loc = getExprLoc();
1690     R1 = getSourceRange();
1691     return true;
1692 
1693   case StmtExprClass: {
1694     // Statement exprs don't logically have side effects themselves, but are
1695     // sometimes used in macros in ways that give them a type that is unused.
1696     // For example ({ blah; foo(); }) will end up with a type if foo has a type.
1697     // however, if the result of the stmt expr is dead, we don't want to emit a
1698     // warning.
1699     const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
1700     if (!CS->body_empty()) {
1701       if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
1702         return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1703       if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
1704         if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
1705           return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1706     }
1707 
1708     if (getType()->isVoidType())
1709       return false;
1710     Loc = cast<StmtExpr>(this)->getLParenLoc();
1711     R1 = getSourceRange();
1712     return true;
1713   }
1714   case CStyleCastExprClass:
1715     // If this is an explicit cast to void, allow it.  People do this when they
1716     // think they know what they're doing :).
1717     if (getType()->isVoidType())
1718       return false;
1719     Loc = cast<CStyleCastExpr>(this)->getLParenLoc();
1720     R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange();
1721     return true;
1722   case CXXFunctionalCastExprClass: {
1723     if (getType()->isVoidType())
1724       return false;
1725     const CastExpr *CE = cast<CastExpr>(this);
1726 
1727     // If this is a cast to void or a constructor conversion, check the operand.
1728     // Otherwise, the result of the cast is unused.
1729     if (CE->getCastKind() == CK_ToVoid ||
1730         CE->getCastKind() == CK_ConstructorConversion)
1731       return (cast<CastExpr>(this)->getSubExpr()
1732               ->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1733     Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc();
1734     R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange();
1735     return true;
1736   }
1737 
1738   case ImplicitCastExprClass:
1739     // Check the operand, since implicit casts are inserted by Sema
1740     return (cast<ImplicitCastExpr>(this)
1741             ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1742 
1743   case CXXDefaultArgExprClass:
1744     return (cast<CXXDefaultArgExpr>(this)
1745             ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1746 
1747   case CXXNewExprClass:
1748     // FIXME: In theory, there might be new expressions that don't have side
1749     // effects (e.g. a placement new with an uninitialized POD).
1750   case CXXDeleteExprClass:
1751     return false;
1752   case CXXBindTemporaryExprClass:
1753     return (cast<CXXBindTemporaryExpr>(this)
1754             ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1755   case ExprWithCleanupsClass:
1756     return (cast<ExprWithCleanups>(this)
1757             ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1758   }
1759 }
1760 
1761 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
1762 /// returns true, if it is; false otherwise.
1763 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
1764   const Expr *E = IgnoreParens();
1765   switch (E->getStmtClass()) {
1766   default:
1767     return false;
1768   case ObjCIvarRefExprClass:
1769     return true;
1770   case Expr::UnaryOperatorClass:
1771     return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1772   case ImplicitCastExprClass:
1773     return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1774   case MaterializeTemporaryExprClass:
1775     return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
1776                                                       ->isOBJCGCCandidate(Ctx);
1777   case CStyleCastExprClass:
1778     return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1779   case DeclRefExprClass: {
1780     const Decl *D = cast<DeclRefExpr>(E)->getDecl();
1781     if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1782       if (VD->hasGlobalStorage())
1783         return true;
1784       QualType T = VD->getType();
1785       // dereferencing to a  pointer is always a gc'able candidate,
1786       // unless it is __weak.
1787       return T->isPointerType() &&
1788              (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
1789     }
1790     return false;
1791   }
1792   case MemberExprClass: {
1793     const MemberExpr *M = cast<MemberExpr>(E);
1794     return M->getBase()->isOBJCGCCandidate(Ctx);
1795   }
1796   case ArraySubscriptExprClass:
1797     return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
1798   }
1799 }
1800 
1801 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
1802   if (isTypeDependent())
1803     return false;
1804   return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
1805 }
1806 
1807 QualType Expr::findBoundMemberType(const Expr *expr) {
1808   assert(expr->getType()->isSpecificPlaceholderType(BuiltinType::BoundMember));
1809 
1810   // Bound member expressions are always one of these possibilities:
1811   //   x->m      x.m      x->*y      x.*y
1812   // (possibly parenthesized)
1813 
1814   expr = expr->IgnoreParens();
1815   if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
1816     assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
1817     return mem->getMemberDecl()->getType();
1818   }
1819 
1820   if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
1821     QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
1822                       ->getPointeeType();
1823     assert(type->isFunctionType());
1824     return type;
1825   }
1826 
1827   assert(isa<UnresolvedMemberExpr>(expr));
1828   return QualType();
1829 }
1830 
1831 static Expr::CanThrowResult MergeCanThrow(Expr::CanThrowResult CT1,
1832                                           Expr::CanThrowResult CT2) {
1833   // CanThrowResult constants are ordered so that the maximum is the correct
1834   // merge result.
1835   return CT1 > CT2 ? CT1 : CT2;
1836 }
1837 
1838 static Expr::CanThrowResult CanSubExprsThrow(ASTContext &C, const Expr *CE) {
1839   Expr *E = const_cast<Expr*>(CE);
1840   Expr::CanThrowResult R = Expr::CT_Cannot;
1841   for (Expr::child_range I = E->children(); I && R != Expr::CT_Can; ++I) {
1842     R = MergeCanThrow(R, cast<Expr>(*I)->CanThrow(C));
1843   }
1844   return R;
1845 }
1846 
1847 static Expr::CanThrowResult CanCalleeThrow(ASTContext &Ctx, const Expr *E,
1848                                            const Decl *D,
1849                                            bool NullThrows = true) {
1850   if (!D)
1851     return NullThrows ? Expr::CT_Can : Expr::CT_Cannot;
1852 
1853   // See if we can get a function type from the decl somehow.
1854   const ValueDecl *VD = dyn_cast<ValueDecl>(D);
1855   if (!VD) // If we have no clue what we're calling, assume the worst.
1856     return Expr::CT_Can;
1857 
1858   // As an extension, we assume that __attribute__((nothrow)) functions don't
1859   // throw.
1860   if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
1861     return Expr::CT_Cannot;
1862 
1863   QualType T = VD->getType();
1864   const FunctionProtoType *FT;
1865   if ((FT = T->getAs<FunctionProtoType>())) {
1866   } else if (const PointerType *PT = T->getAs<PointerType>())
1867     FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1868   else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1869     FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1870   else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1871     FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1872   else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1873     FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1874 
1875   if (!FT)
1876     return Expr::CT_Can;
1877 
1878   if (FT->getExceptionSpecType() == EST_Delayed) {
1879     assert(isa<CXXConstructorDecl>(D) &&
1880            "only constructor exception specs can be unknown");
1881     Ctx.getDiagnostics().Report(E->getLocStart(),
1882                                 diag::err_exception_spec_unknown)
1883       << E->getSourceRange();
1884     return Expr::CT_Can;
1885   }
1886 
1887   return FT->isNothrow(Ctx) ? Expr::CT_Cannot : Expr::CT_Can;
1888 }
1889 
1890 static Expr::CanThrowResult CanDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1891   if (DC->isTypeDependent())
1892     return Expr::CT_Dependent;
1893 
1894   if (!DC->getTypeAsWritten()->isReferenceType())
1895     return Expr::CT_Cannot;
1896 
1897   if (DC->getSubExpr()->isTypeDependent())
1898     return Expr::CT_Dependent;
1899 
1900   return DC->getCastKind() == clang::CK_Dynamic? Expr::CT_Can : Expr::CT_Cannot;
1901 }
1902 
1903 static Expr::CanThrowResult CanTypeidThrow(ASTContext &C,
1904                                            const CXXTypeidExpr *DC) {
1905   if (DC->isTypeOperand())
1906     return Expr::CT_Cannot;
1907 
1908   Expr *Op = DC->getExprOperand();
1909   if (Op->isTypeDependent())
1910     return Expr::CT_Dependent;
1911 
1912   const RecordType *RT = Op->getType()->getAs<RecordType>();
1913   if (!RT)
1914     return Expr::CT_Cannot;
1915 
1916   if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1917     return Expr::CT_Cannot;
1918 
1919   if (Op->Classify(C).isPRValue())
1920     return Expr::CT_Cannot;
1921 
1922   return Expr::CT_Can;
1923 }
1924 
1925 Expr::CanThrowResult Expr::CanThrow(ASTContext &C) const {
1926   // C++ [expr.unary.noexcept]p3:
1927   //   [Can throw] if in a potentially-evaluated context the expression would
1928   //   contain:
1929   switch (getStmtClass()) {
1930   case CXXThrowExprClass:
1931     //   - a potentially evaluated throw-expression
1932     return CT_Can;
1933 
1934   case CXXDynamicCastExprClass: {
1935     //   - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1936     //     where T is a reference type, that requires a run-time check
1937     CanThrowResult CT = CanDynamicCastThrow(cast<CXXDynamicCastExpr>(this));
1938     if (CT == CT_Can)
1939       return CT;
1940     return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1941   }
1942 
1943   case CXXTypeidExprClass:
1944     //   - a potentially evaluated typeid expression applied to a glvalue
1945     //     expression whose type is a polymorphic class type
1946     return CanTypeidThrow(C, cast<CXXTypeidExpr>(this));
1947 
1948     //   - a potentially evaluated call to a function, member function, function
1949     //     pointer, or member function pointer that does not have a non-throwing
1950     //     exception-specification
1951   case CallExprClass:
1952   case CXXOperatorCallExprClass:
1953   case CXXMemberCallExprClass: {
1954     const CallExpr *CE = cast<CallExpr>(this);
1955     CanThrowResult CT;
1956     if (isTypeDependent())
1957       CT = CT_Dependent;
1958     else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
1959       CT = CT_Cannot;
1960     else
1961       CT = CanCalleeThrow(C, this, CE->getCalleeDecl());
1962     if (CT == CT_Can)
1963       return CT;
1964     return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1965   }
1966 
1967   case CXXConstructExprClass:
1968   case CXXTemporaryObjectExprClass: {
1969     CanThrowResult CT = CanCalleeThrow(C, this,
1970         cast<CXXConstructExpr>(this)->getConstructor());
1971     if (CT == CT_Can)
1972       return CT;
1973     return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1974   }
1975 
1976   case CXXNewExprClass: {
1977     CanThrowResult CT;
1978     if (isTypeDependent())
1979       CT = CT_Dependent;
1980     else
1981       CT = MergeCanThrow(
1982         CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getOperatorNew()),
1983         CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getConstructor(),
1984                        /*NullThrows*/false));
1985     if (CT == CT_Can)
1986       return CT;
1987     return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1988   }
1989 
1990   case CXXDeleteExprClass: {
1991     CanThrowResult CT;
1992     QualType DTy = cast<CXXDeleteExpr>(this)->getDestroyedType();
1993     if (DTy.isNull() || DTy->isDependentType()) {
1994       CT = CT_Dependent;
1995     } else {
1996       CT = CanCalleeThrow(C, this,
1997                           cast<CXXDeleteExpr>(this)->getOperatorDelete());
1998       if (const RecordType *RT = DTy->getAs<RecordType>()) {
1999         const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2000         CT = MergeCanThrow(CT, CanCalleeThrow(C, this, RD->getDestructor()));
2001       }
2002       if (CT == CT_Can)
2003         return CT;
2004     }
2005     return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2006   }
2007 
2008   case CXXBindTemporaryExprClass: {
2009     // The bound temporary has to be destroyed again, which might throw.
2010     CanThrowResult CT = CanCalleeThrow(C, this,
2011       cast<CXXBindTemporaryExpr>(this)->getTemporary()->getDestructor());
2012     if (CT == CT_Can)
2013       return CT;
2014     return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2015   }
2016 
2017     // ObjC message sends are like function calls, but never have exception
2018     // specs.
2019   case ObjCMessageExprClass:
2020   case ObjCPropertyRefExprClass:
2021     return CT_Can;
2022 
2023     // Many other things have subexpressions, so we have to test those.
2024     // Some are simple:
2025   case ParenExprClass:
2026   case MemberExprClass:
2027   case CXXReinterpretCastExprClass:
2028   case CXXConstCastExprClass:
2029   case ConditionalOperatorClass:
2030   case CompoundLiteralExprClass:
2031   case ExtVectorElementExprClass:
2032   case InitListExprClass:
2033   case DesignatedInitExprClass:
2034   case ParenListExprClass:
2035   case VAArgExprClass:
2036   case CXXDefaultArgExprClass:
2037   case ExprWithCleanupsClass:
2038   case ObjCIvarRefExprClass:
2039   case ObjCIsaExprClass:
2040   case ShuffleVectorExprClass:
2041     return CanSubExprsThrow(C, this);
2042 
2043     // Some might be dependent for other reasons.
2044   case UnaryOperatorClass:
2045   case ArraySubscriptExprClass:
2046   case ImplicitCastExprClass:
2047   case CStyleCastExprClass:
2048   case CXXStaticCastExprClass:
2049   case CXXFunctionalCastExprClass:
2050   case BinaryOperatorClass:
2051   case CompoundAssignOperatorClass:
2052   case MaterializeTemporaryExprClass: {
2053     CanThrowResult CT = isTypeDependent() ? CT_Dependent : CT_Cannot;
2054     return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2055   }
2056 
2057     // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
2058   case StmtExprClass:
2059     return CT_Can;
2060 
2061   case ChooseExprClass:
2062     if (isTypeDependent() || isValueDependent())
2063       return CT_Dependent;
2064     return cast<ChooseExpr>(this)->getChosenSubExpr(C)->CanThrow(C);
2065 
2066   case GenericSelectionExprClass:
2067     if (cast<GenericSelectionExpr>(this)->isResultDependent())
2068       return CT_Dependent;
2069     return cast<GenericSelectionExpr>(this)->getResultExpr()->CanThrow(C);
2070 
2071     // Some expressions are always dependent.
2072   case DependentScopeDeclRefExprClass:
2073   case CXXUnresolvedConstructExprClass:
2074   case CXXDependentScopeMemberExprClass:
2075     return CT_Dependent;
2076 
2077   default:
2078     // All other expressions don't have subexpressions, or else they are
2079     // unevaluated.
2080     return CT_Cannot;
2081   }
2082 }
2083 
2084 Expr* Expr::IgnoreParens() {
2085   Expr* E = this;
2086   while (true) {
2087     if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2088       E = P->getSubExpr();
2089       continue;
2090     }
2091     if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2092       if (P->getOpcode() == UO_Extension) {
2093         E = P->getSubExpr();
2094         continue;
2095       }
2096     }
2097     if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2098       if (!P->isResultDependent()) {
2099         E = P->getResultExpr();
2100         continue;
2101       }
2102     }
2103     return E;
2104   }
2105 }
2106 
2107 /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
2108 /// or CastExprs or ImplicitCastExprs, returning their operand.
2109 Expr *Expr::IgnoreParenCasts() {
2110   Expr *E = this;
2111   while (true) {
2112     if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2113       E = P->getSubExpr();
2114       continue;
2115     }
2116     if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2117       E = P->getSubExpr();
2118       continue;
2119     }
2120     if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2121       if (P->getOpcode() == UO_Extension) {
2122         E = P->getSubExpr();
2123         continue;
2124       }
2125     }
2126     if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2127       if (!P->isResultDependent()) {
2128         E = P->getResultExpr();
2129         continue;
2130       }
2131     }
2132     if (MaterializeTemporaryExpr *Materialize
2133                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
2134       E = Materialize->GetTemporaryExpr();
2135       continue;
2136     }
2137     if (SubstNonTypeTemplateParmExpr *NTTP
2138                                   = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2139       E = NTTP->getReplacement();
2140       continue;
2141     }
2142     return E;
2143   }
2144 }
2145 
2146 /// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2147 /// casts.  This is intended purely as a temporary workaround for code
2148 /// that hasn't yet been rewritten to do the right thing about those
2149 /// casts, and may disappear along with the last internal use.
2150 Expr *Expr::IgnoreParenLValueCasts() {
2151   Expr *E = this;
2152   while (true) {
2153     if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2154       E = P->getSubExpr();
2155       continue;
2156     } else if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2157       if (P->getCastKind() == CK_LValueToRValue) {
2158         E = P->getSubExpr();
2159         continue;
2160       }
2161     } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2162       if (P->getOpcode() == UO_Extension) {
2163         E = P->getSubExpr();
2164         continue;
2165       }
2166     } else if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2167       if (!P->isResultDependent()) {
2168         E = P->getResultExpr();
2169         continue;
2170       }
2171     } else if (MaterializeTemporaryExpr *Materialize
2172                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
2173       E = Materialize->GetTemporaryExpr();
2174       continue;
2175     } else if (SubstNonTypeTemplateParmExpr *NTTP
2176                                   = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2177       E = NTTP->getReplacement();
2178       continue;
2179     }
2180     break;
2181   }
2182   return E;
2183 }
2184 
2185 Expr *Expr::IgnoreParenImpCasts() {
2186   Expr *E = this;
2187   while (true) {
2188     if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2189       E = P->getSubExpr();
2190       continue;
2191     }
2192     if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
2193       E = P->getSubExpr();
2194       continue;
2195     }
2196     if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2197       if (P->getOpcode() == UO_Extension) {
2198         E = P->getSubExpr();
2199         continue;
2200       }
2201     }
2202     if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2203       if (!P->isResultDependent()) {
2204         E = P->getResultExpr();
2205         continue;
2206       }
2207     }
2208     if (MaterializeTemporaryExpr *Materialize
2209                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
2210       E = Materialize->GetTemporaryExpr();
2211       continue;
2212     }
2213     if (SubstNonTypeTemplateParmExpr *NTTP
2214                                   = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2215       E = NTTP->getReplacement();
2216       continue;
2217     }
2218     return E;
2219   }
2220 }
2221 
2222 Expr *Expr::IgnoreConversionOperator() {
2223   if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2224     if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2225       return MCE->getImplicitObjectArgument();
2226   }
2227   return this;
2228 }
2229 
2230 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2231 /// value (including ptr->int casts of the same size).  Strip off any
2232 /// ParenExpr or CastExprs, returning their operand.
2233 Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2234   Expr *E = this;
2235   while (true) {
2236     if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2237       E = P->getSubExpr();
2238       continue;
2239     }
2240 
2241     if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2242       // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2243       // ptr<->int casts of the same width.  We also ignore all identity casts.
2244       Expr *SE = P->getSubExpr();
2245 
2246       if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2247         E = SE;
2248         continue;
2249       }
2250 
2251       if ((E->getType()->isPointerType() ||
2252            E->getType()->isIntegralType(Ctx)) &&
2253           (SE->getType()->isPointerType() ||
2254            SE->getType()->isIntegralType(Ctx)) &&
2255           Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2256         E = SE;
2257         continue;
2258       }
2259     }
2260 
2261     if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2262       if (P->getOpcode() == UO_Extension) {
2263         E = P->getSubExpr();
2264         continue;
2265       }
2266     }
2267 
2268     if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2269       if (!P->isResultDependent()) {
2270         E = P->getResultExpr();
2271         continue;
2272       }
2273     }
2274 
2275     if (SubstNonTypeTemplateParmExpr *NTTP
2276                                   = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2277       E = NTTP->getReplacement();
2278       continue;
2279     }
2280 
2281     return E;
2282   }
2283 }
2284 
2285 bool Expr::isDefaultArgument() const {
2286   const Expr *E = this;
2287   if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2288     E = M->GetTemporaryExpr();
2289 
2290   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2291     E = ICE->getSubExprAsWritten();
2292 
2293   return isa<CXXDefaultArgExpr>(E);
2294 }
2295 
2296 /// \brief Skip over any no-op casts and any temporary-binding
2297 /// expressions.
2298 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
2299   if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2300     E = M->GetTemporaryExpr();
2301 
2302   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2303     if (ICE->getCastKind() == CK_NoOp)
2304       E = ICE->getSubExpr();
2305     else
2306       break;
2307   }
2308 
2309   while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2310     E = BE->getSubExpr();
2311 
2312   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2313     if (ICE->getCastKind() == CK_NoOp)
2314       E = ICE->getSubExpr();
2315     else
2316       break;
2317   }
2318 
2319   return E->IgnoreParens();
2320 }
2321 
2322 /// isTemporaryObject - Determines if this expression produces a
2323 /// temporary of the given class type.
2324 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2325   if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2326     return false;
2327 
2328   const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
2329 
2330   // Temporaries are by definition pr-values of class type.
2331   if (!E->Classify(C).isPRValue()) {
2332     // In this context, property reference is a message call and is pr-value.
2333     if (!isa<ObjCPropertyRefExpr>(E))
2334       return false;
2335   }
2336 
2337   // Black-list a few cases which yield pr-values of class type that don't
2338   // refer to temporaries of that type:
2339 
2340   // - implicit derived-to-base conversions
2341   if (isa<ImplicitCastExpr>(E)) {
2342     switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2343     case CK_DerivedToBase:
2344     case CK_UncheckedDerivedToBase:
2345       return false;
2346     default:
2347       break;
2348     }
2349   }
2350 
2351   // - member expressions (all)
2352   if (isa<MemberExpr>(E))
2353     return false;
2354 
2355   // - opaque values (all)
2356   if (isa<OpaqueValueExpr>(E))
2357     return false;
2358 
2359   return true;
2360 }
2361 
2362 bool Expr::isImplicitCXXThis() const {
2363   const Expr *E = this;
2364 
2365   // Strip away parentheses and casts we don't care about.
2366   while (true) {
2367     if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2368       E = Paren->getSubExpr();
2369       continue;
2370     }
2371 
2372     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2373       if (ICE->getCastKind() == CK_NoOp ||
2374           ICE->getCastKind() == CK_LValueToRValue ||
2375           ICE->getCastKind() == CK_DerivedToBase ||
2376           ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2377         E = ICE->getSubExpr();
2378         continue;
2379       }
2380     }
2381 
2382     if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2383       if (UnOp->getOpcode() == UO_Extension) {
2384         E = UnOp->getSubExpr();
2385         continue;
2386       }
2387     }
2388 
2389     if (const MaterializeTemporaryExpr *M
2390                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
2391       E = M->GetTemporaryExpr();
2392       continue;
2393     }
2394 
2395     break;
2396   }
2397 
2398   if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2399     return This->isImplicit();
2400 
2401   return false;
2402 }
2403 
2404 /// hasAnyTypeDependentArguments - Determines if any of the expressions
2405 /// in Exprs is type-dependent.
2406 bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) {
2407   for (unsigned I = 0; I < NumExprs; ++I)
2408     if (Exprs[I]->isTypeDependent())
2409       return true;
2410 
2411   return false;
2412 }
2413 
2414 /// hasAnyValueDependentArguments - Determines if any of the expressions
2415 /// in Exprs is value-dependent.
2416 bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) {
2417   for (unsigned I = 0; I < NumExprs; ++I)
2418     if (Exprs[I]->isValueDependent())
2419       return true;
2420 
2421   return false;
2422 }
2423 
2424 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
2425   // This function is attempting whether an expression is an initializer
2426   // which can be evaluated at compile-time.  isEvaluatable handles most
2427   // of the cases, but it can't deal with some initializer-specific
2428   // expressions, and it can't deal with aggregates; we deal with those here,
2429   // and fall back to isEvaluatable for the other cases.
2430 
2431   // If we ever capture reference-binding directly in the AST, we can
2432   // kill the second parameter.
2433 
2434   if (IsForRef) {
2435     EvalResult Result;
2436     return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects;
2437   }
2438 
2439   switch (getStmtClass()) {
2440   default: break;
2441   case StringLiteralClass:
2442   case ObjCStringLiteralClass:
2443   case ObjCEncodeExprClass:
2444     return true;
2445   case CXXTemporaryObjectExprClass:
2446   case CXXConstructExprClass: {
2447     const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2448 
2449     // Only if it's
2450     // 1) an application of the trivial default constructor or
2451     if (!CE->getConstructor()->isTrivial()) return false;
2452     if (!CE->getNumArgs()) return true;
2453 
2454     // 2) an elidable trivial copy construction of an operand which is
2455     //    itself a constant initializer.  Note that we consider the
2456     //    operand on its own, *not* as a reference binding.
2457     return CE->isElidable() &&
2458            CE->getArg(0)->isConstantInitializer(Ctx, false);
2459   }
2460   case CompoundLiteralExprClass: {
2461     // This handles gcc's extension that allows global initializers like
2462     // "struct x {int x;} x = (struct x) {};".
2463     // FIXME: This accepts other cases it shouldn't!
2464     const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
2465     return Exp->isConstantInitializer(Ctx, false);
2466   }
2467   case InitListExprClass: {
2468     // FIXME: This doesn't deal with fields with reference types correctly.
2469     // FIXME: This incorrectly allows pointers cast to integers to be assigned
2470     // to bitfields.
2471     const InitListExpr *Exp = cast<InitListExpr>(this);
2472     unsigned numInits = Exp->getNumInits();
2473     for (unsigned i = 0; i < numInits; i++) {
2474       if (!Exp->getInit(i)->isConstantInitializer(Ctx, false))
2475         return false;
2476     }
2477     return true;
2478   }
2479   case ImplicitValueInitExprClass:
2480     return true;
2481   case ParenExprClass:
2482     return cast<ParenExpr>(this)->getSubExpr()
2483       ->isConstantInitializer(Ctx, IsForRef);
2484   case GenericSelectionExprClass:
2485     if (cast<GenericSelectionExpr>(this)->isResultDependent())
2486       return false;
2487     return cast<GenericSelectionExpr>(this)->getResultExpr()
2488       ->isConstantInitializer(Ctx, IsForRef);
2489   case ChooseExprClass:
2490     return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)
2491       ->isConstantInitializer(Ctx, IsForRef);
2492   case UnaryOperatorClass: {
2493     const UnaryOperator* Exp = cast<UnaryOperator>(this);
2494     if (Exp->getOpcode() == UO_Extension)
2495       return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
2496     break;
2497   }
2498   case BinaryOperatorClass: {
2499     // Special case &&foo - &&bar.  It would be nice to generalize this somehow
2500     // but this handles the common case.
2501     const BinaryOperator *Exp = cast<BinaryOperator>(this);
2502     if (Exp->getOpcode() == BO_Sub &&
2503         isa<AddrLabelExpr>(Exp->getLHS()->IgnoreParenNoopCasts(Ctx)) &&
2504         isa<AddrLabelExpr>(Exp->getRHS()->IgnoreParenNoopCasts(Ctx)))
2505       return true;
2506     break;
2507   }
2508   case CXXFunctionalCastExprClass:
2509   case CXXStaticCastExprClass:
2510   case ImplicitCastExprClass:
2511   case CStyleCastExprClass:
2512     // Handle casts with a destination that's a struct or union; this
2513     // deals with both the gcc no-op struct cast extension and the
2514     // cast-to-union extension.
2515     if (getType()->isRecordType())
2516       return cast<CastExpr>(this)->getSubExpr()
2517         ->isConstantInitializer(Ctx, false);
2518 
2519     // Integer->integer casts can be handled here, which is important for
2520     // things like (int)(&&x-&&y).  Scary but true.
2521     if (getType()->isIntegerType() &&
2522         cast<CastExpr>(this)->getSubExpr()->getType()->isIntegerType())
2523       return cast<CastExpr>(this)->getSubExpr()
2524         ->isConstantInitializer(Ctx, false);
2525 
2526     break;
2527 
2528   case MaterializeTemporaryExprClass:
2529     return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2530                                             ->isConstantInitializer(Ctx, false);
2531   }
2532   return isEvaluatable(Ctx);
2533 }
2534 
2535 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
2536 /// pointer constant or not, as well as the specific kind of constant detected.
2537 /// Null pointer constants can be integer constant expressions with the
2538 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
2539 /// (a GNU extension).
2540 Expr::NullPointerConstantKind
2541 Expr::isNullPointerConstant(ASTContext &Ctx,
2542                             NullPointerConstantValueDependence NPC) const {
2543   if (isValueDependent()) {
2544     switch (NPC) {
2545     case NPC_NeverValueDependent:
2546       assert(false && "Unexpected value dependent expression!");
2547       // If the unthinkable happens, fall through to the safest alternative.
2548 
2549     case NPC_ValueDependentIsNull:
2550       if (isTypeDependent() || getType()->isIntegralType(Ctx))
2551         return NPCK_ZeroInteger;
2552       else
2553         return NPCK_NotNull;
2554 
2555     case NPC_ValueDependentIsNotNull:
2556       return NPCK_NotNull;
2557     }
2558   }
2559 
2560   // Strip off a cast to void*, if it exists. Except in C++.
2561   if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
2562     if (!Ctx.getLangOptions().CPlusPlus) {
2563       // Check that it is a cast to void*.
2564       if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
2565         QualType Pointee = PT->getPointeeType();
2566         if (!Pointee.hasQualifiers() &&
2567             Pointee->isVoidType() &&                              // to void*
2568             CE->getSubExpr()->getType()->isIntegerType())         // from int.
2569           return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2570       }
2571     }
2572   } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
2573     // Ignore the ImplicitCastExpr type entirely.
2574     return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2575   } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
2576     // Accept ((void*)0) as a null pointer constant, as many other
2577     // implementations do.
2578     return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2579   } else if (const GenericSelectionExpr *GE =
2580                dyn_cast<GenericSelectionExpr>(this)) {
2581     return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
2582   } else if (const CXXDefaultArgExpr *DefaultArg
2583                = dyn_cast<CXXDefaultArgExpr>(this)) {
2584     // See through default argument expressions
2585     return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
2586   } else if (isa<GNUNullExpr>(this)) {
2587     // The GNU __null extension is always a null pointer constant.
2588     return NPCK_GNUNull;
2589   } else if (const MaterializeTemporaryExpr *M
2590                                    = dyn_cast<MaterializeTemporaryExpr>(this)) {
2591     return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
2592   }
2593 
2594   // C++0x nullptr_t is always a null pointer constant.
2595   if (getType()->isNullPtrType())
2596     return NPCK_CXX0X_nullptr;
2597 
2598   if (const RecordType *UT = getType()->getAsUnionType())
2599     if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
2600       if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
2601         const Expr *InitExpr = CLE->getInitializer();
2602         if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
2603           return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
2604       }
2605   // This expression must be an integer type.
2606   if (!getType()->isIntegerType() ||
2607       (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType()))
2608     return NPCK_NotNull;
2609 
2610   // If we have an integer constant expression, we need to *evaluate* it and
2611   // test for the value 0.
2612   llvm::APSInt Result;
2613   bool IsNull = isIntegerConstantExpr(Result, Ctx) && Result == 0;
2614 
2615   return (IsNull ? NPCK_ZeroInteger : NPCK_NotNull);
2616 }
2617 
2618 /// \brief If this expression is an l-value for an Objective C
2619 /// property, find the underlying property reference expression.
2620 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
2621   const Expr *E = this;
2622   while (true) {
2623     assert((E->getValueKind() == VK_LValue &&
2624             E->getObjectKind() == OK_ObjCProperty) &&
2625            "expression is not a property reference");
2626     E = E->IgnoreParenCasts();
2627     if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2628       if (BO->getOpcode() == BO_Comma) {
2629         E = BO->getRHS();
2630         continue;
2631       }
2632     }
2633 
2634     break;
2635   }
2636 
2637   return cast<ObjCPropertyRefExpr>(E);
2638 }
2639 
2640 FieldDecl *Expr::getBitField() {
2641   Expr *E = this->IgnoreParens();
2642 
2643   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2644     if (ICE->getCastKind() == CK_LValueToRValue ||
2645         (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
2646       E = ICE->getSubExpr()->IgnoreParens();
2647     else
2648       break;
2649   }
2650 
2651   if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
2652     if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
2653       if (Field->isBitField())
2654         return Field;
2655 
2656   if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
2657     if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
2658       if (Field->isBitField())
2659         return Field;
2660 
2661   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
2662     if (BinOp->isAssignmentOp() && BinOp->getLHS())
2663       return BinOp->getLHS()->getBitField();
2664 
2665     if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
2666       return BinOp->getRHS()->getBitField();
2667   }
2668 
2669   return 0;
2670 }
2671 
2672 bool Expr::refersToVectorElement() const {
2673   const Expr *E = this->IgnoreParens();
2674 
2675   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2676     if (ICE->getValueKind() != VK_RValue &&
2677         ICE->getCastKind() == CK_NoOp)
2678       E = ICE->getSubExpr()->IgnoreParens();
2679     else
2680       break;
2681   }
2682 
2683   if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
2684     return ASE->getBase()->getType()->isVectorType();
2685 
2686   if (isa<ExtVectorElementExpr>(E))
2687     return true;
2688 
2689   return false;
2690 }
2691 
2692 /// isArrow - Return true if the base expression is a pointer to vector,
2693 /// return false if the base expression is a vector.
2694 bool ExtVectorElementExpr::isArrow() const {
2695   return getBase()->getType()->isPointerType();
2696 }
2697 
2698 unsigned ExtVectorElementExpr::getNumElements() const {
2699   if (const VectorType *VT = getType()->getAs<VectorType>())
2700     return VT->getNumElements();
2701   return 1;
2702 }
2703 
2704 /// containsDuplicateElements - Return true if any element access is repeated.
2705 bool ExtVectorElementExpr::containsDuplicateElements() const {
2706   // FIXME: Refactor this code to an accessor on the AST node which returns the
2707   // "type" of component access, and share with code below and in Sema.
2708   StringRef Comp = Accessor->getName();
2709 
2710   // Halving swizzles do not contain duplicate elements.
2711   if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
2712     return false;
2713 
2714   // Advance past s-char prefix on hex swizzles.
2715   if (Comp[0] == 's' || Comp[0] == 'S')
2716     Comp = Comp.substr(1);
2717 
2718   for (unsigned i = 0, e = Comp.size(); i != e; ++i)
2719     if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
2720         return true;
2721 
2722   return false;
2723 }
2724 
2725 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
2726 void ExtVectorElementExpr::getEncodedElementAccess(
2727                                   SmallVectorImpl<unsigned> &Elts) const {
2728   StringRef Comp = Accessor->getName();
2729   if (Comp[0] == 's' || Comp[0] == 'S')
2730     Comp = Comp.substr(1);
2731 
2732   bool isHi =   Comp == "hi";
2733   bool isLo =   Comp == "lo";
2734   bool isEven = Comp == "even";
2735   bool isOdd  = Comp == "odd";
2736 
2737   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2738     uint64_t Index;
2739 
2740     if (isHi)
2741       Index = e + i;
2742     else if (isLo)
2743       Index = i;
2744     else if (isEven)
2745       Index = 2 * i;
2746     else if (isOdd)
2747       Index = 2 * i + 1;
2748     else
2749       Index = ExtVectorType::getAccessorIdx(Comp[i]);
2750 
2751     Elts.push_back(Index);
2752   }
2753 }
2754 
2755 ObjCMessageExpr::ObjCMessageExpr(QualType T,
2756                                  ExprValueKind VK,
2757                                  SourceLocation LBracLoc,
2758                                  SourceLocation SuperLoc,
2759                                  bool IsInstanceSuper,
2760                                  QualType SuperType,
2761                                  Selector Sel,
2762                                  SourceLocation SelLoc,
2763                                  ObjCMethodDecl *Method,
2764                                  Expr **Args, unsigned NumArgs,
2765                                  SourceLocation RBracLoc)
2766   : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
2767          /*TypeDependent=*/false, /*ValueDependent=*/false,
2768          /*InstantiationDependent=*/false,
2769          /*ContainsUnexpandedParameterPack=*/false),
2770     NumArgs(NumArgs), Kind(IsInstanceSuper? SuperInstance : SuperClass),
2771     HasMethod(Method != 0), IsDelegateInitCall(false), SuperLoc(SuperLoc),
2772     SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2773                                                        : Sel.getAsOpaquePtr())),
2774     SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2775 {
2776   setReceiverPointer(SuperType.getAsOpaquePtr());
2777   if (NumArgs)
2778     memcpy(getArgs(), Args, NumArgs * sizeof(Expr *));
2779 }
2780 
2781 ObjCMessageExpr::ObjCMessageExpr(QualType T,
2782                                  ExprValueKind VK,
2783                                  SourceLocation LBracLoc,
2784                                  TypeSourceInfo *Receiver,
2785                                  Selector Sel,
2786                                  SourceLocation SelLoc,
2787                                  ObjCMethodDecl *Method,
2788                                  Expr **Args, unsigned NumArgs,
2789                                  SourceLocation RBracLoc)
2790   : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
2791          T->isDependentType(), T->isInstantiationDependentType(),
2792          T->containsUnexpandedParameterPack()),
2793     NumArgs(NumArgs), Kind(Class),
2794     HasMethod(Method != 0), IsDelegateInitCall(false),
2795     SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2796                                                        : Sel.getAsOpaquePtr())),
2797     SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2798 {
2799   setReceiverPointer(Receiver);
2800   Expr **MyArgs = getArgs();
2801   for (unsigned I = 0; I != NumArgs; ++I) {
2802     if (Args[I]->isTypeDependent())
2803       ExprBits.TypeDependent = true;
2804     if (Args[I]->isValueDependent())
2805       ExprBits.ValueDependent = true;
2806     if (Args[I]->isInstantiationDependent())
2807       ExprBits.InstantiationDependent = true;
2808     if (Args[I]->containsUnexpandedParameterPack())
2809       ExprBits.ContainsUnexpandedParameterPack = true;
2810 
2811     MyArgs[I] = Args[I];
2812   }
2813 }
2814 
2815 ObjCMessageExpr::ObjCMessageExpr(QualType T,
2816                                  ExprValueKind VK,
2817                                  SourceLocation LBracLoc,
2818                                  Expr *Receiver,
2819                                  Selector Sel,
2820                                  SourceLocation SelLoc,
2821                                  ObjCMethodDecl *Method,
2822                                  Expr **Args, unsigned NumArgs,
2823                                  SourceLocation RBracLoc)
2824   : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(),
2825          Receiver->isTypeDependent(),
2826          Receiver->isInstantiationDependent(),
2827          Receiver->containsUnexpandedParameterPack()),
2828     NumArgs(NumArgs), Kind(Instance),
2829     HasMethod(Method != 0), IsDelegateInitCall(false),
2830     SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2831                                                        : Sel.getAsOpaquePtr())),
2832     SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2833 {
2834   setReceiverPointer(Receiver);
2835   Expr **MyArgs = getArgs();
2836   for (unsigned I = 0; I != NumArgs; ++I) {
2837     if (Args[I]->isTypeDependent())
2838       ExprBits.TypeDependent = true;
2839     if (Args[I]->isValueDependent())
2840       ExprBits.ValueDependent = true;
2841     if (Args[I]->isInstantiationDependent())
2842       ExprBits.InstantiationDependent = true;
2843     if (Args[I]->containsUnexpandedParameterPack())
2844       ExprBits.ContainsUnexpandedParameterPack = true;
2845 
2846     MyArgs[I] = Args[I];
2847   }
2848 }
2849 
2850 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2851                                          ExprValueKind VK,
2852                                          SourceLocation LBracLoc,
2853                                          SourceLocation SuperLoc,
2854                                          bool IsInstanceSuper,
2855                                          QualType SuperType,
2856                                          Selector Sel,
2857                                          SourceLocation SelLoc,
2858                                          ObjCMethodDecl *Method,
2859                                          Expr **Args, unsigned NumArgs,
2860                                          SourceLocation RBracLoc) {
2861   unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2862     NumArgs * sizeof(Expr *);
2863   void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2864   return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper,
2865                                    SuperType, Sel, SelLoc, Method, Args,NumArgs,
2866                                    RBracLoc);
2867 }
2868 
2869 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2870                                          ExprValueKind VK,
2871                                          SourceLocation LBracLoc,
2872                                          TypeSourceInfo *Receiver,
2873                                          Selector Sel,
2874                                          SourceLocation SelLoc,
2875                                          ObjCMethodDecl *Method,
2876                                          Expr **Args, unsigned NumArgs,
2877                                          SourceLocation RBracLoc) {
2878   unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2879     NumArgs * sizeof(Expr *);
2880   void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2881   return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, SelLoc,
2882                                    Method, Args, NumArgs, RBracLoc);
2883 }
2884 
2885 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2886                                          ExprValueKind VK,
2887                                          SourceLocation LBracLoc,
2888                                          Expr *Receiver,
2889                                          Selector Sel,
2890                                          SourceLocation SelLoc,
2891                                          ObjCMethodDecl *Method,
2892                                          Expr **Args, unsigned NumArgs,
2893                                          SourceLocation RBracLoc) {
2894   unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2895     NumArgs * sizeof(Expr *);
2896   void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2897   return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, SelLoc,
2898                                    Method, Args, NumArgs, RBracLoc);
2899 }
2900 
2901 ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,
2902                                               unsigned NumArgs) {
2903   unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2904     NumArgs * sizeof(Expr *);
2905   void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2906   return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
2907 }
2908 
2909 SourceRange ObjCMessageExpr::getReceiverRange() const {
2910   switch (getReceiverKind()) {
2911   case Instance:
2912     return getInstanceReceiver()->getSourceRange();
2913 
2914   case Class:
2915     return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange();
2916 
2917   case SuperInstance:
2918   case SuperClass:
2919     return getSuperLoc();
2920   }
2921 
2922   return SourceLocation();
2923 }
2924 
2925 Selector ObjCMessageExpr::getSelector() const {
2926   if (HasMethod)
2927     return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
2928                                                                ->getSelector();
2929   return Selector(SelectorOrMethod);
2930 }
2931 
2932 ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
2933   switch (getReceiverKind()) {
2934   case Instance:
2935     if (const ObjCObjectPointerType *Ptr
2936           = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>())
2937       return Ptr->getInterfaceDecl();
2938     break;
2939 
2940   case Class:
2941     if (const ObjCObjectType *Ty
2942           = getClassReceiver()->getAs<ObjCObjectType>())
2943       return Ty->getInterface();
2944     break;
2945 
2946   case SuperInstance:
2947     if (const ObjCObjectPointerType *Ptr
2948           = getSuperType()->getAs<ObjCObjectPointerType>())
2949       return Ptr->getInterfaceDecl();
2950     break;
2951 
2952   case SuperClass:
2953     if (const ObjCObjectType *Iface
2954           = getSuperType()->getAs<ObjCObjectType>())
2955       return Iface->getInterface();
2956     break;
2957   }
2958 
2959   return 0;
2960 }
2961 
2962 StringRef ObjCBridgedCastExpr::getBridgeKindName() const {
2963   switch (getBridgeKind()) {
2964   case OBC_Bridge:
2965     return "__bridge";
2966   case OBC_BridgeTransfer:
2967     return "__bridge_transfer";
2968   case OBC_BridgeRetained:
2969     return "__bridge_retained";
2970   }
2971 
2972   return "__bridge";
2973 }
2974 
2975 bool ChooseExpr::isConditionTrue(const ASTContext &C) const {
2976   return getCond()->EvaluateAsInt(C) != 0;
2977 }
2978 
2979 ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2980                                      QualType Type, SourceLocation BLoc,
2981                                      SourceLocation RP)
2982    : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
2983           Type->isDependentType(), Type->isDependentType(),
2984           Type->isInstantiationDependentType(),
2985           Type->containsUnexpandedParameterPack()),
2986      BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr)
2987 {
2988   SubExprs = new (C) Stmt*[nexpr];
2989   for (unsigned i = 0; i < nexpr; i++) {
2990     if (args[i]->isTypeDependent())
2991       ExprBits.TypeDependent = true;
2992     if (args[i]->isValueDependent())
2993       ExprBits.ValueDependent = true;
2994     if (args[i]->isInstantiationDependent())
2995       ExprBits.InstantiationDependent = true;
2996     if (args[i]->containsUnexpandedParameterPack())
2997       ExprBits.ContainsUnexpandedParameterPack = true;
2998 
2999     SubExprs[i] = args[i];
3000   }
3001 }
3002 
3003 void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
3004                                  unsigned NumExprs) {
3005   if (SubExprs) C.Deallocate(SubExprs);
3006 
3007   SubExprs = new (C) Stmt* [NumExprs];
3008   this->NumExprs = NumExprs;
3009   memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
3010 }
3011 
3012 GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
3013                                SourceLocation GenericLoc, Expr *ControllingExpr,
3014                                TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3015                                unsigned NumAssocs, SourceLocation DefaultLoc,
3016                                SourceLocation RParenLoc,
3017                                bool ContainsUnexpandedParameterPack,
3018                                unsigned ResultIndex)
3019   : Expr(GenericSelectionExprClass,
3020          AssocExprs[ResultIndex]->getType(),
3021          AssocExprs[ResultIndex]->getValueKind(),
3022          AssocExprs[ResultIndex]->getObjectKind(),
3023          AssocExprs[ResultIndex]->isTypeDependent(),
3024          AssocExprs[ResultIndex]->isValueDependent(),
3025          AssocExprs[ResultIndex]->isInstantiationDependent(),
3026          ContainsUnexpandedParameterPack),
3027     AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]),
3028     SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs),
3029     ResultIndex(ResultIndex), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc),
3030     RParenLoc(RParenLoc) {
3031   SubExprs[CONTROLLING] = ControllingExpr;
3032   std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes);
3033   std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR);
3034 }
3035 
3036 GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
3037                                SourceLocation GenericLoc, Expr *ControllingExpr,
3038                                TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3039                                unsigned NumAssocs, SourceLocation DefaultLoc,
3040                                SourceLocation RParenLoc,
3041                                bool ContainsUnexpandedParameterPack)
3042   : Expr(GenericSelectionExprClass,
3043          Context.DependentTy,
3044          VK_RValue,
3045          OK_Ordinary,
3046          /*isTypeDependent=*/true,
3047          /*isValueDependent=*/true,
3048          /*isInstantiationDependent=*/true,
3049          ContainsUnexpandedParameterPack),
3050     AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]),
3051     SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs),
3052     ResultIndex(-1U), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc),
3053     RParenLoc(RParenLoc) {
3054   SubExprs[CONTROLLING] = ControllingExpr;
3055   std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes);
3056   std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR);
3057 }
3058 
3059 //===----------------------------------------------------------------------===//
3060 //  DesignatedInitExpr
3061 //===----------------------------------------------------------------------===//
3062 
3063 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
3064   assert(Kind == FieldDesignator && "Only valid on a field designator");
3065   if (Field.NameOrField & 0x01)
3066     return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3067   else
3068     return getField()->getIdentifier();
3069 }
3070 
3071 DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty,
3072                                        unsigned NumDesignators,
3073                                        const Designator *Designators,
3074                                        SourceLocation EqualOrColonLoc,
3075                                        bool GNUSyntax,
3076                                        Expr **IndexExprs,
3077                                        unsigned NumIndexExprs,
3078                                        Expr *Init)
3079   : Expr(DesignatedInitExprClass, Ty,
3080          Init->getValueKind(), Init->getObjectKind(),
3081          Init->isTypeDependent(), Init->isValueDependent(),
3082          Init->isInstantiationDependent(),
3083          Init->containsUnexpandedParameterPack()),
3084     EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
3085     NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) {
3086   this->Designators = new (C) Designator[NumDesignators];
3087 
3088   // Record the initializer itself.
3089   child_range Child = children();
3090   *Child++ = Init;
3091 
3092   // Copy the designators and their subexpressions, computing
3093   // value-dependence along the way.
3094   unsigned IndexIdx = 0;
3095   for (unsigned I = 0; I != NumDesignators; ++I) {
3096     this->Designators[I] = Designators[I];
3097 
3098     if (this->Designators[I].isArrayDesignator()) {
3099       // Compute type- and value-dependence.
3100       Expr *Index = IndexExprs[IndexIdx];
3101       if (Index->isTypeDependent() || Index->isValueDependent())
3102         ExprBits.ValueDependent = true;
3103       if (Index->isInstantiationDependent())
3104         ExprBits.InstantiationDependent = true;
3105       // Propagate unexpanded parameter packs.
3106       if (Index->containsUnexpandedParameterPack())
3107         ExprBits.ContainsUnexpandedParameterPack = true;
3108 
3109       // Copy the index expressions into permanent storage.
3110       *Child++ = IndexExprs[IndexIdx++];
3111     } else if (this->Designators[I].isArrayRangeDesignator()) {
3112       // Compute type- and value-dependence.
3113       Expr *Start = IndexExprs[IndexIdx];
3114       Expr *End = IndexExprs[IndexIdx + 1];
3115       if (Start->isTypeDependent() || Start->isValueDependent() ||
3116           End->isTypeDependent() || End->isValueDependent()) {
3117         ExprBits.ValueDependent = true;
3118         ExprBits.InstantiationDependent = true;
3119       } else if (Start->isInstantiationDependent() ||
3120                  End->isInstantiationDependent()) {
3121         ExprBits.InstantiationDependent = true;
3122       }
3123 
3124       // Propagate unexpanded parameter packs.
3125       if (Start->containsUnexpandedParameterPack() ||
3126           End->containsUnexpandedParameterPack())
3127         ExprBits.ContainsUnexpandedParameterPack = true;
3128 
3129       // Copy the start/end expressions into permanent storage.
3130       *Child++ = IndexExprs[IndexIdx++];
3131       *Child++ = IndexExprs[IndexIdx++];
3132     }
3133   }
3134 
3135   assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions");
3136 }
3137 
3138 DesignatedInitExpr *
3139 DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
3140                            unsigned NumDesignators,
3141                            Expr **IndexExprs, unsigned NumIndexExprs,
3142                            SourceLocation ColonOrEqualLoc,
3143                            bool UsesColonSyntax, Expr *Init) {
3144   void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3145                          sizeof(Stmt *) * (NumIndexExprs + 1), 8);
3146   return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
3147                                       ColonOrEqualLoc, UsesColonSyntax,
3148                                       IndexExprs, NumIndexExprs, Init);
3149 }
3150 
3151 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
3152                                                     unsigned NumIndexExprs) {
3153   void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3154                          sizeof(Stmt *) * (NumIndexExprs + 1), 8);
3155   return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3156 }
3157 
3158 void DesignatedInitExpr::setDesignators(ASTContext &C,
3159                                         const Designator *Desigs,
3160                                         unsigned NumDesigs) {
3161   Designators = new (C) Designator[NumDesigs];
3162   NumDesignators = NumDesigs;
3163   for (unsigned I = 0; I != NumDesigs; ++I)
3164     Designators[I] = Desigs[I];
3165 }
3166 
3167 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3168   DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3169   if (size() == 1)
3170     return DIE->getDesignator(0)->getSourceRange();
3171   return SourceRange(DIE->getDesignator(0)->getStartLocation(),
3172                      DIE->getDesignator(size()-1)->getEndLocation());
3173 }
3174 
3175 SourceRange DesignatedInitExpr::getSourceRange() const {
3176   SourceLocation StartLoc;
3177   Designator &First =
3178     *const_cast<DesignatedInitExpr*>(this)->designators_begin();
3179   if (First.isFieldDesignator()) {
3180     if (GNUSyntax)
3181       StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3182     else
3183       StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3184   } else
3185     StartLoc =
3186       SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
3187   return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
3188 }
3189 
3190 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
3191   assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
3192   char* Ptr = static_cast<char*>(static_cast<void *>(this));
3193   Ptr += sizeof(DesignatedInitExpr);
3194   Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3195   return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3196 }
3197 
3198 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
3199   assert(D.Kind == Designator::ArrayRangeDesignator &&
3200          "Requires array range designator");
3201   char* Ptr = static_cast<char*>(static_cast<void *>(this));
3202   Ptr += sizeof(DesignatedInitExpr);
3203   Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3204   return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3205 }
3206 
3207 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
3208   assert(D.Kind == Designator::ArrayRangeDesignator &&
3209          "Requires array range designator");
3210   char* Ptr = static_cast<char*>(static_cast<void *>(this));
3211   Ptr += sizeof(DesignatedInitExpr);
3212   Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3213   return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
3214 }
3215 
3216 /// \brief Replaces the designator at index @p Idx with the series
3217 /// of designators in [First, Last).
3218 void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx,
3219                                           const Designator *First,
3220                                           const Designator *Last) {
3221   unsigned NumNewDesignators = Last - First;
3222   if (NumNewDesignators == 0) {
3223     std::copy_backward(Designators + Idx + 1,
3224                        Designators + NumDesignators,
3225                        Designators + Idx);
3226     --NumNewDesignators;
3227     return;
3228   } else if (NumNewDesignators == 1) {
3229     Designators[Idx] = *First;
3230     return;
3231   }
3232 
3233   Designator *NewDesignators
3234     = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
3235   std::copy(Designators, Designators + Idx, NewDesignators);
3236   std::copy(First, Last, NewDesignators + Idx);
3237   std::copy(Designators + Idx + 1, Designators + NumDesignators,
3238             NewDesignators + Idx + NumNewDesignators);
3239   Designators = NewDesignators;
3240   NumDesignators = NumDesignators - 1 + NumNewDesignators;
3241 }
3242 
3243 ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
3244                              Expr **exprs, unsigned nexprs,
3245                              SourceLocation rparenloc, QualType T)
3246   : Expr(ParenListExprClass, T, VK_RValue, OK_Ordinary,
3247          false, false, false, false),
3248     NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3249   assert(!T.isNull() && "ParenListExpr must have a valid type");
3250   Exprs = new (C) Stmt*[nexprs];
3251   for (unsigned i = 0; i != nexprs; ++i) {
3252     if (exprs[i]->isTypeDependent())
3253       ExprBits.TypeDependent = true;
3254     if (exprs[i]->isValueDependent())
3255       ExprBits.ValueDependent = true;
3256     if (exprs[i]->isInstantiationDependent())
3257       ExprBits.InstantiationDependent = true;
3258     if (exprs[i]->containsUnexpandedParameterPack())
3259       ExprBits.ContainsUnexpandedParameterPack = true;
3260 
3261     Exprs[i] = exprs[i];
3262   }
3263 }
3264 
3265 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3266   if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3267     e = ewc->getSubExpr();
3268   if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3269     e = m->GetTemporaryExpr();
3270   e = cast<CXXConstructExpr>(e)->getArg(0);
3271   while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3272     e = ice->getSubExpr();
3273   return cast<OpaqueValueExpr>(e);
3274 }
3275 
3276 //===----------------------------------------------------------------------===//
3277 //  ExprIterator.
3278 //===----------------------------------------------------------------------===//
3279 
3280 Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
3281 Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
3282 Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
3283 const Expr* ConstExprIterator::operator[](size_t idx) const {
3284   return cast<Expr>(I[idx]);
3285 }
3286 const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
3287 const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
3288 
3289 //===----------------------------------------------------------------------===//
3290 //  Child Iterators for iterating over subexpressions/substatements
3291 //===----------------------------------------------------------------------===//
3292 
3293 // UnaryExprOrTypeTraitExpr
3294 Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
3295   // If this is of a type and the type is a VLA type (and not a typedef), the
3296   // size expression of the VLA needs to be treated as an executable expression.
3297   // Why isn't this weirdness documented better in StmtIterator?
3298   if (isArgumentType()) {
3299     if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
3300                                    getArgumentType().getTypePtr()))
3301       return child_range(child_iterator(T), child_iterator());
3302     return child_range();
3303   }
3304   return child_range(&Argument.Ex, &Argument.Ex + 1);
3305 }
3306 
3307 // ObjCMessageExpr
3308 Stmt::child_range ObjCMessageExpr::children() {
3309   Stmt **begin;
3310   if (getReceiverKind() == Instance)
3311     begin = reinterpret_cast<Stmt **>(this + 1);
3312   else
3313     begin = reinterpret_cast<Stmt **>(getArgs());
3314   return child_range(begin,
3315                      reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
3316 }
3317 
3318 // Blocks
3319 BlockDeclRefExpr::BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
3320                                    SourceLocation l, bool ByRef,
3321                                    bool constAdded)
3322   : Expr(BlockDeclRefExprClass, t, VK, OK_Ordinary, false, false, false,
3323          d->isParameterPack()),
3324     D(d), Loc(l), IsByRef(ByRef), ConstQualAdded(constAdded)
3325 {
3326   bool TypeDependent = false;
3327   bool ValueDependent = false;
3328   bool InstantiationDependent = false;
3329   computeDeclRefDependence(D, getType(), TypeDependent, ValueDependent,
3330                            InstantiationDependent);
3331   ExprBits.TypeDependent = TypeDependent;
3332   ExprBits.ValueDependent = ValueDependent;
3333   ExprBits.InstantiationDependent = InstantiationDependent;
3334 }
3335