Expr.cpp revision 198398
1193326Sed//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This file implements the Expr class and subclasses.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#include "clang/AST/Expr.h"
15198092Srdivacky#include "clang/AST/ExprCXX.h"
16193326Sed#include "clang/AST/APValue.h"
17193326Sed#include "clang/AST/ASTContext.h"
18193326Sed#include "clang/AST/DeclObjC.h"
19193326Sed#include "clang/AST/DeclCXX.h"
20193326Sed#include "clang/AST/DeclTemplate.h"
21193326Sed#include "clang/AST/RecordLayout.h"
22193326Sed#include "clang/AST/StmtVisitor.h"
23194179Sed#include "clang/Basic/Builtins.h"
24193326Sed#include "clang/Basic/TargetInfo.h"
25198092Srdivacky#include "llvm/Support/raw_ostream.h"
26193326Sed#include <algorithm>
27193326Sedusing namespace clang;
28193326Sed
29193326Sed//===----------------------------------------------------------------------===//
30193326Sed// Primary Expressions.
31193326Sed//===----------------------------------------------------------------------===//
32193326Sed
33198092Srdivacky// FIXME: Maybe this should use DeclPrinter with a special "print predefined
34198092Srdivacky// expr" policy instead.
35198092Srdivackystd::string PredefinedExpr::ComputeName(ASTContext &Context, IdentType IT,
36198092Srdivacky                                        const Decl *CurrentDecl) {
37198092Srdivacky  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
38198092Srdivacky    if (IT != PrettyFunction)
39198092Srdivacky      return FD->getNameAsString();
40193326Sed
41198092Srdivacky    llvm::SmallString<256> Name;
42198092Srdivacky    llvm::raw_svector_ostream Out(Name);
43193326Sed
44198092Srdivacky    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
45198092Srdivacky      if (MD->isVirtual())
46198092Srdivacky        Out << "virtual ";
47198092Srdivacky    }
48193326Sed
49198092Srdivacky    PrintingPolicy Policy(Context.getLangOptions());
50198092Srdivacky    Policy.SuppressTagKind = true;
51193326Sed
52198092Srdivacky    std::string Proto = FD->getQualifiedNameAsString(Policy);
53193326Sed
54198092Srdivacky    const FunctionType *AFT = FD->getType()->getAs<FunctionType>();
55198092Srdivacky    const FunctionProtoType *FT = 0;
56198092Srdivacky    if (FD->hasWrittenPrototype())
57198092Srdivacky      FT = dyn_cast<FunctionProtoType>(AFT);
58198092Srdivacky
59198092Srdivacky    Proto += "(";
60198092Srdivacky    if (FT) {
61198092Srdivacky      llvm::raw_string_ostream POut(Proto);
62198092Srdivacky      for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
63198092Srdivacky        if (i) POut << ", ";
64198092Srdivacky        std::string Param;
65198092Srdivacky        FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
66198092Srdivacky        POut << Param;
67198092Srdivacky      }
68198092Srdivacky
69198092Srdivacky      if (FT->isVariadic()) {
70198092Srdivacky        if (FD->getNumParams()) POut << ", ";
71198092Srdivacky        POut << "...";
72198092Srdivacky      }
73198092Srdivacky    }
74198092Srdivacky    Proto += ")";
75198092Srdivacky
76198092Srdivacky    AFT->getResultType().getAsStringInternal(Proto, Policy);
77198092Srdivacky
78198092Srdivacky    Out << Proto;
79198092Srdivacky
80198092Srdivacky    Out.flush();
81198092Srdivacky    return Name.str().str();
82198092Srdivacky  }
83198092Srdivacky  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
84198092Srdivacky    llvm::SmallString<256> Name;
85198092Srdivacky    llvm::raw_svector_ostream Out(Name);
86198092Srdivacky    Out << (MD->isInstanceMethod() ? '-' : '+');
87198092Srdivacky    Out << '[';
88198092Srdivacky    Out << MD->getClassInterface()->getNameAsString();
89198092Srdivacky    if (const ObjCCategoryImplDecl *CID =
90198092Srdivacky        dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext())) {
91198092Srdivacky      Out << '(';
92198092Srdivacky      Out <<  CID->getNameAsString();
93198092Srdivacky      Out <<  ')';
94198092Srdivacky    }
95198092Srdivacky    Out <<  ' ';
96198092Srdivacky    Out << MD->getSelector().getAsString();
97198092Srdivacky    Out <<  ']';
98198092Srdivacky
99198092Srdivacky    Out.flush();
100198092Srdivacky    return Name.str().str();
101198092Srdivacky  }
102198092Srdivacky  if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
103198092Srdivacky    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
104198092Srdivacky    return "top level";
105198092Srdivacky  }
106198092Srdivacky  return "";
107193326Sed}
108193326Sed
109193326Sed/// getValueAsApproximateDouble - This returns the value as an inaccurate
110193326Sed/// double.  Note that this may cause loss of precision, but is useful for
111193326Sed/// debugging dumps, etc.
112193326Seddouble FloatingLiteral::getValueAsApproximateDouble() const {
113193326Sed  llvm::APFloat V = getValue();
114193326Sed  bool ignored;
115193326Sed  V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
116193326Sed            &ignored);
117193326Sed  return V.convertToDouble();
118193326Sed}
119193326Sed
120193326SedStringLiteral *StringLiteral::Create(ASTContext &C, const char *StrData,
121193326Sed                                     unsigned ByteLength, bool Wide,
122193326Sed                                     QualType Ty,
123198092Srdivacky                                     const SourceLocation *Loc,
124193326Sed                                     unsigned NumStrs) {
125193326Sed  // Allocate enough space for the StringLiteral plus an array of locations for
126193326Sed  // any concatenated string tokens.
127193326Sed  void *Mem = C.Allocate(sizeof(StringLiteral)+
128193326Sed                         sizeof(SourceLocation)*(NumStrs-1),
129193326Sed                         llvm::alignof<StringLiteral>());
130193326Sed  StringLiteral *SL = new (Mem) StringLiteral(Ty);
131198092Srdivacky
132193326Sed  // OPTIMIZE: could allocate this appended to the StringLiteral.
133193326Sed  char *AStrData = new (C, 1) char[ByteLength];
134193326Sed  memcpy(AStrData, StrData, ByteLength);
135193326Sed  SL->StrData = AStrData;
136193326Sed  SL->ByteLength = ByteLength;
137193326Sed  SL->IsWide = Wide;
138193326Sed  SL->TokLocs[0] = Loc[0];
139193326Sed  SL->NumConcatenated = NumStrs;
140193326Sed
141193326Sed  if (NumStrs != 1)
142193326Sed    memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
143193326Sed  return SL;
144193326Sed}
145193326Sed
146193326SedStringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
147193326Sed  void *Mem = C.Allocate(sizeof(StringLiteral)+
148193326Sed                         sizeof(SourceLocation)*(NumStrs-1),
149193326Sed                         llvm::alignof<StringLiteral>());
150193326Sed  StringLiteral *SL = new (Mem) StringLiteral(QualType());
151193326Sed  SL->StrData = 0;
152193326Sed  SL->ByteLength = 0;
153193326Sed  SL->NumConcatenated = NumStrs;
154193326Sed  return SL;
155193326Sed}
156193326Sed
157198092Srdivackyvoid StringLiteral::DoDestroy(ASTContext &C) {
158193326Sed  C.Deallocate(const_cast<char*>(StrData));
159198092Srdivacky  Expr::DoDestroy(C);
160193326Sed}
161193326Sed
162198092Srdivackyvoid StringLiteral::setString(ASTContext &C, llvm::StringRef Str) {
163193326Sed  if (StrData)
164193326Sed    C.Deallocate(const_cast<char*>(StrData));
165193326Sed
166198092Srdivacky  char *AStrData = new (C, 1) char[Str.size()];
167198092Srdivacky  memcpy(AStrData, Str.data(), Str.size());
168193326Sed  StrData = AStrData;
169198092Srdivacky  ByteLength = Str.size();
170193326Sed}
171193326Sed
172193326Sed/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
173193326Sed/// corresponds to, e.g. "sizeof" or "[pre]++".
174193326Sedconst char *UnaryOperator::getOpcodeStr(Opcode Op) {
175193326Sed  switch (Op) {
176193326Sed  default: assert(0 && "Unknown unary operator");
177193326Sed  case PostInc: return "++";
178193326Sed  case PostDec: return "--";
179193326Sed  case PreInc:  return "++";
180193326Sed  case PreDec:  return "--";
181193326Sed  case AddrOf:  return "&";
182193326Sed  case Deref:   return "*";
183193326Sed  case Plus:    return "+";
184193326Sed  case Minus:   return "-";
185193326Sed  case Not:     return "~";
186193326Sed  case LNot:    return "!";
187193326Sed  case Real:    return "__real";
188193326Sed  case Imag:    return "__imag";
189193326Sed  case Extension: return "__extension__";
190193326Sed  case OffsetOf: return "__builtin_offsetof";
191193326Sed  }
192193326Sed}
193193326Sed
194198092SrdivackyUnaryOperator::Opcode
195193326SedUnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
196193326Sed  switch (OO) {
197193326Sed  default: assert(false && "No unary operator for overloaded function");
198193326Sed  case OO_PlusPlus:   return Postfix ? PostInc : PreInc;
199193326Sed  case OO_MinusMinus: return Postfix ? PostDec : PreDec;
200193326Sed  case OO_Amp:        return AddrOf;
201193326Sed  case OO_Star:       return Deref;
202193326Sed  case OO_Plus:       return Plus;
203193326Sed  case OO_Minus:      return Minus;
204193326Sed  case OO_Tilde:      return Not;
205193326Sed  case OO_Exclaim:    return LNot;
206193326Sed  }
207193326Sed}
208193326Sed
209193326SedOverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
210193326Sed  switch (Opc) {
211193326Sed  case PostInc: case PreInc: return OO_PlusPlus;
212193326Sed  case PostDec: case PreDec: return OO_MinusMinus;
213193326Sed  case AddrOf: return OO_Amp;
214193326Sed  case Deref: return OO_Star;
215193326Sed  case Plus: return OO_Plus;
216193326Sed  case Minus: return OO_Minus;
217193326Sed  case Not: return OO_Tilde;
218193326Sed  case LNot: return OO_Exclaim;
219193326Sed  default: return OO_None;
220193326Sed  }
221193326Sed}
222193326Sed
223193326Sed
224193326Sed//===----------------------------------------------------------------------===//
225193326Sed// Postfix Operators.
226193326Sed//===----------------------------------------------------------------------===//
227193326Sed
228193326SedCallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args,
229193326Sed                   unsigned numargs, QualType t, SourceLocation rparenloc)
230198092Srdivacky  : Expr(SC, t,
231193326Sed         fn->isTypeDependent() || hasAnyTypeDependentArguments(args, numargs),
232193326Sed         fn->isValueDependent() || hasAnyValueDependentArguments(args,numargs)),
233193326Sed    NumArgs(numargs) {
234198092Srdivacky
235193326Sed  SubExprs = new (C) Stmt*[numargs+1];
236193326Sed  SubExprs[FN] = fn;
237193326Sed  for (unsigned i = 0; i != numargs; ++i)
238193326Sed    SubExprs[i+ARGS_START] = args[i];
239193326Sed
240193326Sed  RParenLoc = rparenloc;
241193326Sed}
242193326Sed
243193326SedCallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs,
244193326Sed                   QualType t, SourceLocation rparenloc)
245193326Sed  : Expr(CallExprClass, t,
246193326Sed         fn->isTypeDependent() || hasAnyTypeDependentArguments(args, numargs),
247193326Sed         fn->isValueDependent() || hasAnyValueDependentArguments(args,numargs)),
248193326Sed    NumArgs(numargs) {
249193326Sed
250193326Sed  SubExprs = new (C) Stmt*[numargs+1];
251193326Sed  SubExprs[FN] = fn;
252193326Sed  for (unsigned i = 0; i != numargs; ++i)
253193326Sed    SubExprs[i+ARGS_START] = args[i];
254193326Sed
255193326Sed  RParenLoc = rparenloc;
256193326Sed}
257193326Sed
258198092SrdivackyCallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
259198092Srdivacky  : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
260193326Sed  SubExprs = new (C) Stmt*[1];
261193326Sed}
262193326Sed
263198092Srdivackyvoid CallExpr::DoDestroy(ASTContext& C) {
264193326Sed  DestroyChildren(C);
265193326Sed  if (SubExprs) C.Deallocate(SubExprs);
266193326Sed  this->~CallExpr();
267193326Sed  C.Deallocate(this);
268193326Sed}
269193326Sed
270198092SrdivackyFunctionDecl *CallExpr::getDirectCallee() {
271198092Srdivacky  Expr *CEE = getCallee()->IgnoreParenCasts();
272198092Srdivacky  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
273198092Srdivacky    return dyn_cast<FunctionDecl>(DRE->getDecl());
274198092Srdivacky
275198092Srdivacky  return 0;
276198092Srdivacky}
277198092Srdivacky
278193326Sed/// setNumArgs - This changes the number of arguments present in this call.
279193326Sed/// Any orphaned expressions are deleted by this, and any new operands are set
280193326Sed/// to null.
281193326Sedvoid CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
282193326Sed  // No change, just return.
283193326Sed  if (NumArgs == getNumArgs()) return;
284198092Srdivacky
285193326Sed  // If shrinking # arguments, just delete the extras and forgot them.
286193326Sed  if (NumArgs < getNumArgs()) {
287193326Sed    for (unsigned i = NumArgs, e = getNumArgs(); i != e; ++i)
288193326Sed      getArg(i)->Destroy(C);
289193326Sed    this->NumArgs = NumArgs;
290193326Sed    return;
291193326Sed  }
292193326Sed
293193326Sed  // Otherwise, we are growing the # arguments.  New an bigger argument array.
294198092Srdivacky  Stmt **NewSubExprs = new (C) Stmt*[NumArgs+1];
295193326Sed  // Copy over args.
296193326Sed  for (unsigned i = 0; i != getNumArgs()+ARGS_START; ++i)
297193326Sed    NewSubExprs[i] = SubExprs[i];
298193326Sed  // Null out new args.
299193326Sed  for (unsigned i = getNumArgs()+ARGS_START; i != NumArgs+ARGS_START; ++i)
300193326Sed    NewSubExprs[i] = 0;
301198092Srdivacky
302193326Sed  if (SubExprs) C.Deallocate(SubExprs);
303193326Sed  SubExprs = NewSubExprs;
304193326Sed  this->NumArgs = NumArgs;
305193326Sed}
306193326Sed
307193326Sed/// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
308193326Sed/// not, return 0.
309193326Sedunsigned CallExpr::isBuiltinCall(ASTContext &Context) const {
310193326Sed  // All simple function calls (e.g. func()) are implicitly cast to pointer to
311198092Srdivacky  // function. As a result, we try and obtain the DeclRefExpr from the
312193326Sed  // ImplicitCastExpr.
313193326Sed  const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
314193326Sed  if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
315193326Sed    return 0;
316198092Srdivacky
317193326Sed  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
318193326Sed  if (!DRE)
319193326Sed    return 0;
320198092Srdivacky
321193326Sed  const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
322193326Sed  if (!FDecl)
323193326Sed    return 0;
324198092Srdivacky
325193326Sed  if (!FDecl->getIdentifier())
326193326Sed    return 0;
327193326Sed
328198092Srdivacky  return FDecl->getBuiltinID();
329193326Sed}
330193326Sed
331193326SedQualType CallExpr::getCallReturnType() const {
332193326Sed  QualType CalleeType = getCallee()->getType();
333198092Srdivacky  if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
334193326Sed    CalleeType = FnTypePtr->getPointeeType();
335198092Srdivacky  else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
336193326Sed    CalleeType = BPT->getPointeeType();
337198092Srdivacky
338198092Srdivacky  const FunctionType *FnType = CalleeType->getAs<FunctionType>();
339193326Sed  return FnType->getResultType();
340193326Sed}
341193326Sed
342198092SrdivackyMemberExpr::MemberExpr(Expr *base, bool isarrow, NestedNameSpecifier *qual,
343198092Srdivacky                       SourceRange qualrange, NamedDecl *memberdecl,
344198092Srdivacky                       SourceLocation l, bool has_explicit,
345198092Srdivacky                       SourceLocation langle,
346198092Srdivacky                       const TemplateArgument *targs, unsigned numtargs,
347198092Srdivacky                       SourceLocation rangle, QualType ty)
348198092Srdivacky  : Expr(MemberExprClass, ty,
349198092Srdivacky         base->isTypeDependent() || (qual && qual->isDependent()),
350198092Srdivacky         base->isValueDependent() || (qual && qual->isDependent())),
351198092Srdivacky    Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow),
352198092Srdivacky    HasQualifier(qual != 0), HasExplicitTemplateArgumentList(has_explicit) {
353198092Srdivacky  // Initialize the qualifier, if any.
354198092Srdivacky  if (HasQualifier) {
355198092Srdivacky    NameQualifier *NQ = getMemberQualifier();
356198092Srdivacky    NQ->NNS = qual;
357198092Srdivacky    NQ->Range = qualrange;
358198092Srdivacky  }
359198092Srdivacky
360198092Srdivacky  // Initialize the explicit template argument list, if any.
361198092Srdivacky  if (HasExplicitTemplateArgumentList) {
362198092Srdivacky    ExplicitTemplateArgumentList *ETemplateArgs
363198092Srdivacky      = getExplicitTemplateArgumentList();
364198092Srdivacky    ETemplateArgs->LAngleLoc = langle;
365198092Srdivacky    ETemplateArgs->RAngleLoc = rangle;
366198092Srdivacky    ETemplateArgs->NumTemplateArgs = numtargs;
367198092Srdivacky
368198092Srdivacky    TemplateArgument *TemplateArgs = ETemplateArgs->getTemplateArgs();
369198092Srdivacky    for (unsigned I = 0; I < numtargs; ++I)
370198092Srdivacky      new (TemplateArgs + I) TemplateArgument(targs[I]);
371198092Srdivacky  }
372198092Srdivacky}
373198092Srdivacky
374198092SrdivackyMemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
375198092Srdivacky                               NestedNameSpecifier *qual,
376198092Srdivacky                               SourceRange qualrange,
377198092Srdivacky                               NamedDecl *memberdecl,
378198092Srdivacky                               SourceLocation l,
379198092Srdivacky                               bool has_explicit,
380198092Srdivacky                               SourceLocation langle,
381198092Srdivacky                               const TemplateArgument *targs,
382198092Srdivacky                               unsigned numtargs,
383198092Srdivacky                               SourceLocation rangle,
384198092Srdivacky                               QualType ty) {
385198092Srdivacky  std::size_t Size = sizeof(MemberExpr);
386198092Srdivacky  if (qual != 0)
387198092Srdivacky    Size += sizeof(NameQualifier);
388198092Srdivacky
389198092Srdivacky  if (has_explicit)
390198092Srdivacky    Size += sizeof(ExplicitTemplateArgumentList) +
391198092Srdivacky    sizeof(TemplateArgument) * numtargs;
392198092Srdivacky
393198092Srdivacky  void *Mem = C.Allocate(Size, llvm::alignof<MemberExpr>());
394198092Srdivacky  return new (Mem) MemberExpr(base, isarrow, qual, qualrange, memberdecl, l,
395198092Srdivacky                              has_explicit, langle, targs, numtargs, rangle,
396198092Srdivacky                              ty);
397198092Srdivacky}
398198092Srdivacky
399198092Srdivackyconst char *CastExpr::getCastKindName() const {
400198092Srdivacky  switch (getCastKind()) {
401198092Srdivacky  case CastExpr::CK_Unknown:
402198092Srdivacky    return "Unknown";
403198092Srdivacky  case CastExpr::CK_BitCast:
404198092Srdivacky    return "BitCast";
405198092Srdivacky  case CastExpr::CK_NoOp:
406198092Srdivacky    return "NoOp";
407198092Srdivacky  case CastExpr::CK_DerivedToBase:
408198092Srdivacky    return "DerivedToBase";
409198092Srdivacky  case CastExpr::CK_Dynamic:
410198092Srdivacky    return "Dynamic";
411198092Srdivacky  case CastExpr::CK_ToUnion:
412198092Srdivacky    return "ToUnion";
413198092Srdivacky  case CastExpr::CK_ArrayToPointerDecay:
414198092Srdivacky    return "ArrayToPointerDecay";
415198092Srdivacky  case CastExpr::CK_FunctionToPointerDecay:
416198092Srdivacky    return "FunctionToPointerDecay";
417198092Srdivacky  case CastExpr::CK_NullToMemberPointer:
418198092Srdivacky    return "NullToMemberPointer";
419198092Srdivacky  case CastExpr::CK_BaseToDerivedMemberPointer:
420198092Srdivacky    return "BaseToDerivedMemberPointer";
421198092Srdivacky  case CastExpr::CK_UserDefinedConversion:
422198092Srdivacky    return "UserDefinedConversion";
423198092Srdivacky  case CastExpr::CK_ConstructorConversion:
424198092Srdivacky    return "ConstructorConversion";
425198092Srdivacky  case CastExpr::CK_IntegralToPointer:
426198092Srdivacky    return "IntegralToPointer";
427198092Srdivacky  case CastExpr::CK_PointerToIntegral:
428198092Srdivacky    return "PointerToIntegral";
429198398Srdivacky  case CastExpr::CK_ToVoid:
430198398Srdivacky    return "ToVoid";
431198398Srdivacky  case CastExpr::CK_VectorSplat:
432198398Srdivacky    return "VectorSplat";
433198398Srdivacky  case CastExpr::CK_IntegralCast:
434198398Srdivacky    return "IntegralCast";
435198398Srdivacky  case CastExpr::CK_IntegralToFloating:
436198398Srdivacky    return "IntegralToFloating";
437198398Srdivacky  case CastExpr::CK_FloatingToIntegral:
438198398Srdivacky    return "FloatingToIntegral";
439198398Srdivacky  case CastExpr::CK_FloatingCast:
440198398Srdivacky    return "FloatingCast";
441198092Srdivacky  }
442198092Srdivacky
443198092Srdivacky  assert(0 && "Unhandled cast kind!");
444198092Srdivacky  return 0;
445198092Srdivacky}
446198092Srdivacky
447193326Sed/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
448193326Sed/// corresponds to, e.g. "<<=".
449193326Sedconst char *BinaryOperator::getOpcodeStr(Opcode Op) {
450193326Sed  switch (Op) {
451193326Sed  case PtrMemD:   return ".*";
452193326Sed  case PtrMemI:   return "->*";
453193326Sed  case Mul:       return "*";
454193326Sed  case Div:       return "/";
455193326Sed  case Rem:       return "%";
456193326Sed  case Add:       return "+";
457193326Sed  case Sub:       return "-";
458193326Sed  case Shl:       return "<<";
459193326Sed  case Shr:       return ">>";
460193326Sed  case LT:        return "<";
461193326Sed  case GT:        return ">";
462193326Sed  case LE:        return "<=";
463193326Sed  case GE:        return ">=";
464193326Sed  case EQ:        return "==";
465193326Sed  case NE:        return "!=";
466193326Sed  case And:       return "&";
467193326Sed  case Xor:       return "^";
468193326Sed  case Or:        return "|";
469193326Sed  case LAnd:      return "&&";
470193326Sed  case LOr:       return "||";
471193326Sed  case Assign:    return "=";
472193326Sed  case MulAssign: return "*=";
473193326Sed  case DivAssign: return "/=";
474193326Sed  case RemAssign: return "%=";
475193326Sed  case AddAssign: return "+=";
476193326Sed  case SubAssign: return "-=";
477193326Sed  case ShlAssign: return "<<=";
478193326Sed  case ShrAssign: return ">>=";
479193326Sed  case AndAssign: return "&=";
480193326Sed  case XorAssign: return "^=";
481193326Sed  case OrAssign:  return "|=";
482193326Sed  case Comma:     return ",";
483193326Sed  }
484193326Sed
485193326Sed  return "";
486193326Sed}
487193326Sed
488198092SrdivackyBinaryOperator::Opcode
489193326SedBinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
490193326Sed  switch (OO) {
491193326Sed  default: assert(false && "Not an overloadable binary operator");
492193326Sed  case OO_Plus: return Add;
493193326Sed  case OO_Minus: return Sub;
494193326Sed  case OO_Star: return Mul;
495193326Sed  case OO_Slash: return Div;
496193326Sed  case OO_Percent: return Rem;
497193326Sed  case OO_Caret: return Xor;
498193326Sed  case OO_Amp: return And;
499193326Sed  case OO_Pipe: return Or;
500193326Sed  case OO_Equal: return Assign;
501193326Sed  case OO_Less: return LT;
502193326Sed  case OO_Greater: return GT;
503193326Sed  case OO_PlusEqual: return AddAssign;
504193326Sed  case OO_MinusEqual: return SubAssign;
505193326Sed  case OO_StarEqual: return MulAssign;
506193326Sed  case OO_SlashEqual: return DivAssign;
507193326Sed  case OO_PercentEqual: return RemAssign;
508193326Sed  case OO_CaretEqual: return XorAssign;
509193326Sed  case OO_AmpEqual: return AndAssign;
510193326Sed  case OO_PipeEqual: return OrAssign;
511193326Sed  case OO_LessLess: return Shl;
512193326Sed  case OO_GreaterGreater: return Shr;
513193326Sed  case OO_LessLessEqual: return ShlAssign;
514193326Sed  case OO_GreaterGreaterEqual: return ShrAssign;
515193326Sed  case OO_EqualEqual: return EQ;
516193326Sed  case OO_ExclaimEqual: return NE;
517193326Sed  case OO_LessEqual: return LE;
518193326Sed  case OO_GreaterEqual: return GE;
519193326Sed  case OO_AmpAmp: return LAnd;
520193326Sed  case OO_PipePipe: return LOr;
521193326Sed  case OO_Comma: return Comma;
522193326Sed  case OO_ArrowStar: return PtrMemI;
523193326Sed  }
524193326Sed}
525193326Sed
526193326SedOverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
527193326Sed  static const OverloadedOperatorKind OverOps[] = {
528193326Sed    /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
529193326Sed    OO_Star, OO_Slash, OO_Percent,
530193326Sed    OO_Plus, OO_Minus,
531193326Sed    OO_LessLess, OO_GreaterGreater,
532193326Sed    OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
533193326Sed    OO_EqualEqual, OO_ExclaimEqual,
534193326Sed    OO_Amp,
535193326Sed    OO_Caret,
536193326Sed    OO_Pipe,
537193326Sed    OO_AmpAmp,
538193326Sed    OO_PipePipe,
539193326Sed    OO_Equal, OO_StarEqual,
540193326Sed    OO_SlashEqual, OO_PercentEqual,
541193326Sed    OO_PlusEqual, OO_MinusEqual,
542193326Sed    OO_LessLessEqual, OO_GreaterGreaterEqual,
543193326Sed    OO_AmpEqual, OO_CaretEqual,
544193326Sed    OO_PipeEqual,
545193326Sed    OO_Comma
546193326Sed  };
547193326Sed  return OverOps[Opc];
548193326Sed}
549193326Sed
550198092SrdivackyInitListExpr::InitListExpr(SourceLocation lbraceloc,
551193326Sed                           Expr **initExprs, unsigned numInits,
552193326Sed                           SourceLocation rbraceloc)
553193326Sed  : Expr(InitListExprClass, QualType(),
554193326Sed         hasAnyTypeDependentArguments(initExprs, numInits),
555193326Sed         hasAnyValueDependentArguments(initExprs, numInits)),
556198092Srdivacky    LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0),
557193326Sed    UnionFieldInit(0), HadArrayRangeDesignator(false) {
558193326Sed
559193326Sed  InitExprs.insert(InitExprs.end(), initExprs, initExprs+numInits);
560193326Sed}
561193326Sed
562193326Sedvoid InitListExpr::reserveInits(unsigned NumInits) {
563193326Sed  if (NumInits > InitExprs.size())
564193326Sed    InitExprs.reserve(NumInits);
565193326Sed}
566193326Sed
567193326Sedvoid InitListExpr::resizeInits(ASTContext &Context, unsigned NumInits) {
568193326Sed  for (unsigned Idx = NumInits, LastIdx = InitExprs.size();
569193326Sed       Idx < LastIdx; ++Idx)
570193326Sed    InitExprs[Idx]->Destroy(Context);
571193326Sed  InitExprs.resize(NumInits, 0);
572193326Sed}
573193326Sed
574193326SedExpr *InitListExpr::updateInit(unsigned Init, Expr *expr) {
575193326Sed  if (Init >= InitExprs.size()) {
576193326Sed    InitExprs.insert(InitExprs.end(), Init - InitExprs.size() + 1, 0);
577193326Sed    InitExprs.back() = expr;
578193326Sed    return 0;
579193326Sed  }
580198092Srdivacky
581193326Sed  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
582193326Sed  InitExprs[Init] = expr;
583193326Sed  return Result;
584193326Sed}
585193326Sed
586193326Sed/// getFunctionType - Return the underlying function type for this block.
587193326Sed///
588193326Sedconst FunctionType *BlockExpr::getFunctionType() const {
589198092Srdivacky  return getType()->getAs<BlockPointerType>()->
590198092Srdivacky                    getPointeeType()->getAs<FunctionType>();
591193326Sed}
592193326Sed
593198092SrdivackySourceLocation BlockExpr::getCaretLocation() const {
594198092Srdivacky  return TheBlock->getCaretLocation();
595193326Sed}
596198092Srdivackyconst Stmt *BlockExpr::getBody() const {
597193326Sed  return TheBlock->getBody();
598193326Sed}
599198092SrdivackyStmt *BlockExpr::getBody() {
600198092Srdivacky  return TheBlock->getBody();
601193326Sed}
602193326Sed
603193326Sed
604193326Sed//===----------------------------------------------------------------------===//
605193326Sed// Generic Expression Routines
606193326Sed//===----------------------------------------------------------------------===//
607193326Sed
608193326Sed/// isUnusedResultAWarning - Return true if this immediate expression should
609193326Sed/// be warned about if the result is unused.  If so, fill in Loc and Ranges
610193326Sed/// with location to warn on and the source range[s] to report with the
611193326Sed/// warning.
612193326Sedbool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
613195341Sed                                  SourceRange &R2) const {
614193326Sed  // Don't warn if the expr is type dependent. The type could end up
615193326Sed  // instantiating to void.
616193326Sed  if (isTypeDependent())
617193326Sed    return false;
618198092Srdivacky
619193326Sed  switch (getStmtClass()) {
620193326Sed  default:
621193326Sed    Loc = getExprLoc();
622193326Sed    R1 = getSourceRange();
623193326Sed    return true;
624193326Sed  case ParenExprClass:
625193326Sed    return cast<ParenExpr>(this)->getSubExpr()->
626195341Sed      isUnusedResultAWarning(Loc, R1, R2);
627193326Sed  case UnaryOperatorClass: {
628193326Sed    const UnaryOperator *UO = cast<UnaryOperator>(this);
629198092Srdivacky
630193326Sed    switch (UO->getOpcode()) {
631193326Sed    default: break;
632193326Sed    case UnaryOperator::PostInc:
633193326Sed    case UnaryOperator::PostDec:
634193326Sed    case UnaryOperator::PreInc:
635193326Sed    case UnaryOperator::PreDec:                 // ++/--
636193326Sed      return false;  // Not a warning.
637193326Sed    case UnaryOperator::Deref:
638193326Sed      // Dereferencing a volatile pointer is a side-effect.
639193326Sed      if (getType().isVolatileQualified())
640193326Sed        return false;
641193326Sed      break;
642193326Sed    case UnaryOperator::Real:
643193326Sed    case UnaryOperator::Imag:
644193326Sed      // accessing a piece of a volatile complex is a side-effect.
645193326Sed      if (UO->getSubExpr()->getType().isVolatileQualified())
646193326Sed        return false;
647193326Sed      break;
648193326Sed    case UnaryOperator::Extension:
649195341Sed      return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2);
650193326Sed    }
651193326Sed    Loc = UO->getOperatorLoc();
652193326Sed    R1 = UO->getSubExpr()->getSourceRange();
653193326Sed    return true;
654193326Sed  }
655193326Sed  case BinaryOperatorClass: {
656193326Sed    const BinaryOperator *BO = cast<BinaryOperator>(this);
657193326Sed    // Consider comma to have side effects if the LHS or RHS does.
658193326Sed    if (BO->getOpcode() == BinaryOperator::Comma)
659195341Sed      return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2) ||
660195341Sed             BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2);
661198092Srdivacky
662193326Sed    if (BO->isAssignmentOp())
663193326Sed      return false;
664193326Sed    Loc = BO->getOperatorLoc();
665193326Sed    R1 = BO->getLHS()->getSourceRange();
666193326Sed    R2 = BO->getRHS()->getSourceRange();
667193326Sed    return true;
668193326Sed  }
669193326Sed  case CompoundAssignOperatorClass:
670193326Sed    return false;
671193326Sed
672193326Sed  case ConditionalOperatorClass: {
673193326Sed    // The condition must be evaluated, but if either the LHS or RHS is a
674193326Sed    // warning, warn about them.
675193326Sed    const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
676198092Srdivacky    if (Exp->getLHS() &&
677195341Sed        Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2))
678193326Sed      return true;
679195341Sed    return Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2);
680193326Sed  }
681193326Sed
682193326Sed  case MemberExprClass:
683193326Sed    // If the base pointer or element is to a volatile pointer/field, accessing
684193326Sed    // it is a side effect.
685193326Sed    if (getType().isVolatileQualified())
686193326Sed      return false;
687193326Sed    Loc = cast<MemberExpr>(this)->getMemberLoc();
688193326Sed    R1 = SourceRange(Loc, Loc);
689193326Sed    R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
690193326Sed    return true;
691198092Srdivacky
692193326Sed  case ArraySubscriptExprClass:
693193326Sed    // If the base pointer or element is to a volatile pointer/field, accessing
694193326Sed    // it is a side effect.
695193326Sed    if (getType().isVolatileQualified())
696193326Sed      return false;
697193326Sed    Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
698193326Sed    R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
699193326Sed    R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
700193326Sed    return true;
701193326Sed
702193326Sed  case CallExprClass:
703193326Sed  case CXXOperatorCallExprClass:
704193326Sed  case CXXMemberCallExprClass: {
705193326Sed    // If this is a direct call, get the callee.
706193326Sed    const CallExpr *CE = cast<CallExpr>(this);
707198092Srdivacky    if (const FunctionDecl *FD = CE->getDirectCallee()) {
708193326Sed      // If the callee has attribute pure, const, or warn_unused_result, warn
709193326Sed      // about it. void foo() { strlen("bar"); } should warn.
710198092Srdivacky      //
711198092Srdivacky      // Note: If new cases are added here, DiagnoseUnusedExprResult should be
712198092Srdivacky      // updated to match for QoI.
713198092Srdivacky      if (FD->getAttr<WarnUnusedResultAttr>() ||
714198092Srdivacky          FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
715198092Srdivacky        Loc = CE->getCallee()->getLocStart();
716198092Srdivacky        R1 = CE->getCallee()->getSourceRange();
717198092Srdivacky
718198092Srdivacky        if (unsigned NumArgs = CE->getNumArgs())
719198092Srdivacky          R2 = SourceRange(CE->getArg(0)->getLocStart(),
720198092Srdivacky                           CE->getArg(NumArgs-1)->getLocEnd());
721198092Srdivacky        return true;
722198092Srdivacky      }
723193326Sed    }
724193326Sed    return false;
725193326Sed  }
726193326Sed  case ObjCMessageExprClass:
727193326Sed    return false;
728198092Srdivacky
729198092Srdivacky  case ObjCImplicitSetterGetterRefExprClass: {   // Dot syntax for message send.
730198092Srdivacky#if 0
731198092Srdivacky    const ObjCImplicitSetterGetterRefExpr *Ref =
732198092Srdivacky      cast<ObjCImplicitSetterGetterRefExpr>(this);
733198092Srdivacky    // FIXME: We really want the location of the '.' here.
734198092Srdivacky    Loc = Ref->getLocation();
735198092Srdivacky    R1 = SourceRange(Ref->getLocation(), Ref->getLocation());
736198092Srdivacky    if (Ref->getBase())
737198092Srdivacky      R2 = Ref->getBase()->getSourceRange();
738198092Srdivacky#else
739198092Srdivacky    Loc = getExprLoc();
740198092Srdivacky    R1 = getSourceRange();
741198092Srdivacky#endif
742198092Srdivacky    return true;
743198092Srdivacky  }
744193326Sed  case StmtExprClass: {
745193326Sed    // Statement exprs don't logically have side effects themselves, but are
746193326Sed    // sometimes used in macros in ways that give them a type that is unused.
747193326Sed    // For example ({ blah; foo(); }) will end up with a type if foo has a type.
748193326Sed    // however, if the result of the stmt expr is dead, we don't want to emit a
749193326Sed    // warning.
750193326Sed    const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
751193326Sed    if (!CS->body_empty())
752193326Sed      if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
753195341Sed        return E->isUnusedResultAWarning(Loc, R1, R2);
754198092Srdivacky
755193326Sed    Loc = cast<StmtExpr>(this)->getLParenLoc();
756193326Sed    R1 = getSourceRange();
757193326Sed    return true;
758193326Sed  }
759193326Sed  case CStyleCastExprClass:
760198092Srdivacky    // If this is an explicit cast to void, allow it.  People do this when they
761198092Srdivacky    // think they know what they're doing :).
762193326Sed    if (getType()->isVoidType())
763198092Srdivacky      return false;
764193326Sed    Loc = cast<CStyleCastExpr>(this)->getLParenLoc();
765193326Sed    R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange();
766193326Sed    return true;
767193326Sed  case CXXFunctionalCastExprClass:
768193326Sed    // If this is a cast to void, check the operand.  Otherwise, the result of
769193326Sed    // the cast is unused.
770193326Sed    if (getType()->isVoidType())
771194613Sed      return cast<CastExpr>(this)->getSubExpr()
772195341Sed               ->isUnusedResultAWarning(Loc, R1, R2);
773193326Sed    Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc();
774193326Sed    R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange();
775193326Sed    return true;
776198092Srdivacky
777193326Sed  case ImplicitCastExprClass:
778193326Sed    // Check the operand, since implicit casts are inserted by Sema
779193326Sed    return cast<ImplicitCastExpr>(this)
780195341Sed      ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2);
781193326Sed
782193326Sed  case CXXDefaultArgExprClass:
783193326Sed    return cast<CXXDefaultArgExpr>(this)
784195341Sed      ->getExpr()->isUnusedResultAWarning(Loc, R1, R2);
785193326Sed
786193326Sed  case CXXNewExprClass:
787193326Sed    // FIXME: In theory, there might be new expressions that don't have side
788193326Sed    // effects (e.g. a placement new with an uninitialized POD).
789193326Sed  case CXXDeleteExprClass:
790193326Sed    return false;
791198092Srdivacky  case CXXBindTemporaryExprClass:
792198092Srdivacky    return cast<CXXBindTemporaryExpr>(this)
793198092Srdivacky      ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2);
794193326Sed  case CXXExprWithTemporariesClass:
795193326Sed    return cast<CXXExprWithTemporaries>(this)
796195341Sed      ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2);
797193326Sed  }
798193326Sed}
799193326Sed
800193326Sed/// DeclCanBeLvalue - Determine whether the given declaration can be
801193326Sed/// an lvalue. This is a helper routine for isLvalue.
802193326Sedstatic bool DeclCanBeLvalue(const NamedDecl *Decl, ASTContext &Ctx) {
803193326Sed  // C++ [temp.param]p6:
804193326Sed  //   A non-type non-reference template-parameter is not an lvalue.
805198092Srdivacky  if (const NonTypeTemplateParmDecl *NTTParm
806193326Sed        = dyn_cast<NonTypeTemplateParmDecl>(Decl))
807193326Sed    return NTTParm->getType()->isReferenceType();
808193326Sed
809193326Sed  return isa<VarDecl>(Decl) || isa<FieldDecl>(Decl) ||
810193326Sed    // C++ 3.10p2: An lvalue refers to an object or function.
811193326Sed    (Ctx.getLangOptions().CPlusPlus &&
812198092Srdivacky     (isa<FunctionDecl>(Decl) || isa<OverloadedFunctionDecl>(Decl) ||
813198092Srdivacky      isa<FunctionTemplateDecl>(Decl)));
814193326Sed}
815193326Sed
816193326Sed/// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or an
817193326Sed/// incomplete type other than void. Nonarray expressions that can be lvalues:
818193326Sed///  - name, where name must be a variable
819193326Sed///  - e[i]
820193326Sed///  - (e), where e must be an lvalue
821193326Sed///  - e.name, where e must be an lvalue
822193326Sed///  - e->name
823193326Sed///  - *e, the type of e cannot be a function type
824193326Sed///  - string-constant
825193326Sed///  - (__real__ e) and (__imag__ e) where e is an lvalue  [GNU extension]
826193326Sed///  - reference type [C++ [expr]]
827193326Sed///
828193326SedExpr::isLvalueResult Expr::isLvalue(ASTContext &Ctx) const {
829193326Sed  assert(!TR->isReferenceType() && "Expressions can't have reference type.");
830193326Sed
831193326Sed  isLvalueResult Res = isLvalueInternal(Ctx);
832193326Sed  if (Res != LV_Valid || Ctx.getLangOptions().CPlusPlus)
833193326Sed    return Res;
834193326Sed
835193326Sed  // first, check the type (C99 6.3.2.1). Expressions with function
836193326Sed  // type in C are not lvalues, but they can be lvalues in C++.
837198092Srdivacky  if (TR->isFunctionType() || TR == Ctx.OverloadTy)
838193326Sed    return LV_NotObjectType;
839193326Sed
840193326Sed  // Allow qualified void which is an incomplete type other than void (yuck).
841198092Srdivacky  if (TR->isVoidType() && !Ctx.getCanonicalType(TR).hasQualifiers())
842193326Sed    return LV_IncompleteVoidType;
843193326Sed
844193326Sed  return LV_Valid;
845193326Sed}
846193326Sed
847193326Sed// Check whether the expression can be sanely treated like an l-value
848193326SedExpr::isLvalueResult Expr::isLvalueInternal(ASTContext &Ctx) const {
849193326Sed  switch (getStmtClass()) {
850193326Sed  case StringLiteralClass:  // C99 6.5.1p4
851193326Sed  case ObjCEncodeExprClass: // @encode behaves like its string in every way.
852193326Sed    return LV_Valid;
853193326Sed  case ArraySubscriptExprClass: // C99 6.5.3p4 (e1[e2] == (*((e1)+(e2))))
854193326Sed    // For vectors, make sure base is an lvalue (i.e. not a function call).
855193326Sed    if (cast<ArraySubscriptExpr>(this)->getBase()->getType()->isVectorType())
856193326Sed      return cast<ArraySubscriptExpr>(this)->getBase()->isLvalue(Ctx);
857193326Sed    return LV_Valid;
858198092Srdivacky  case DeclRefExprClass:
859193326Sed  case QualifiedDeclRefExprClass: { // C99 6.5.1p2
860193326Sed    const NamedDecl *RefdDecl = cast<DeclRefExpr>(this)->getDecl();
861193326Sed    if (DeclCanBeLvalue(RefdDecl, Ctx))
862193326Sed      return LV_Valid;
863193326Sed    break;
864193326Sed  }
865193326Sed  case BlockDeclRefExprClass: {
866193326Sed    const BlockDeclRefExpr *BDR = cast<BlockDeclRefExpr>(this);
867193326Sed    if (isa<VarDecl>(BDR->getDecl()))
868193326Sed      return LV_Valid;
869193326Sed    break;
870193326Sed  }
871198092Srdivacky  case MemberExprClass: {
872193326Sed    const MemberExpr *m = cast<MemberExpr>(this);
873193326Sed    if (Ctx.getLangOptions().CPlusPlus) { // C++ [expr.ref]p4:
874193326Sed      NamedDecl *Member = m->getMemberDecl();
875193326Sed      // C++ [expr.ref]p4:
876193326Sed      //   If E2 is declared to have type "reference to T", then E1.E2
877193326Sed      //   is an lvalue.
878193326Sed      if (ValueDecl *Value = dyn_cast<ValueDecl>(Member))
879193326Sed        if (Value->getType()->isReferenceType())
880193326Sed          return LV_Valid;
881193326Sed
882193326Sed      //   -- If E2 is a static data member [...] then E1.E2 is an lvalue.
883193326Sed      if (isa<VarDecl>(Member) && Member->getDeclContext()->isRecord())
884193326Sed        return LV_Valid;
885193326Sed
886193326Sed      //   -- If E2 is a non-static data member [...]. If E1 is an
887193326Sed      //      lvalue, then E1.E2 is an lvalue.
888193326Sed      if (isa<FieldDecl>(Member))
889193326Sed        return m->isArrow() ? LV_Valid : m->getBase()->isLvalue(Ctx);
890193326Sed
891193326Sed      //   -- If it refers to a static member function [...], then
892193326Sed      //      E1.E2 is an lvalue.
893193326Sed      //   -- Otherwise, if E1.E2 refers to a non-static member
894193326Sed      //      function [...], then E1.E2 is not an lvalue.
895193326Sed      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member))
896193326Sed        return Method->isStatic()? LV_Valid : LV_MemberFunction;
897193326Sed
898193326Sed      //   -- If E2 is a member enumerator [...], the expression E1.E2
899193326Sed      //      is not an lvalue.
900193326Sed      if (isa<EnumConstantDecl>(Member))
901193326Sed        return LV_InvalidExpression;
902193326Sed
903193326Sed        // Not an lvalue.
904193326Sed      return LV_InvalidExpression;
905198092Srdivacky    }
906193326Sed
907193326Sed    // C99 6.5.2.3p4
908193326Sed    return m->isArrow() ? LV_Valid : m->getBase()->isLvalue(Ctx);
909193326Sed  }
910193326Sed  case UnaryOperatorClass:
911193326Sed    if (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Deref)
912193326Sed      return LV_Valid; // C99 6.5.3p4
913193326Sed
914193326Sed    if (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Real ||
915193326Sed        cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Imag ||
916193326Sed        cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::Extension)
917193326Sed      return cast<UnaryOperator>(this)->getSubExpr()->isLvalue(Ctx);  // GNU.
918193326Sed
919193326Sed    if (Ctx.getLangOptions().CPlusPlus && // C++ [expr.pre.incr]p1
920193326Sed        (cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::PreInc ||
921193326Sed         cast<UnaryOperator>(this)->getOpcode() == UnaryOperator::PreDec))
922193326Sed      return LV_Valid;
923193326Sed    break;
924193326Sed  case ImplicitCastExprClass:
925198092Srdivacky    return cast<ImplicitCastExpr>(this)->isLvalueCast()? LV_Valid
926193326Sed                                                       : LV_InvalidExpression;
927193326Sed  case ParenExprClass: // C99 6.5.1p5
928193326Sed    return cast<ParenExpr>(this)->getSubExpr()->isLvalue(Ctx);
929193326Sed  case BinaryOperatorClass:
930193326Sed  case CompoundAssignOperatorClass: {
931193326Sed    const BinaryOperator *BinOp = cast<BinaryOperator>(this);
932193326Sed
933193326Sed    if (Ctx.getLangOptions().CPlusPlus && // C++ [expr.comma]p1
934193326Sed        BinOp->getOpcode() == BinaryOperator::Comma)
935193326Sed      return BinOp->getRHS()->isLvalue(Ctx);
936193326Sed
937193326Sed    // C++ [expr.mptr.oper]p6
938198092Srdivacky    // The result of a .* expression is an lvalue only if its first operand is
939198092Srdivacky    // an lvalue and its second operand is a pointer to data member.
940198092Srdivacky    if (BinOp->getOpcode() == BinaryOperator::PtrMemD &&
941193326Sed        !BinOp->getType()->isFunctionType())
942193326Sed      return BinOp->getLHS()->isLvalue(Ctx);
943193326Sed
944198092Srdivacky    // The result of an ->* expression is an lvalue only if its second operand
945198092Srdivacky    // is a pointer to data member.
946198092Srdivacky    if (BinOp->getOpcode() == BinaryOperator::PtrMemI &&
947198092Srdivacky        !BinOp->getType()->isFunctionType()) {
948198092Srdivacky      QualType Ty = BinOp->getRHS()->getType();
949198092Srdivacky      if (Ty->isMemberPointerType() && !Ty->isMemberFunctionPointerType())
950198092Srdivacky        return LV_Valid;
951198092Srdivacky    }
952198092Srdivacky
953193326Sed    if (!BinOp->isAssignmentOp())
954193326Sed      return LV_InvalidExpression;
955193326Sed
956193326Sed    if (Ctx.getLangOptions().CPlusPlus)
957198092Srdivacky      // C++ [expr.ass]p1:
958193326Sed      //   The result of an assignment operation [...] is an lvalue.
959193326Sed      return LV_Valid;
960193326Sed
961193326Sed
962193326Sed    // C99 6.5.16:
963193326Sed    //   An assignment expression [...] is not an lvalue.
964193326Sed    return LV_InvalidExpression;
965193326Sed  }
966198092Srdivacky  case CallExprClass:
967193326Sed  case CXXOperatorCallExprClass:
968193326Sed  case CXXMemberCallExprClass: {
969193326Sed    // C++0x [expr.call]p10
970193326Sed    //   A function call is an lvalue if and only if the result type
971193326Sed    //   is an lvalue reference.
972193326Sed    QualType ReturnType = cast<CallExpr>(this)->getCallReturnType();
973193326Sed    if (ReturnType->isLValueReferenceType())
974193326Sed      return LV_Valid;
975193326Sed
976193326Sed    break;
977193326Sed  }
978193326Sed  case CompoundLiteralExprClass: // C99 6.5.2.5p5
979193326Sed    return LV_Valid;
980193326Sed  case ChooseExprClass:
981193326Sed    // __builtin_choose_expr is an lvalue if the selected operand is.
982193326Sed    return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)->isLvalue(Ctx);
983193326Sed  case ExtVectorElementExprClass:
984193326Sed    if (cast<ExtVectorElementExpr>(this)->containsDuplicateElements())
985193326Sed      return LV_DuplicateVectorComponents;
986193326Sed    return LV_Valid;
987193326Sed  case ObjCIvarRefExprClass: // ObjC instance variables are lvalues.
988193326Sed    return LV_Valid;
989193326Sed  case ObjCPropertyRefExprClass: // FIXME: check if read-only property.
990193326Sed    return LV_Valid;
991198092Srdivacky  case ObjCImplicitSetterGetterRefExprClass: // FIXME: check if read-only property.
992193326Sed    return LV_Valid;
993193326Sed  case PredefinedExprClass:
994193326Sed    return LV_Valid;
995193326Sed  case CXXDefaultArgExprClass:
996193326Sed    return cast<CXXDefaultArgExpr>(this)->getExpr()->isLvalue(Ctx);
997193326Sed  case CXXConditionDeclExprClass:
998193326Sed    return LV_Valid;
999193326Sed  case CStyleCastExprClass:
1000193326Sed  case CXXFunctionalCastExprClass:
1001193326Sed  case CXXStaticCastExprClass:
1002193326Sed  case CXXDynamicCastExprClass:
1003193326Sed  case CXXReinterpretCastExprClass:
1004193326Sed  case CXXConstCastExprClass:
1005193326Sed    // The result of an explicit cast is an lvalue if the type we are
1006193326Sed    // casting to is an lvalue reference type. See C++ [expr.cast]p1,
1007193326Sed    // C++ [expr.static.cast]p2, C++ [expr.dynamic.cast]p2,
1008193326Sed    // C++ [expr.reinterpret.cast]p1, C++ [expr.const.cast]p1.
1009193326Sed    if (cast<ExplicitCastExpr>(this)->getTypeAsWritten()->
1010193326Sed          isLValueReferenceType())
1011193326Sed      return LV_Valid;
1012193326Sed    break;
1013193326Sed  case CXXTypeidExprClass:
1014193326Sed    // C++ 5.2.8p1: The result of a typeid expression is an lvalue of ...
1015193326Sed    return LV_Valid;
1016198092Srdivacky  case CXXBindTemporaryExprClass:
1017198092Srdivacky    return cast<CXXBindTemporaryExpr>(this)->getSubExpr()->
1018198092Srdivacky      isLvalueInternal(Ctx);
1019193326Sed  case ConditionalOperatorClass: {
1020193326Sed    // Complicated handling is only for C++.
1021193326Sed    if (!Ctx.getLangOptions().CPlusPlus)
1022193326Sed      return LV_InvalidExpression;
1023193326Sed
1024193326Sed    // Sema should have taken care to ensure that a CXXTemporaryObjectExpr is
1025193326Sed    // everywhere there's an object converted to an rvalue. Also, any other
1026193326Sed    // casts should be wrapped by ImplicitCastExprs. There's just the special
1027193326Sed    // case involving throws to work out.
1028193326Sed    const ConditionalOperator *Cond = cast<ConditionalOperator>(this);
1029193326Sed    Expr *True = Cond->getTrueExpr();
1030193326Sed    Expr *False = Cond->getFalseExpr();
1031193326Sed    // C++0x 5.16p2
1032193326Sed    //   If either the second or the third operand has type (cv) void, [...]
1033193326Sed    //   the result [...] is an rvalue.
1034193326Sed    if (True->getType()->isVoidType() || False->getType()->isVoidType())
1035193326Sed      return LV_InvalidExpression;
1036193326Sed
1037193326Sed    // Both sides must be lvalues for the result to be an lvalue.
1038193326Sed    if (True->isLvalue(Ctx) != LV_Valid || False->isLvalue(Ctx) != LV_Valid)
1039193326Sed      return LV_InvalidExpression;
1040193326Sed
1041193326Sed    // That's it.
1042193326Sed    return LV_Valid;
1043193326Sed  }
1044193326Sed
1045193326Sed  default:
1046193326Sed    break;
1047193326Sed  }
1048193326Sed  return LV_InvalidExpression;
1049193326Sed}
1050193326Sed
1051193326Sed/// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
1052193326Sed/// does not have an incomplete type, does not have a const-qualified type, and
1053198092Srdivacky/// if it is a structure or union, does not have any member (including,
1054193326Sed/// recursively, any member or element of all contained aggregates or unions)
1055193326Sed/// with a const-qualified type.
1056198092SrdivackyExpr::isModifiableLvalueResult
1057193326SedExpr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const {
1058193326Sed  isLvalueResult lvalResult = isLvalue(Ctx);
1059198092Srdivacky
1060193326Sed  switch (lvalResult) {
1061198092Srdivacky  case LV_Valid:
1062193326Sed    // C++ 3.10p11: Functions cannot be modified, but pointers to
1063193326Sed    // functions can be modifiable.
1064193326Sed    if (Ctx.getLangOptions().CPlusPlus && TR->isFunctionType())
1065193326Sed      return MLV_NotObjectType;
1066193326Sed    break;
1067193326Sed
1068193326Sed  case LV_NotObjectType: return MLV_NotObjectType;
1069193326Sed  case LV_IncompleteVoidType: return MLV_IncompleteVoidType;
1070193326Sed  case LV_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
1071193326Sed  case LV_InvalidExpression:
1072193326Sed    // If the top level is a C-style cast, and the subexpression is a valid
1073193326Sed    // lvalue, then this is probably a use of the old-school "cast as lvalue"
1074193326Sed    // GCC extension.  We don't support it, but we want to produce good
1075193326Sed    // diagnostics when it happens so that the user knows why.
1076193326Sed    if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(IgnoreParens())) {
1077193326Sed      if (CE->getSubExpr()->isLvalue(Ctx) == LV_Valid) {
1078193326Sed        if (Loc)
1079193326Sed          *Loc = CE->getLParenLoc();
1080193326Sed        return MLV_LValueCast;
1081193326Sed      }
1082193326Sed    }
1083193326Sed    return MLV_InvalidExpression;
1084193326Sed  case LV_MemberFunction: return MLV_MemberFunction;
1085193326Sed  }
1086193326Sed
1087193326Sed  // The following is illegal:
1088193326Sed  //   void takeclosure(void (^C)(void));
1089193326Sed  //   void func() { int x = 1; takeclosure(^{ x = 7; }); }
1090193326Sed  //
1091198092Srdivacky  if (const BlockDeclRefExpr *BDR = dyn_cast<BlockDeclRefExpr>(this)) {
1092193326Sed    if (!BDR->isByRef() && isa<VarDecl>(BDR->getDecl()))
1093193326Sed      return MLV_NotBlockQualified;
1094193326Sed  }
1095193326Sed
1096198092Srdivacky  // Assigning to an 'implicit' property?
1097198092Srdivacky  if (const ObjCImplicitSetterGetterRefExpr* Expr =
1098198092Srdivacky        dyn_cast<ObjCImplicitSetterGetterRefExpr>(this)) {
1099198092Srdivacky    if (Expr->getSetterMethod() == 0)
1100198092Srdivacky      return MLV_NoSetterProperty;
1101198092Srdivacky  }
1102198092Srdivacky
1103193326Sed  QualType CT = Ctx.getCanonicalType(getType());
1104198092Srdivacky
1105193326Sed  if (CT.isConstQualified())
1106193326Sed    return MLV_ConstQualified;
1107193326Sed  if (CT->isArrayType())
1108193326Sed    return MLV_ArrayType;
1109193326Sed  if (CT->isIncompleteType())
1110193326Sed    return MLV_IncompleteType;
1111198092Srdivacky
1112198092Srdivacky  if (const RecordType *r = CT->getAs<RecordType>()) {
1113198092Srdivacky    if (r->hasConstFields())
1114193326Sed      return MLV_ConstQualified;
1115193326Sed  }
1116193326Sed
1117198092Srdivacky  return MLV_Valid;
1118193326Sed}
1119193326Sed
1120193326Sed/// isOBJCGCCandidate - Check if an expression is objc gc'able.
1121198092Srdivacky/// returns true, if it is; false otherwise.
1122193326Sedbool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
1123193326Sed  switch (getStmtClass()) {
1124193326Sed  default:
1125193326Sed    return false;
1126193326Sed  case ObjCIvarRefExprClass:
1127193326Sed    return true;
1128193326Sed  case Expr::UnaryOperatorClass:
1129193326Sed    return cast<UnaryOperator>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1130193326Sed  case ParenExprClass:
1131193326Sed    return cast<ParenExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1132193326Sed  case ImplicitCastExprClass:
1133193326Sed    return cast<ImplicitCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1134193326Sed  case CStyleCastExprClass:
1135193326Sed    return cast<CStyleCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1136193326Sed  case DeclRefExprClass:
1137193326Sed  case QualifiedDeclRefExprClass: {
1138193326Sed    const Decl *D = cast<DeclRefExpr>(this)->getDecl();
1139193326Sed    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1140193326Sed      if (VD->hasGlobalStorage())
1141193326Sed        return true;
1142193326Sed      QualType T = VD->getType();
1143198092Srdivacky      // dereferencing to a  pointer is always a gc'able candidate,
1144198092Srdivacky      // unless it is __weak.
1145198092Srdivacky      return T->isPointerType() &&
1146198092Srdivacky             (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
1147193326Sed    }
1148193326Sed    return false;
1149193326Sed  }
1150193326Sed  case MemberExprClass: {
1151193326Sed    const MemberExpr *M = cast<MemberExpr>(this);
1152193326Sed    return M->getBase()->isOBJCGCCandidate(Ctx);
1153193326Sed  }
1154193326Sed  case ArraySubscriptExprClass:
1155193326Sed    return cast<ArraySubscriptExpr>(this)->getBase()->isOBJCGCCandidate(Ctx);
1156193326Sed  }
1157193326Sed}
1158193326SedExpr* Expr::IgnoreParens() {
1159193326Sed  Expr* E = this;
1160193326Sed  while (ParenExpr* P = dyn_cast<ParenExpr>(E))
1161193326Sed    E = P->getSubExpr();
1162198092Srdivacky
1163193326Sed  return E;
1164193326Sed}
1165193326Sed
1166193326Sed/// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
1167193326Sed/// or CastExprs or ImplicitCastExprs, returning their operand.
1168193326SedExpr *Expr::IgnoreParenCasts() {
1169193326Sed  Expr *E = this;
1170193326Sed  while (true) {
1171193326Sed    if (ParenExpr *P = dyn_cast<ParenExpr>(E))
1172193326Sed      E = P->getSubExpr();
1173193326Sed    else if (CastExpr *P = dyn_cast<CastExpr>(E))
1174193326Sed      E = P->getSubExpr();
1175193326Sed    else
1176193326Sed      return E;
1177193326Sed  }
1178193326Sed}
1179193326Sed
1180193326Sed/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
1181193326Sed/// value (including ptr->int casts of the same size).  Strip off any
1182193326Sed/// ParenExpr or CastExprs, returning their operand.
1183193326SedExpr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
1184193326Sed  Expr *E = this;
1185193326Sed  while (true) {
1186193326Sed    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1187193326Sed      E = P->getSubExpr();
1188193326Sed      continue;
1189193326Sed    }
1190198092Srdivacky
1191193326Sed    if (CastExpr *P = dyn_cast<CastExpr>(E)) {
1192193326Sed      // We ignore integer <-> casts that are of the same width, ptr<->ptr and
1193193326Sed      // ptr<->int casts of the same width.  We also ignore all identify casts.
1194193326Sed      Expr *SE = P->getSubExpr();
1195198092Srdivacky
1196193326Sed      if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
1197193326Sed        E = SE;
1198193326Sed        continue;
1199193326Sed      }
1200198092Srdivacky
1201193326Sed      if ((E->getType()->isPointerType() || E->getType()->isIntegralType()) &&
1202193326Sed          (SE->getType()->isPointerType() || SE->getType()->isIntegralType()) &&
1203193326Sed          Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
1204193326Sed        E = SE;
1205193326Sed        continue;
1206193326Sed      }
1207193326Sed    }
1208198092Srdivacky
1209193326Sed    return E;
1210193326Sed  }
1211193326Sed}
1212193326Sed
1213193326Sed
1214193326Sed/// hasAnyTypeDependentArguments - Determines if any of the expressions
1215193326Sed/// in Exprs is type-dependent.
1216193326Sedbool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) {
1217193326Sed  for (unsigned I = 0; I < NumExprs; ++I)
1218193326Sed    if (Exprs[I]->isTypeDependent())
1219193326Sed      return true;
1220193326Sed
1221193326Sed  return false;
1222193326Sed}
1223193326Sed
1224193326Sed/// hasAnyValueDependentArguments - Determines if any of the expressions
1225193326Sed/// in Exprs is value-dependent.
1226193326Sedbool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) {
1227193326Sed  for (unsigned I = 0; I < NumExprs; ++I)
1228193326Sed    if (Exprs[I]->isValueDependent())
1229193326Sed      return true;
1230193326Sed
1231193326Sed  return false;
1232193326Sed}
1233193326Sed
1234193326Sedbool Expr::isConstantInitializer(ASTContext &Ctx) const {
1235193326Sed  // This function is attempting whether an expression is an initializer
1236193326Sed  // which can be evaluated at compile-time.  isEvaluatable handles most
1237193326Sed  // of the cases, but it can't deal with some initializer-specific
1238193326Sed  // expressions, and it can't deal with aggregates; we deal with those here,
1239193326Sed  // and fall back to isEvaluatable for the other cases.
1240193326Sed
1241193326Sed  // FIXME: This function assumes the variable being assigned to
1242193326Sed  // isn't a reference type!
1243193326Sed
1244193326Sed  switch (getStmtClass()) {
1245193326Sed  default: break;
1246193326Sed  case StringLiteralClass:
1247198092Srdivacky  case ObjCStringLiteralClass:
1248193326Sed  case ObjCEncodeExprClass:
1249193326Sed    return true;
1250193326Sed  case CompoundLiteralExprClass: {
1251193326Sed    // This handles gcc's extension that allows global initializers like
1252193326Sed    // "struct x {int x;} x = (struct x) {};".
1253193326Sed    // FIXME: This accepts other cases it shouldn't!
1254193326Sed    const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
1255193326Sed    return Exp->isConstantInitializer(Ctx);
1256193326Sed  }
1257193326Sed  case InitListExprClass: {
1258193326Sed    // FIXME: This doesn't deal with fields with reference types correctly.
1259193326Sed    // FIXME: This incorrectly allows pointers cast to integers to be assigned
1260193326Sed    // to bitfields.
1261193326Sed    const InitListExpr *Exp = cast<InitListExpr>(this);
1262193326Sed    unsigned numInits = Exp->getNumInits();
1263193326Sed    for (unsigned i = 0; i < numInits; i++) {
1264198092Srdivacky      if (!Exp->getInit(i)->isConstantInitializer(Ctx))
1265193326Sed        return false;
1266193326Sed    }
1267193326Sed    return true;
1268193326Sed  }
1269193326Sed  case ImplicitValueInitExprClass:
1270193326Sed    return true;
1271198092Srdivacky  case ParenExprClass:
1272193326Sed    return cast<ParenExpr>(this)->getSubExpr()->isConstantInitializer(Ctx);
1273193326Sed  case UnaryOperatorClass: {
1274193326Sed    const UnaryOperator* Exp = cast<UnaryOperator>(this);
1275193326Sed    if (Exp->getOpcode() == UnaryOperator::Extension)
1276193326Sed      return Exp->getSubExpr()->isConstantInitializer(Ctx);
1277193326Sed    break;
1278193326Sed  }
1279198092Srdivacky  case BinaryOperatorClass: {
1280198092Srdivacky    // Special case &&foo - &&bar.  It would be nice to generalize this somehow
1281198092Srdivacky    // but this handles the common case.
1282198092Srdivacky    const BinaryOperator *Exp = cast<BinaryOperator>(this);
1283198092Srdivacky    if (Exp->getOpcode() == BinaryOperator::Sub &&
1284198092Srdivacky        isa<AddrLabelExpr>(Exp->getLHS()->IgnoreParenNoopCasts(Ctx)) &&
1285198092Srdivacky        isa<AddrLabelExpr>(Exp->getRHS()->IgnoreParenNoopCasts(Ctx)))
1286198092Srdivacky      return true;
1287198092Srdivacky    break;
1288198092Srdivacky  }
1289193326Sed  case ImplicitCastExprClass:
1290193326Sed  case CStyleCastExprClass:
1291193326Sed    // Handle casts with a destination that's a struct or union; this
1292193326Sed    // deals with both the gcc no-op struct cast extension and the
1293193326Sed    // cast-to-union extension.
1294193326Sed    if (getType()->isRecordType())
1295193326Sed      return cast<CastExpr>(this)->getSubExpr()->isConstantInitializer(Ctx);
1296198092Srdivacky
1297198092Srdivacky    // Integer->integer casts can be handled here, which is important for
1298198092Srdivacky    // things like (int)(&&x-&&y).  Scary but true.
1299198092Srdivacky    if (getType()->isIntegerType() &&
1300198092Srdivacky        cast<CastExpr>(this)->getSubExpr()->getType()->isIntegerType())
1301198092Srdivacky      return cast<CastExpr>(this)->getSubExpr()->isConstantInitializer(Ctx);
1302198092Srdivacky
1303193326Sed    break;
1304193326Sed  }
1305193326Sed  return isEvaluatable(Ctx);
1306193326Sed}
1307193326Sed
1308193326Sed/// isIntegerConstantExpr - this recursive routine will test if an expression is
1309193326Sed/// an integer constant expression.
1310193326Sed
1311193326Sed/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
1312193326Sed/// comma, etc
1313193326Sed///
1314193326Sed/// FIXME: Handle offsetof.  Two things to do:  Handle GCC's __builtin_offsetof
1315193326Sed/// to support gcc 4.0+  and handle the idiom GCC recognizes with a null pointer
1316193326Sed/// cast+dereference.
1317193326Sed
1318193326Sed// CheckICE - This function does the fundamental ICE checking: the returned
1319193326Sed// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
1320193326Sed// Note that to reduce code duplication, this helper does no evaluation
1321198092Srdivacky// itself; the caller checks whether the expression is evaluatable, and
1322193326Sed// in the rare cases where CheckICE actually cares about the evaluated
1323198092Srdivacky// value, it calls into Evalute.
1324193326Sed//
1325193326Sed// Meanings of Val:
1326193326Sed// 0: This expression is an ICE if it can be evaluated by Evaluate.
1327193326Sed// 1: This expression is not an ICE, but if it isn't evaluated, it's
1328193326Sed//    a legal subexpression for an ICE. This return value is used to handle
1329193326Sed//    the comma operator in C99 mode.
1330193326Sed// 2: This expression is not an ICE, and is not a legal subexpression for one.
1331193326Sed
1332193326Sedstruct ICEDiag {
1333193326Sed  unsigned Val;
1334193326Sed  SourceLocation Loc;
1335193326Sed
1336193326Sed  public:
1337193326Sed  ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
1338193326Sed  ICEDiag() : Val(0) {}
1339193326Sed};
1340193326Sed
1341193326SedICEDiag NoDiag() { return ICEDiag(); }
1342193326Sed
1343193326Sedstatic ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
1344193326Sed  Expr::EvalResult EVResult;
1345193326Sed  if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
1346193326Sed      !EVResult.Val.isInt()) {
1347193326Sed    return ICEDiag(2, E->getLocStart());
1348193326Sed  }
1349193326Sed  return NoDiag();
1350193326Sed}
1351193326Sed
1352193326Sedstatic ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
1353193326Sed  assert(!E->isValueDependent() && "Should not see value dependent exprs!");
1354193326Sed  if (!E->getType()->isIntegralType()) {
1355193326Sed    return ICEDiag(2, E->getLocStart());
1356193326Sed  }
1357193326Sed
1358193326Sed  switch (E->getStmtClass()) {
1359198092Srdivacky#define STMT(Node, Base) case Expr::Node##Class:
1360198092Srdivacky#define EXPR(Node, Base)
1361198092Srdivacky#include "clang/AST/StmtNodes.def"
1362198092Srdivacky  case Expr::PredefinedExprClass:
1363198092Srdivacky  case Expr::FloatingLiteralClass:
1364198092Srdivacky  case Expr::ImaginaryLiteralClass:
1365198092Srdivacky  case Expr::StringLiteralClass:
1366198092Srdivacky  case Expr::ArraySubscriptExprClass:
1367198092Srdivacky  case Expr::MemberExprClass:
1368198092Srdivacky  case Expr::CompoundAssignOperatorClass:
1369198092Srdivacky  case Expr::CompoundLiteralExprClass:
1370198092Srdivacky  case Expr::ExtVectorElementExprClass:
1371198092Srdivacky  case Expr::InitListExprClass:
1372198092Srdivacky  case Expr::DesignatedInitExprClass:
1373198092Srdivacky  case Expr::ImplicitValueInitExprClass:
1374198092Srdivacky  case Expr::ParenListExprClass:
1375198092Srdivacky  case Expr::VAArgExprClass:
1376198092Srdivacky  case Expr::AddrLabelExprClass:
1377198092Srdivacky  case Expr::StmtExprClass:
1378198092Srdivacky  case Expr::CXXMemberCallExprClass:
1379198092Srdivacky  case Expr::CXXDynamicCastExprClass:
1380198092Srdivacky  case Expr::CXXTypeidExprClass:
1381198092Srdivacky  case Expr::CXXNullPtrLiteralExprClass:
1382198092Srdivacky  case Expr::CXXThisExprClass:
1383198092Srdivacky  case Expr::CXXThrowExprClass:
1384198092Srdivacky  case Expr::CXXConditionDeclExprClass: // FIXME: is this correct?
1385198092Srdivacky  case Expr::CXXNewExprClass:
1386198092Srdivacky  case Expr::CXXDeleteExprClass:
1387198092Srdivacky  case Expr::CXXPseudoDestructorExprClass:
1388198092Srdivacky  case Expr::UnresolvedFunctionNameExprClass:
1389198092Srdivacky  case Expr::UnresolvedDeclRefExprClass:
1390198092Srdivacky  case Expr::TemplateIdRefExprClass:
1391198092Srdivacky  case Expr::CXXConstructExprClass:
1392198092Srdivacky  case Expr::CXXBindTemporaryExprClass:
1393198092Srdivacky  case Expr::CXXExprWithTemporariesClass:
1394198092Srdivacky  case Expr::CXXTemporaryObjectExprClass:
1395198092Srdivacky  case Expr::CXXUnresolvedConstructExprClass:
1396198092Srdivacky  case Expr::CXXUnresolvedMemberExprClass:
1397198092Srdivacky  case Expr::ObjCStringLiteralClass:
1398198092Srdivacky  case Expr::ObjCEncodeExprClass:
1399198092Srdivacky  case Expr::ObjCMessageExprClass:
1400198092Srdivacky  case Expr::ObjCSelectorExprClass:
1401198092Srdivacky  case Expr::ObjCProtocolExprClass:
1402198092Srdivacky  case Expr::ObjCIvarRefExprClass:
1403198092Srdivacky  case Expr::ObjCPropertyRefExprClass:
1404198092Srdivacky  case Expr::ObjCImplicitSetterGetterRefExprClass:
1405198092Srdivacky  case Expr::ObjCSuperExprClass:
1406198092Srdivacky  case Expr::ObjCIsaExprClass:
1407198092Srdivacky  case Expr::ShuffleVectorExprClass:
1408198092Srdivacky  case Expr::BlockExprClass:
1409198092Srdivacky  case Expr::BlockDeclRefExprClass:
1410198092Srdivacky  case Expr::NoStmtClass:
1411198092Srdivacky  case Expr::ExprClass:
1412193326Sed    return ICEDiag(2, E->getLocStart());
1413198092Srdivacky
1414198092Srdivacky  case Expr::GNUNullExprClass:
1415198092Srdivacky    // GCC considers the GNU __null value to be an integral constant expression.
1416198092Srdivacky    return NoDiag();
1417198092Srdivacky
1418193326Sed  case Expr::ParenExprClass:
1419193326Sed    return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
1420193326Sed  case Expr::IntegerLiteralClass:
1421193326Sed  case Expr::CharacterLiteralClass:
1422193326Sed  case Expr::CXXBoolLiteralExprClass:
1423193326Sed  case Expr::CXXZeroInitValueExprClass:
1424193326Sed  case Expr::TypesCompatibleExprClass:
1425193326Sed  case Expr::UnaryTypeTraitExprClass:
1426193326Sed    return NoDiag();
1427198092Srdivacky  case Expr::CallExprClass:
1428193326Sed  case Expr::CXXOperatorCallExprClass: {
1429193326Sed    const CallExpr *CE = cast<CallExpr>(E);
1430193326Sed    if (CE->isBuiltinCall(Ctx))
1431193326Sed      return CheckEvalInICE(E, Ctx);
1432193326Sed    return ICEDiag(2, E->getLocStart());
1433193326Sed  }
1434193326Sed  case Expr::DeclRefExprClass:
1435193326Sed  case Expr::QualifiedDeclRefExprClass:
1436193326Sed    if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
1437193326Sed      return NoDiag();
1438193326Sed    if (Ctx.getLangOptions().CPlusPlus &&
1439198092Srdivacky        E->getType().getCVRQualifiers() == Qualifiers::Const) {
1440193326Sed      // C++ 7.1.5.1p2
1441193326Sed      //   A variable of non-volatile const-qualified integral or enumeration
1442193326Sed      //   type initialized by an ICE can be used in ICEs.
1443193326Sed      if (const VarDecl *Dcl =
1444193326Sed              dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
1445193326Sed        if (Dcl->isInitKnownICE()) {
1446193326Sed          // We have already checked whether this subexpression is an
1447193326Sed          // integral constant expression.
1448193326Sed          if (Dcl->isInitICE())
1449193326Sed            return NoDiag();
1450193326Sed          else
1451193326Sed            return ICEDiag(2, E->getLocStart());
1452193326Sed        }
1453193326Sed
1454193326Sed        if (const Expr *Init = Dcl->getInit()) {
1455193326Sed          ICEDiag Result = CheckICE(Init, Ctx);
1456193326Sed          // Cache the result of the ICE test.
1457193326Sed          Dcl->setInitKnownICE(Ctx, Result.Val == 0);
1458193326Sed          return Result;
1459193326Sed        }
1460193326Sed      }
1461193326Sed    }
1462193326Sed    return ICEDiag(2, E->getLocStart());
1463193326Sed  case Expr::UnaryOperatorClass: {
1464193326Sed    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1465193326Sed    switch (Exp->getOpcode()) {
1466198092Srdivacky    case UnaryOperator::PostInc:
1467198092Srdivacky    case UnaryOperator::PostDec:
1468198092Srdivacky    case UnaryOperator::PreInc:
1469198092Srdivacky    case UnaryOperator::PreDec:
1470198092Srdivacky    case UnaryOperator::AddrOf:
1471198092Srdivacky    case UnaryOperator::Deref:
1472193326Sed      return ICEDiag(2, E->getLocStart());
1473198092Srdivacky
1474193326Sed    case UnaryOperator::Extension:
1475193326Sed    case UnaryOperator::LNot:
1476193326Sed    case UnaryOperator::Plus:
1477193326Sed    case UnaryOperator::Minus:
1478193326Sed    case UnaryOperator::Not:
1479193326Sed    case UnaryOperator::Real:
1480193326Sed    case UnaryOperator::Imag:
1481193326Sed      return CheckICE(Exp->getSubExpr(), Ctx);
1482193326Sed    case UnaryOperator::OffsetOf:
1483193326Sed      // Note that per C99, offsetof must be an ICE. And AFAIK, using
1484193326Sed      // Evaluate matches the proposed gcc behavior for cases like
1485193326Sed      // "offsetof(struct s{int x[4];}, x[!.0])".  This doesn't affect
1486193326Sed      // compliance: we should warn earlier for offsetof expressions with
1487193326Sed      // array subscripts that aren't ICEs, and if the array subscripts
1488193326Sed      // are ICEs, the value of the offsetof must be an integer constant.
1489193326Sed      return CheckEvalInICE(E, Ctx);
1490193326Sed    }
1491193326Sed  }
1492193326Sed  case Expr::SizeOfAlignOfExprClass: {
1493193326Sed    const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
1494193326Sed    if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
1495193326Sed      return ICEDiag(2, E->getLocStart());
1496193326Sed    return NoDiag();
1497193326Sed  }
1498193326Sed  case Expr::BinaryOperatorClass: {
1499193326Sed    const BinaryOperator *Exp = cast<BinaryOperator>(E);
1500193326Sed    switch (Exp->getOpcode()) {
1501198092Srdivacky    case BinaryOperator::PtrMemD:
1502198092Srdivacky    case BinaryOperator::PtrMemI:
1503198092Srdivacky    case BinaryOperator::Assign:
1504198092Srdivacky    case BinaryOperator::MulAssign:
1505198092Srdivacky    case BinaryOperator::DivAssign:
1506198092Srdivacky    case BinaryOperator::RemAssign:
1507198092Srdivacky    case BinaryOperator::AddAssign:
1508198092Srdivacky    case BinaryOperator::SubAssign:
1509198092Srdivacky    case BinaryOperator::ShlAssign:
1510198092Srdivacky    case BinaryOperator::ShrAssign:
1511198092Srdivacky    case BinaryOperator::AndAssign:
1512198092Srdivacky    case BinaryOperator::XorAssign:
1513198092Srdivacky    case BinaryOperator::OrAssign:
1514193326Sed      return ICEDiag(2, E->getLocStart());
1515198092Srdivacky
1516193326Sed    case BinaryOperator::Mul:
1517193326Sed    case BinaryOperator::Div:
1518193326Sed    case BinaryOperator::Rem:
1519193326Sed    case BinaryOperator::Add:
1520193326Sed    case BinaryOperator::Sub:
1521193326Sed    case BinaryOperator::Shl:
1522193326Sed    case BinaryOperator::Shr:
1523193326Sed    case BinaryOperator::LT:
1524193326Sed    case BinaryOperator::GT:
1525193326Sed    case BinaryOperator::LE:
1526193326Sed    case BinaryOperator::GE:
1527193326Sed    case BinaryOperator::EQ:
1528193326Sed    case BinaryOperator::NE:
1529193326Sed    case BinaryOperator::And:
1530193326Sed    case BinaryOperator::Xor:
1531193326Sed    case BinaryOperator::Or:
1532193326Sed    case BinaryOperator::Comma: {
1533193326Sed      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
1534193326Sed      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
1535193326Sed      if (Exp->getOpcode() == BinaryOperator::Div ||
1536193326Sed          Exp->getOpcode() == BinaryOperator::Rem) {
1537193326Sed        // Evaluate gives an error for undefined Div/Rem, so make sure
1538193326Sed        // we don't evaluate one.
1539193326Sed        if (LHSResult.Val != 2 && RHSResult.Val != 2) {
1540193326Sed          llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
1541193326Sed          if (REval == 0)
1542193326Sed            return ICEDiag(1, E->getLocStart());
1543193326Sed          if (REval.isSigned() && REval.isAllOnesValue()) {
1544193326Sed            llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
1545193326Sed            if (LEval.isMinSignedValue())
1546193326Sed              return ICEDiag(1, E->getLocStart());
1547193326Sed          }
1548193326Sed        }
1549193326Sed      }
1550193326Sed      if (Exp->getOpcode() == BinaryOperator::Comma) {
1551193326Sed        if (Ctx.getLangOptions().C99) {
1552193326Sed          // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
1553193326Sed          // if it isn't evaluated.
1554193326Sed          if (LHSResult.Val == 0 && RHSResult.Val == 0)
1555193326Sed            return ICEDiag(1, E->getLocStart());
1556193326Sed        } else {
1557193326Sed          // In both C89 and C++, commas in ICEs are illegal.
1558193326Sed          return ICEDiag(2, E->getLocStart());
1559193326Sed        }
1560193326Sed      }
1561193326Sed      if (LHSResult.Val >= RHSResult.Val)
1562193326Sed        return LHSResult;
1563193326Sed      return RHSResult;
1564193326Sed    }
1565193326Sed    case BinaryOperator::LAnd:
1566193326Sed    case BinaryOperator::LOr: {
1567193326Sed      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
1568193326Sed      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
1569193326Sed      if (LHSResult.Val == 0 && RHSResult.Val == 1) {
1570193326Sed        // Rare case where the RHS has a comma "side-effect"; we need
1571193326Sed        // to actually check the condition to see whether the side
1572193326Sed        // with the comma is evaluated.
1573193326Sed        if ((Exp->getOpcode() == BinaryOperator::LAnd) !=
1574193326Sed            (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
1575193326Sed          return RHSResult;
1576193326Sed        return NoDiag();
1577193326Sed      }
1578193326Sed
1579193326Sed      if (LHSResult.Val >= RHSResult.Val)
1580193326Sed        return LHSResult;
1581193326Sed      return RHSResult;
1582193326Sed    }
1583193326Sed    }
1584193326Sed  }
1585198092Srdivacky  case Expr::CastExprClass:
1586193326Sed  case Expr::ImplicitCastExprClass:
1587198092Srdivacky  case Expr::ExplicitCastExprClass:
1588193326Sed  case Expr::CStyleCastExprClass:
1589198092Srdivacky  case Expr::CXXFunctionalCastExprClass:
1590198092Srdivacky  case Expr::CXXNamedCastExprClass:
1591198092Srdivacky  case Expr::CXXStaticCastExprClass:
1592198092Srdivacky  case Expr::CXXReinterpretCastExprClass:
1593198092Srdivacky  case Expr::CXXConstCastExprClass: {
1594193326Sed    const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
1595193326Sed    if (SubExpr->getType()->isIntegralType())
1596193326Sed      return CheckICE(SubExpr, Ctx);
1597193326Sed    if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
1598193326Sed      return NoDiag();
1599193326Sed    return ICEDiag(2, E->getLocStart());
1600193326Sed  }
1601193326Sed  case Expr::ConditionalOperatorClass: {
1602193326Sed    const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
1603198092Srdivacky    // If the condition (ignoring parens) is a __builtin_constant_p call,
1604193326Sed    // then only the true side is actually considered in an integer constant
1605193326Sed    // expression, and it is fully evaluated.  This is an important GNU
1606193326Sed    // extension.  See GCC PR38377 for discussion.
1607193326Sed    if (const CallExpr *CallCE = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
1608193326Sed      if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
1609193326Sed        Expr::EvalResult EVResult;
1610193326Sed        if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
1611193326Sed            !EVResult.Val.isInt()) {
1612193326Sed          return ICEDiag(2, E->getLocStart());
1613193326Sed        }
1614193326Sed        return NoDiag();
1615193326Sed      }
1616193326Sed    ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
1617193326Sed    ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
1618193326Sed    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
1619193326Sed    if (CondResult.Val == 2)
1620193326Sed      return CondResult;
1621193326Sed    if (TrueResult.Val == 2)
1622193326Sed      return TrueResult;
1623193326Sed    if (FalseResult.Val == 2)
1624193326Sed      return FalseResult;
1625193326Sed    if (CondResult.Val == 1)
1626193326Sed      return CondResult;
1627193326Sed    if (TrueResult.Val == 0 && FalseResult.Val == 0)
1628193326Sed      return NoDiag();
1629193326Sed    // Rare case where the diagnostics depend on which side is evaluated
1630193326Sed    // Note that if we get here, CondResult is 0, and at least one of
1631193326Sed    // TrueResult and FalseResult is non-zero.
1632193326Sed    if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
1633193326Sed      return FalseResult;
1634193326Sed    }
1635193326Sed    return TrueResult;
1636193326Sed  }
1637193326Sed  case Expr::CXXDefaultArgExprClass:
1638193326Sed    return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
1639193326Sed  case Expr::ChooseExprClass: {
1640193326Sed    return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
1641193326Sed  }
1642193326Sed  }
1643198092Srdivacky
1644198092Srdivacky  // Silence a GCC warning
1645198092Srdivacky  return ICEDiag(2, E->getLocStart());
1646193326Sed}
1647193326Sed
1648193326Sedbool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
1649193326Sed                                 SourceLocation *Loc, bool isEvaluated) const {
1650193326Sed  ICEDiag d = CheckICE(this, Ctx);
1651193326Sed  if (d.Val != 0) {
1652193326Sed    if (Loc) *Loc = d.Loc;
1653193326Sed    return false;
1654193326Sed  }
1655193326Sed  EvalResult EvalResult;
1656193326Sed  if (!Evaluate(EvalResult, Ctx))
1657193326Sed    assert(0 && "ICE cannot be evaluated!");
1658193326Sed  assert(!EvalResult.HasSideEffects && "ICE with side effects!");
1659193326Sed  assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
1660193326Sed  Result = EvalResult.Val.getInt();
1661193326Sed  return true;
1662193326Sed}
1663193326Sed
1664193326Sed/// isNullPointerConstant - C99 6.3.2.3p3 -  Return true if this is either an
1665193326Sed/// integer constant expression with the value zero, or if this is one that is
1666193326Sed/// cast to void*.
1667198092Srdivackybool Expr::isNullPointerConstant(ASTContext &Ctx,
1668198092Srdivacky                                 NullPointerConstantValueDependence NPC) const {
1669198092Srdivacky  if (isValueDependent()) {
1670198092Srdivacky    switch (NPC) {
1671198092Srdivacky    case NPC_NeverValueDependent:
1672198092Srdivacky      assert(false && "Unexpected value dependent expression!");
1673198092Srdivacky      // If the unthinkable happens, fall through to the safest alternative.
1674198092Srdivacky
1675198092Srdivacky    case NPC_ValueDependentIsNull:
1676198092Srdivacky      return isTypeDependent() || getType()->isIntegralType();
1677198092Srdivacky
1678198092Srdivacky    case NPC_ValueDependentIsNotNull:
1679198092Srdivacky      return false;
1680198092Srdivacky    }
1681198092Srdivacky  }
1682198092Srdivacky
1683193326Sed  // Strip off a cast to void*, if it exists. Except in C++.
1684193326Sed  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
1685193326Sed    if (!Ctx.getLangOptions().CPlusPlus) {
1686193326Sed      // Check that it is a cast to void*.
1687198092Srdivacky      if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
1688193326Sed        QualType Pointee = PT->getPointeeType();
1689198092Srdivacky        if (!Pointee.hasQualifiers() &&
1690193326Sed            Pointee->isVoidType() &&                              // to void*
1691193326Sed            CE->getSubExpr()->getType()->isIntegerType())         // from int.
1692198092Srdivacky          return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
1693193326Sed      }
1694193326Sed    }
1695193326Sed  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
1696193326Sed    // Ignore the ImplicitCastExpr type entirely.
1697198092Srdivacky    return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
1698193326Sed  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
1699193326Sed    // Accept ((void*)0) as a null pointer constant, as many other
1700193326Sed    // implementations do.
1701198092Srdivacky    return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
1702198092Srdivacky  } else if (const CXXDefaultArgExpr *DefaultArg
1703193326Sed               = dyn_cast<CXXDefaultArgExpr>(this)) {
1704193326Sed    // See through default argument expressions
1705198092Srdivacky    return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
1706193326Sed  } else if (isa<GNUNullExpr>(this)) {
1707193326Sed    // The GNU __null extension is always a null pointer constant.
1708193326Sed    return true;
1709193326Sed  }
1710193326Sed
1711193326Sed  // C++0x nullptr_t is always a null pointer constant.
1712193326Sed  if (getType()->isNullPtrType())
1713193326Sed    return true;
1714193326Sed
1715193326Sed  // This expression must be an integer type.
1716198092Srdivacky  if (!getType()->isIntegerType() ||
1717198092Srdivacky      (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType()))
1718193326Sed    return false;
1719198092Srdivacky
1720193326Sed  // If we have an integer constant expression, we need to *evaluate* it and
1721193326Sed  // test for the value 0.
1722193326Sed  llvm::APSInt Result;
1723193326Sed  return isIntegerConstantExpr(Result, Ctx) && Result == 0;
1724193326Sed}
1725193326Sed
1726193326SedFieldDecl *Expr::getBitField() {
1727198092Srdivacky  Expr *E = this->IgnoreParens();
1728193326Sed
1729193326Sed  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
1730193326Sed    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
1731193326Sed      if (Field->isBitField())
1732193326Sed        return Field;
1733193326Sed
1734193326Sed  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E))
1735193326Sed    if (BinOp->isAssignmentOp() && BinOp->getLHS())
1736193326Sed      return BinOp->getLHS()->getBitField();
1737193326Sed
1738193326Sed  return 0;
1739193326Sed}
1740193326Sed
1741193326Sed/// isArrow - Return true if the base expression is a pointer to vector,
1742193326Sed/// return false if the base expression is a vector.
1743193326Sedbool ExtVectorElementExpr::isArrow() const {
1744193326Sed  return getBase()->getType()->isPointerType();
1745193326Sed}
1746193326Sed
1747193326Sedunsigned ExtVectorElementExpr::getNumElements() const {
1748198092Srdivacky  if (const VectorType *VT = getType()->getAs<VectorType>())
1749193326Sed    return VT->getNumElements();
1750193326Sed  return 1;
1751193326Sed}
1752193326Sed
1753193326Sed/// containsDuplicateElements - Return true if any element access is repeated.
1754193326Sedbool ExtVectorElementExpr::containsDuplicateElements() const {
1755198398Srdivacky  // FIXME: Refactor this code to an accessor on the AST node which returns the
1756198398Srdivacky  // "type" of component access, and share with code below and in Sema.
1757198398Srdivacky  llvm::StringRef Comp = Accessor->getName();
1758193326Sed
1759193326Sed  // Halving swizzles do not contain duplicate elements.
1760198398Srdivacky  if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
1761193326Sed    return false;
1762198092Srdivacky
1763193326Sed  // Advance past s-char prefix on hex swizzles.
1764198398Srdivacky  if (Comp[0] == 's' || Comp[0] == 'S')
1765198398Srdivacky    Comp = Comp.substr(1);
1766198092Srdivacky
1767198398Srdivacky  for (unsigned i = 0, e = Comp.size(); i != e; ++i)
1768198398Srdivacky    if (Comp.substr(i + 1).find(Comp[i]) != llvm::StringRef::npos)
1769193326Sed        return true;
1770198398Srdivacky
1771193326Sed  return false;
1772193326Sed}
1773193326Sed
1774193326Sed/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
1775193326Sedvoid ExtVectorElementExpr::getEncodedElementAccess(
1776193326Sed                                  llvm::SmallVectorImpl<unsigned> &Elts) const {
1777198398Srdivacky  llvm::StringRef Comp = Accessor->getName();
1778198398Srdivacky  if (Comp[0] == 's' || Comp[0] == 'S')
1779198398Srdivacky    Comp = Comp.substr(1);
1780198092Srdivacky
1781198398Srdivacky  bool isHi =   Comp == "hi";
1782198398Srdivacky  bool isLo =   Comp == "lo";
1783198398Srdivacky  bool isEven = Comp == "even";
1784198398Srdivacky  bool isOdd  = Comp == "odd";
1785198092Srdivacky
1786193326Sed  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
1787193326Sed    uint64_t Index;
1788198092Srdivacky
1789193326Sed    if (isHi)
1790193326Sed      Index = e + i;
1791193326Sed    else if (isLo)
1792193326Sed      Index = i;
1793193326Sed    else if (isEven)
1794193326Sed      Index = 2 * i;
1795193326Sed    else if (isOdd)
1796193326Sed      Index = 2 * i + 1;
1797193326Sed    else
1798198398Srdivacky      Index = ExtVectorType::getAccessorIdx(Comp[i]);
1799193326Sed
1800193326Sed    Elts.push_back(Index);
1801193326Sed  }
1802193326Sed}
1803193326Sed
1804193326Sed// constructor for instance messages.
1805193326SedObjCMessageExpr::ObjCMessageExpr(Expr *receiver, Selector selInfo,
1806193326Sed                QualType retType, ObjCMethodDecl *mproto,
1807193326Sed                SourceLocation LBrac, SourceLocation RBrac,
1808193326Sed                Expr **ArgExprs, unsigned nargs)
1809198092Srdivacky  : Expr(ObjCMessageExprClass, retType), SelName(selInfo),
1810193326Sed    MethodProto(mproto) {
1811193326Sed  NumArgs = nargs;
1812193326Sed  SubExprs = new Stmt*[NumArgs+1];
1813193326Sed  SubExprs[RECEIVER] = receiver;
1814193326Sed  if (NumArgs) {
1815193326Sed    for (unsigned i = 0; i != NumArgs; ++i)
1816193326Sed      SubExprs[i+ARGS_START] = static_cast<Expr *>(ArgExprs[i]);
1817193326Sed  }
1818193326Sed  LBracloc = LBrac;
1819193326Sed  RBracloc = RBrac;
1820193326Sed}
1821193326Sed
1822198092Srdivacky// constructor for class messages.
1823193326Sed// FIXME: clsName should be typed to ObjCInterfaceType
1824193326SedObjCMessageExpr::ObjCMessageExpr(IdentifierInfo *clsName, Selector selInfo,
1825193326Sed                QualType retType, ObjCMethodDecl *mproto,
1826193326Sed                SourceLocation LBrac, SourceLocation RBrac,
1827193326Sed                Expr **ArgExprs, unsigned nargs)
1828198092Srdivacky  : Expr(ObjCMessageExprClass, retType), SelName(selInfo),
1829193326Sed    MethodProto(mproto) {
1830193326Sed  NumArgs = nargs;
1831193326Sed  SubExprs = new Stmt*[NumArgs+1];
1832193326Sed  SubExprs[RECEIVER] = (Expr*) ((uintptr_t) clsName | IsClsMethDeclUnknown);
1833193326Sed  if (NumArgs) {
1834193326Sed    for (unsigned i = 0; i != NumArgs; ++i)
1835193326Sed      SubExprs[i+ARGS_START] = static_cast<Expr *>(ArgExprs[i]);
1836193326Sed  }
1837193326Sed  LBracloc = LBrac;
1838193326Sed  RBracloc = RBrac;
1839193326Sed}
1840193326Sed
1841198092Srdivacky// constructor for class messages.
1842193326SedObjCMessageExpr::ObjCMessageExpr(ObjCInterfaceDecl *cls, Selector selInfo,
1843193326Sed                                 QualType retType, ObjCMethodDecl *mproto,
1844193326Sed                                 SourceLocation LBrac, SourceLocation RBrac,
1845193326Sed                                 Expr **ArgExprs, unsigned nargs)
1846198092Srdivacky: Expr(ObjCMessageExprClass, retType), SelName(selInfo),
1847193326SedMethodProto(mproto) {
1848193326Sed  NumArgs = nargs;
1849193326Sed  SubExprs = new Stmt*[NumArgs+1];
1850193326Sed  SubExprs[RECEIVER] = (Expr*) ((uintptr_t) cls | IsClsMethDeclKnown);
1851193326Sed  if (NumArgs) {
1852193326Sed    for (unsigned i = 0; i != NumArgs; ++i)
1853193326Sed      SubExprs[i+ARGS_START] = static_cast<Expr *>(ArgExprs[i]);
1854193326Sed  }
1855193326Sed  LBracloc = LBrac;
1856193326Sed  RBracloc = RBrac;
1857193326Sed}
1858193326Sed
1859193326SedObjCMessageExpr::ClassInfo ObjCMessageExpr::getClassInfo() const {
1860193326Sed  uintptr_t x = (uintptr_t) SubExprs[RECEIVER];
1861193326Sed  switch (x & Flags) {
1862193326Sed    default:
1863193326Sed      assert(false && "Invalid ObjCMessageExpr.");
1864193326Sed    case IsInstMeth:
1865193326Sed      return ClassInfo(0, 0);
1866193326Sed    case IsClsMethDeclUnknown:
1867193326Sed      return ClassInfo(0, (IdentifierInfo*) (x & ~Flags));
1868193326Sed    case IsClsMethDeclKnown: {
1869193326Sed      ObjCInterfaceDecl* D = (ObjCInterfaceDecl*) (x & ~Flags);
1870193326Sed      return ClassInfo(D, D->getIdentifier());
1871193326Sed    }
1872193326Sed  }
1873193326Sed}
1874193326Sed
1875193326Sedvoid ObjCMessageExpr::setClassInfo(const ObjCMessageExpr::ClassInfo &CI) {
1876193326Sed  if (CI.first == 0 && CI.second == 0)
1877193326Sed    SubExprs[RECEIVER] = (Expr*)((uintptr_t)0 | IsInstMeth);
1878193326Sed  else if (CI.first == 0)
1879193326Sed    SubExprs[RECEIVER] = (Expr*)((uintptr_t)CI.second | IsClsMethDeclUnknown);
1880193326Sed  else
1881193326Sed    SubExprs[RECEIVER] = (Expr*)((uintptr_t)CI.first | IsClsMethDeclKnown);
1882193326Sed}
1883193326Sed
1884193326Sed
1885193326Sedbool ChooseExpr::isConditionTrue(ASTContext &C) const {
1886193326Sed  return getCond()->EvaluateAsInt(C) != 0;
1887193326Sed}
1888193326Sed
1889198092Srdivackyvoid ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
1890198092Srdivacky                                 unsigned NumExprs) {
1891198092Srdivacky  if (SubExprs) C.Deallocate(SubExprs);
1892198092Srdivacky
1893198092Srdivacky  SubExprs = new (C) Stmt* [NumExprs];
1894193326Sed  this->NumExprs = NumExprs;
1895193326Sed  memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
1896193326Sed}
1897193326Sed
1898198092Srdivackyvoid ShuffleVectorExpr::DoDestroy(ASTContext& C) {
1899198092Srdivacky  DestroyChildren(C);
1900198092Srdivacky  if (SubExprs) C.Deallocate(SubExprs);
1901198092Srdivacky  this->~ShuffleVectorExpr();
1902198092Srdivacky  C.Deallocate(this);
1903198092Srdivacky}
1904198092Srdivacky
1905198092Srdivackyvoid SizeOfAlignOfExpr::DoDestroy(ASTContext& C) {
1906193326Sed  // Override default behavior of traversing children. If this has a type
1907193326Sed  // operand and the type is a variable-length array, the child iteration
1908193326Sed  // will iterate over the size expression. However, this expression belongs
1909193326Sed  // to the type, not to this, so we don't want to delete it.
1910193326Sed  // We still want to delete this expression.
1911193326Sed  if (isArgumentType()) {
1912193326Sed    this->~SizeOfAlignOfExpr();
1913193326Sed    C.Deallocate(this);
1914193326Sed  }
1915193326Sed  else
1916198092Srdivacky    Expr::DoDestroy(C);
1917193326Sed}
1918193326Sed
1919193326Sed//===----------------------------------------------------------------------===//
1920193326Sed//  DesignatedInitExpr
1921193326Sed//===----------------------------------------------------------------------===//
1922193326Sed
1923193326SedIdentifierInfo *DesignatedInitExpr::Designator::getFieldName() {
1924193326Sed  assert(Kind == FieldDesignator && "Only valid on a field designator");
1925193326Sed  if (Field.NameOrField & 0x01)
1926193326Sed    return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
1927193326Sed  else
1928193326Sed    return getField()->getIdentifier();
1929193326Sed}
1930193326Sed
1931198092SrdivackyDesignatedInitExpr::DesignatedInitExpr(QualType Ty, unsigned NumDesignators,
1932193326Sed                                       const Designator *Designators,
1933198092Srdivacky                                       SourceLocation EqualOrColonLoc,
1934193326Sed                                       bool GNUSyntax,
1935198092Srdivacky                                       Expr **IndexExprs,
1936193326Sed                                       unsigned NumIndexExprs,
1937193326Sed                                       Expr *Init)
1938198092Srdivacky  : Expr(DesignatedInitExprClass, Ty,
1939193326Sed         Init->isTypeDependent(), Init->isValueDependent()),
1940198092Srdivacky    EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
1941198092Srdivacky    NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) {
1942193326Sed  this->Designators = new Designator[NumDesignators];
1943193326Sed
1944193326Sed  // Record the initializer itself.
1945193326Sed  child_iterator Child = child_begin();
1946193326Sed  *Child++ = Init;
1947193326Sed
1948193326Sed  // Copy the designators and their subexpressions, computing
1949193326Sed  // value-dependence along the way.
1950193326Sed  unsigned IndexIdx = 0;
1951193326Sed  for (unsigned I = 0; I != NumDesignators; ++I) {
1952193326Sed    this->Designators[I] = Designators[I];
1953193326Sed
1954193326Sed    if (this->Designators[I].isArrayDesignator()) {
1955193326Sed      // Compute type- and value-dependence.
1956193326Sed      Expr *Index = IndexExprs[IndexIdx];
1957198092Srdivacky      ValueDependent = ValueDependent ||
1958193326Sed        Index->isTypeDependent() || Index->isValueDependent();
1959193326Sed
1960193326Sed      // Copy the index expressions into permanent storage.
1961193326Sed      *Child++ = IndexExprs[IndexIdx++];
1962193326Sed    } else if (this->Designators[I].isArrayRangeDesignator()) {
1963193326Sed      // Compute type- and value-dependence.
1964193326Sed      Expr *Start = IndexExprs[IndexIdx];
1965193326Sed      Expr *End = IndexExprs[IndexIdx + 1];
1966198092Srdivacky      ValueDependent = ValueDependent ||
1967193326Sed        Start->isTypeDependent() || Start->isValueDependent() ||
1968193326Sed        End->isTypeDependent() || End->isValueDependent();
1969193326Sed
1970193326Sed      // Copy the start/end expressions into permanent storage.
1971193326Sed      *Child++ = IndexExprs[IndexIdx++];
1972193326Sed      *Child++ = IndexExprs[IndexIdx++];
1973193326Sed    }
1974193326Sed  }
1975193326Sed
1976193326Sed  assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions");
1977193326Sed}
1978193326Sed
1979193326SedDesignatedInitExpr *
1980198092SrdivackyDesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
1981193326Sed                           unsigned NumDesignators,
1982193326Sed                           Expr **IndexExprs, unsigned NumIndexExprs,
1983193326Sed                           SourceLocation ColonOrEqualLoc,
1984193326Sed                           bool UsesColonSyntax, Expr *Init) {
1985193326Sed  void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
1986193326Sed                         sizeof(Stmt *) * (NumIndexExprs + 1), 8);
1987193326Sed  return new (Mem) DesignatedInitExpr(C.VoidTy, NumDesignators, Designators,
1988193326Sed                                      ColonOrEqualLoc, UsesColonSyntax,
1989193326Sed                                      IndexExprs, NumIndexExprs, Init);
1990193326Sed}
1991193326Sed
1992198092SrdivackyDesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
1993193326Sed                                                    unsigned NumIndexExprs) {
1994193326Sed  void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
1995193326Sed                         sizeof(Stmt *) * (NumIndexExprs + 1), 8);
1996193326Sed  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
1997193326Sed}
1998193326Sed
1999198092Srdivackyvoid DesignatedInitExpr::setDesignators(const Designator *Desigs,
2000193326Sed                                        unsigned NumDesigs) {
2001193326Sed  if (Designators)
2002193326Sed    delete [] Designators;
2003193326Sed
2004193326Sed  Designators = new Designator[NumDesigs];
2005193326Sed  NumDesignators = NumDesigs;
2006193326Sed  for (unsigned I = 0; I != NumDesigs; ++I)
2007193326Sed    Designators[I] = Desigs[I];
2008193326Sed}
2009193326Sed
2010193326SedSourceRange DesignatedInitExpr::getSourceRange() const {
2011193326Sed  SourceLocation StartLoc;
2012193326Sed  Designator &First =
2013193326Sed    *const_cast<DesignatedInitExpr*>(this)->designators_begin();
2014193326Sed  if (First.isFieldDesignator()) {
2015193326Sed    if (GNUSyntax)
2016193326Sed      StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
2017193326Sed    else
2018193326Sed      StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
2019193326Sed  } else
2020193326Sed    StartLoc =
2021193326Sed      SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
2022193326Sed  return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
2023193326Sed}
2024193326Sed
2025193326SedExpr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
2026193326Sed  assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
2027193326Sed  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2028193326Sed  Ptr += sizeof(DesignatedInitExpr);
2029193326Sed  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2030193326Sed  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2031193326Sed}
2032193326Sed
2033193326SedExpr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
2034198092Srdivacky  assert(D.Kind == Designator::ArrayRangeDesignator &&
2035193326Sed         "Requires array range designator");
2036193326Sed  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2037193326Sed  Ptr += sizeof(DesignatedInitExpr);
2038193326Sed  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2039193326Sed  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2040193326Sed}
2041193326Sed
2042193326SedExpr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
2043198092Srdivacky  assert(D.Kind == Designator::ArrayRangeDesignator &&
2044193326Sed         "Requires array range designator");
2045193326Sed  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2046193326Sed  Ptr += sizeof(DesignatedInitExpr);
2047193326Sed  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2048193326Sed  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
2049193326Sed}
2050193326Sed
2051193326Sed/// \brief Replaces the designator at index @p Idx with the series
2052193326Sed/// of designators in [First, Last).
2053198092Srdivackyvoid DesignatedInitExpr::ExpandDesignator(unsigned Idx,
2054198092Srdivacky                                          const Designator *First,
2055193326Sed                                          const Designator *Last) {
2056193326Sed  unsigned NumNewDesignators = Last - First;
2057193326Sed  if (NumNewDesignators == 0) {
2058193326Sed    std::copy_backward(Designators + Idx + 1,
2059193326Sed                       Designators + NumDesignators,
2060193326Sed                       Designators + Idx);
2061193326Sed    --NumNewDesignators;
2062193326Sed    return;
2063193326Sed  } else if (NumNewDesignators == 1) {
2064193326Sed    Designators[Idx] = *First;
2065193326Sed    return;
2066193326Sed  }
2067193326Sed
2068198092Srdivacky  Designator *NewDesignators
2069193326Sed    = new Designator[NumDesignators - 1 + NumNewDesignators];
2070193326Sed  std::copy(Designators, Designators + Idx, NewDesignators);
2071193326Sed  std::copy(First, Last, NewDesignators + Idx);
2072193326Sed  std::copy(Designators + Idx + 1, Designators + NumDesignators,
2073193326Sed            NewDesignators + Idx + NumNewDesignators);
2074193326Sed  delete [] Designators;
2075193326Sed  Designators = NewDesignators;
2076193326Sed  NumDesignators = NumDesignators - 1 + NumNewDesignators;
2077193326Sed}
2078193326Sed
2079198092Srdivackyvoid DesignatedInitExpr::DoDestroy(ASTContext &C) {
2080193326Sed  delete [] Designators;
2081198092Srdivacky  Expr::DoDestroy(C);
2082193326Sed}
2083193326Sed
2084198092SrdivackyParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
2085198092Srdivacky                             Expr **exprs, unsigned nexprs,
2086198092Srdivacky                             SourceLocation rparenloc)
2087198092Srdivacky: Expr(ParenListExprClass, QualType(),
2088198092Srdivacky       hasAnyTypeDependentArguments(exprs, nexprs),
2089198092Srdivacky       hasAnyValueDependentArguments(exprs, nexprs)),
2090198092Srdivacky  NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
2091198092Srdivacky
2092198092Srdivacky  Exprs = new (C) Stmt*[nexprs];
2093198092Srdivacky  for (unsigned i = 0; i != nexprs; ++i)
2094198092Srdivacky    Exprs[i] = exprs[i];
2095193326Sed}
2096193326Sed
2097198092Srdivackyvoid ParenListExpr::DoDestroy(ASTContext& C) {
2098198092Srdivacky  DestroyChildren(C);
2099198092Srdivacky  if (Exprs) C.Deallocate(Exprs);
2100198092Srdivacky  this->~ParenListExpr();
2101198092Srdivacky  C.Deallocate(this);
2102198092Srdivacky}
2103198092Srdivacky
2104193326Sed//===----------------------------------------------------------------------===//
2105193326Sed//  ExprIterator.
2106193326Sed//===----------------------------------------------------------------------===//
2107193326Sed
2108193326SedExpr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
2109193326SedExpr* ExprIterator::operator*() const { return cast<Expr>(*I); }
2110193326SedExpr* ExprIterator::operator->() const { return cast<Expr>(*I); }
2111193326Sedconst Expr* ConstExprIterator::operator[](size_t idx) const {
2112193326Sed  return cast<Expr>(I[idx]);
2113193326Sed}
2114193326Sedconst Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
2115193326Sedconst Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
2116193326Sed
2117193326Sed//===----------------------------------------------------------------------===//
2118193326Sed//  Child Iterators for iterating over subexpressions/substatements
2119193326Sed//===----------------------------------------------------------------------===//
2120193326Sed
2121193326Sed// DeclRefExpr
2122193326SedStmt::child_iterator DeclRefExpr::child_begin() { return child_iterator(); }
2123193326SedStmt::child_iterator DeclRefExpr::child_end() { return child_iterator(); }
2124193326Sed
2125193326Sed// ObjCIvarRefExpr
2126193326SedStmt::child_iterator ObjCIvarRefExpr::child_begin() { return &Base; }
2127193326SedStmt::child_iterator ObjCIvarRefExpr::child_end() { return &Base+1; }
2128193326Sed
2129193326Sed// ObjCPropertyRefExpr
2130193326SedStmt::child_iterator ObjCPropertyRefExpr::child_begin() { return &Base; }
2131193326SedStmt::child_iterator ObjCPropertyRefExpr::child_end() { return &Base+1; }
2132193326Sed
2133198092Srdivacky// ObjCImplicitSetterGetterRefExpr
2134198092SrdivackyStmt::child_iterator ObjCImplicitSetterGetterRefExpr::child_begin() {
2135198092Srdivacky  return &Base;
2136198092Srdivacky}
2137198092SrdivackyStmt::child_iterator ObjCImplicitSetterGetterRefExpr::child_end() {
2138198092Srdivacky  return &Base+1;
2139198092Srdivacky}
2140193326Sed
2141193326Sed// ObjCSuperExpr
2142193326SedStmt::child_iterator ObjCSuperExpr::child_begin() { return child_iterator(); }
2143193326SedStmt::child_iterator ObjCSuperExpr::child_end() { return child_iterator(); }
2144193326Sed
2145198092Srdivacky// ObjCIsaExpr
2146198092SrdivackyStmt::child_iterator ObjCIsaExpr::child_begin() { return &Base; }
2147198092SrdivackyStmt::child_iterator ObjCIsaExpr::child_end() { return &Base+1; }
2148198092Srdivacky
2149193326Sed// PredefinedExpr
2150193326SedStmt::child_iterator PredefinedExpr::child_begin() { return child_iterator(); }
2151193326SedStmt::child_iterator PredefinedExpr::child_end() { return child_iterator(); }
2152193326Sed
2153193326Sed// IntegerLiteral
2154193326SedStmt::child_iterator IntegerLiteral::child_begin() { return child_iterator(); }
2155193326SedStmt::child_iterator IntegerLiteral::child_end() { return child_iterator(); }
2156193326Sed
2157193326Sed// CharacterLiteral
2158193326SedStmt::child_iterator CharacterLiteral::child_begin() { return child_iterator();}
2159193326SedStmt::child_iterator CharacterLiteral::child_end() { return child_iterator(); }
2160193326Sed
2161193326Sed// FloatingLiteral
2162193326SedStmt::child_iterator FloatingLiteral::child_begin() { return child_iterator(); }
2163193326SedStmt::child_iterator FloatingLiteral::child_end() { return child_iterator(); }
2164193326Sed
2165193326Sed// ImaginaryLiteral
2166193326SedStmt::child_iterator ImaginaryLiteral::child_begin() { return &Val; }
2167193326SedStmt::child_iterator ImaginaryLiteral::child_end() { return &Val+1; }
2168193326Sed
2169193326Sed// StringLiteral
2170193326SedStmt::child_iterator StringLiteral::child_begin() { return child_iterator(); }
2171193326SedStmt::child_iterator StringLiteral::child_end() { return child_iterator(); }
2172193326Sed
2173193326Sed// ParenExpr
2174193326SedStmt::child_iterator ParenExpr::child_begin() { return &Val; }
2175193326SedStmt::child_iterator ParenExpr::child_end() { return &Val+1; }
2176193326Sed
2177193326Sed// UnaryOperator
2178193326SedStmt::child_iterator UnaryOperator::child_begin() { return &Val; }
2179193326SedStmt::child_iterator UnaryOperator::child_end() { return &Val+1; }
2180193326Sed
2181193326Sed// SizeOfAlignOfExpr
2182198092SrdivackyStmt::child_iterator SizeOfAlignOfExpr::child_begin() {
2183193326Sed  // If this is of a type and the type is a VLA type (and not a typedef), the
2184193326Sed  // size expression of the VLA needs to be treated as an executable expression.
2185193326Sed  // Why isn't this weirdness documented better in StmtIterator?
2186193326Sed  if (isArgumentType()) {
2187193326Sed    if (VariableArrayType* T = dyn_cast<VariableArrayType>(
2188193326Sed                                   getArgumentType().getTypePtr()))
2189193326Sed      return child_iterator(T);
2190193326Sed    return child_iterator();
2191193326Sed  }
2192193326Sed  return child_iterator(&Argument.Ex);
2193193326Sed}
2194193326SedStmt::child_iterator SizeOfAlignOfExpr::child_end() {
2195193326Sed  if (isArgumentType())
2196193326Sed    return child_iterator();
2197193326Sed  return child_iterator(&Argument.Ex + 1);
2198193326Sed}
2199193326Sed
2200193326Sed// ArraySubscriptExpr
2201193326SedStmt::child_iterator ArraySubscriptExpr::child_begin() {
2202193326Sed  return &SubExprs[0];
2203193326Sed}
2204193326SedStmt::child_iterator ArraySubscriptExpr::child_end() {
2205193326Sed  return &SubExprs[0]+END_EXPR;
2206193326Sed}
2207193326Sed
2208193326Sed// CallExpr
2209193326SedStmt::child_iterator CallExpr::child_begin() {
2210193326Sed  return &SubExprs[0];
2211193326Sed}
2212193326SedStmt::child_iterator CallExpr::child_end() {
2213193326Sed  return &SubExprs[0]+NumArgs+ARGS_START;
2214193326Sed}
2215193326Sed
2216193326Sed// MemberExpr
2217193326SedStmt::child_iterator MemberExpr::child_begin() { return &Base; }
2218193326SedStmt::child_iterator MemberExpr::child_end() { return &Base+1; }
2219193326Sed
2220193326Sed// ExtVectorElementExpr
2221193326SedStmt::child_iterator ExtVectorElementExpr::child_begin() { return &Base; }
2222193326SedStmt::child_iterator ExtVectorElementExpr::child_end() { return &Base+1; }
2223193326Sed
2224193326Sed// CompoundLiteralExpr
2225193326SedStmt::child_iterator CompoundLiteralExpr::child_begin() { return &Init; }
2226193326SedStmt::child_iterator CompoundLiteralExpr::child_end() { return &Init+1; }
2227193326Sed
2228193326Sed// CastExpr
2229193326SedStmt::child_iterator CastExpr::child_begin() { return &Op; }
2230193326SedStmt::child_iterator CastExpr::child_end() { return &Op+1; }
2231193326Sed
2232193326Sed// BinaryOperator
2233193326SedStmt::child_iterator BinaryOperator::child_begin() {
2234193326Sed  return &SubExprs[0];
2235193326Sed}
2236193326SedStmt::child_iterator BinaryOperator::child_end() {
2237193326Sed  return &SubExprs[0]+END_EXPR;
2238193326Sed}
2239193326Sed
2240193326Sed// ConditionalOperator
2241193326SedStmt::child_iterator ConditionalOperator::child_begin() {
2242193326Sed  return &SubExprs[0];
2243193326Sed}
2244193326SedStmt::child_iterator ConditionalOperator::child_end() {
2245193326Sed  return &SubExprs[0]+END_EXPR;
2246193326Sed}
2247193326Sed
2248193326Sed// AddrLabelExpr
2249193326SedStmt::child_iterator AddrLabelExpr::child_begin() { return child_iterator(); }
2250193326SedStmt::child_iterator AddrLabelExpr::child_end() { return child_iterator(); }
2251193326Sed
2252193326Sed// StmtExpr
2253193326SedStmt::child_iterator StmtExpr::child_begin() { return &SubStmt; }
2254193326SedStmt::child_iterator StmtExpr::child_end() { return &SubStmt+1; }
2255193326Sed
2256193326Sed// TypesCompatibleExpr
2257193326SedStmt::child_iterator TypesCompatibleExpr::child_begin() {
2258193326Sed  return child_iterator();
2259193326Sed}
2260193326Sed
2261193326SedStmt::child_iterator TypesCompatibleExpr::child_end() {
2262193326Sed  return child_iterator();
2263193326Sed}
2264193326Sed
2265193326Sed// ChooseExpr
2266193326SedStmt::child_iterator ChooseExpr::child_begin() { return &SubExprs[0]; }
2267193326SedStmt::child_iterator ChooseExpr::child_end() { return &SubExprs[0]+END_EXPR; }
2268193326Sed
2269193326Sed// GNUNullExpr
2270193326SedStmt::child_iterator GNUNullExpr::child_begin() { return child_iterator(); }
2271193326SedStmt::child_iterator GNUNullExpr::child_end() { return child_iterator(); }
2272193326Sed
2273193326Sed// ShuffleVectorExpr
2274193326SedStmt::child_iterator ShuffleVectorExpr::child_begin() {
2275193326Sed  return &SubExprs[0];
2276193326Sed}
2277193326SedStmt::child_iterator ShuffleVectorExpr::child_end() {
2278193326Sed  return &SubExprs[0]+NumExprs;
2279193326Sed}
2280193326Sed
2281193326Sed// VAArgExpr
2282193326SedStmt::child_iterator VAArgExpr::child_begin() { return &Val; }
2283193326SedStmt::child_iterator VAArgExpr::child_end() { return &Val+1; }
2284193326Sed
2285193326Sed// InitListExpr
2286193326SedStmt::child_iterator InitListExpr::child_begin() {
2287193326Sed  return InitExprs.size() ? &InitExprs[0] : 0;
2288193326Sed}
2289193326SedStmt::child_iterator InitListExpr::child_end() {
2290193326Sed  return InitExprs.size() ? &InitExprs[0] + InitExprs.size() : 0;
2291193326Sed}
2292193326Sed
2293193326Sed// DesignatedInitExpr
2294193326SedStmt::child_iterator DesignatedInitExpr::child_begin() {
2295193326Sed  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2296193326Sed  Ptr += sizeof(DesignatedInitExpr);
2297193326Sed  return reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2298193326Sed}
2299193326SedStmt::child_iterator DesignatedInitExpr::child_end() {
2300193326Sed  return child_iterator(&*child_begin() + NumSubExprs);
2301193326Sed}
2302193326Sed
2303193326Sed// ImplicitValueInitExpr
2304198092SrdivackyStmt::child_iterator ImplicitValueInitExpr::child_begin() {
2305198092Srdivacky  return child_iterator();
2306193326Sed}
2307193326Sed
2308198092SrdivackyStmt::child_iterator ImplicitValueInitExpr::child_end() {
2309198092Srdivacky  return child_iterator();
2310193326Sed}
2311193326Sed
2312198092Srdivacky// ParenListExpr
2313198092SrdivackyStmt::child_iterator ParenListExpr::child_begin() {
2314198092Srdivacky  return &Exprs[0];
2315198092Srdivacky}
2316198092SrdivackyStmt::child_iterator ParenListExpr::child_end() {
2317198092Srdivacky  return &Exprs[0]+NumExprs;
2318198092Srdivacky}
2319198092Srdivacky
2320193326Sed// ObjCStringLiteral
2321198092SrdivackyStmt::child_iterator ObjCStringLiteral::child_begin() {
2322193326Sed  return &String;
2323193326Sed}
2324193326SedStmt::child_iterator ObjCStringLiteral::child_end() {
2325193326Sed  return &String+1;
2326193326Sed}
2327193326Sed
2328193326Sed// ObjCEncodeExpr
2329193326SedStmt::child_iterator ObjCEncodeExpr::child_begin() { return child_iterator(); }
2330193326SedStmt::child_iterator ObjCEncodeExpr::child_end() { return child_iterator(); }
2331193326Sed
2332193326Sed// ObjCSelectorExpr
2333198092SrdivackyStmt::child_iterator ObjCSelectorExpr::child_begin() {
2334193326Sed  return child_iterator();
2335193326Sed}
2336193326SedStmt::child_iterator ObjCSelectorExpr::child_end() {
2337193326Sed  return child_iterator();
2338193326Sed}
2339193326Sed
2340193326Sed// ObjCProtocolExpr
2341193326SedStmt::child_iterator ObjCProtocolExpr::child_begin() {
2342193326Sed  return child_iterator();
2343193326Sed}
2344193326SedStmt::child_iterator ObjCProtocolExpr::child_end() {
2345193326Sed  return child_iterator();
2346193326Sed}
2347193326Sed
2348193326Sed// ObjCMessageExpr
2349198092SrdivackyStmt::child_iterator ObjCMessageExpr::child_begin() {
2350193326Sed  return getReceiver() ? &SubExprs[0] : &SubExprs[0] + ARGS_START;
2351193326Sed}
2352193326SedStmt::child_iterator ObjCMessageExpr::child_end() {
2353193326Sed  return &SubExprs[0]+ARGS_START+getNumArgs();
2354193326Sed}
2355193326Sed
2356193326Sed// Blocks
2357193326SedStmt::child_iterator BlockExpr::child_begin() { return child_iterator(); }
2358193326SedStmt::child_iterator BlockExpr::child_end() { return child_iterator(); }
2359193326Sed
2360193326SedStmt::child_iterator BlockDeclRefExpr::child_begin() { return child_iterator();}
2361193326SedStmt::child_iterator BlockDeclRefExpr::child_end() { return child_iterator(); }
2362