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