1 //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Expr class and subclasses.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/Expr.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Lex/LiteralSupport.h"
24 #include "clang/Lex/Lexer.h"
25 #include "clang/Basic/Builtins.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
31 using namespace clang;
33 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
34 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
35 /// but also int expressions which are produced by things like comparisons in
37 bool Expr::isKnownToHaveBooleanValue() const {
38 // If this value has _Bool type, it is obvious 0/1.
39 if (getType()->isBooleanType()) return true;
40 // If this is a non-scalar-integer type, we don't care enough to try.
41 if (!getType()->isIntegralOrEnumerationType()) return false;
43 if (const ParenExpr *PE = dyn_cast<ParenExpr>(this))
44 return PE->getSubExpr()->isKnownToHaveBooleanValue();
46 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(this)) {
47 switch (UO->getOpcode()) {
50 return UO->getSubExpr()->isKnownToHaveBooleanValue();
56 // Only look through implicit casts. If the user writes
57 // '(int) (a && b)' treat it as an arbitrary int.
58 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(this))
59 return CE->getSubExpr()->isKnownToHaveBooleanValue();
61 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(this)) {
62 switch (BO->getOpcode()) {
63 default: return false;
64 case BO_LT: // Relational operators.
68 case BO_EQ: // Equality operators.
70 case BO_LAnd: // AND operator.
71 case BO_LOr: // Logical OR operator.
74 case BO_And: // Bitwise AND operator.
75 case BO_Xor: // Bitwise XOR operator.
76 case BO_Or: // Bitwise OR operator.
77 // Handle things like (x==2)|(y==12).
78 return BO->getLHS()->isKnownToHaveBooleanValue() &&
79 BO->getRHS()->isKnownToHaveBooleanValue();
83 return BO->getRHS()->isKnownToHaveBooleanValue();
87 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(this))
88 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
89 CO->getFalseExpr()->isKnownToHaveBooleanValue();
94 // Amusing macro metaprogramming hack: check whether a class provides
95 // a more specific implementation of getExprLoc().
97 /// This implementation is used when a class provides a custom
98 /// implementation of getExprLoc.
99 template <class E, class T>
100 SourceLocation getExprLocImpl(const Expr *expr,
101 SourceLocation (T::*v)() const) {
102 return static_cast<const E*>(expr)->getExprLoc();
105 /// This implementation is used when a class doesn't provide
106 /// a custom implementation of getExprLoc. Overload resolution
107 /// should pick it over the implementation above because it's
108 /// more specialized according to function template partial ordering.
110 SourceLocation getExprLocImpl(const Expr *expr,
111 SourceLocation (Expr::*v)() const) {
112 return static_cast<const E*>(expr)->getSourceRange().getBegin();
116 SourceLocation Expr::getExprLoc() const {
117 switch (getStmtClass()) {
118 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
119 #define ABSTRACT_STMT(type)
120 #define STMT(type, base) \
121 case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break;
122 #define EXPR(type, base) \
123 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
124 #include "clang/AST/StmtNodes.inc"
126 llvm_unreachable("unknown statement kind");
127 return SourceLocation();
130 //===----------------------------------------------------------------------===//
131 // Primary Expressions.
132 //===----------------------------------------------------------------------===//
134 void ExplicitTemplateArgumentList::initializeFrom(
135 const TemplateArgumentListInfo &Info) {
136 LAngleLoc = Info.getLAngleLoc();
137 RAngleLoc = Info.getRAngleLoc();
138 NumTemplateArgs = Info.size();
140 TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
141 for (unsigned i = 0; i != NumTemplateArgs; ++i)
142 new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
145 void ExplicitTemplateArgumentList::initializeFrom(
146 const TemplateArgumentListInfo &Info,
148 bool &ContainsUnexpandedParameterPack) {
149 LAngleLoc = Info.getLAngleLoc();
150 RAngleLoc = Info.getRAngleLoc();
151 NumTemplateArgs = Info.size();
153 TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
154 for (unsigned i = 0; i != NumTemplateArgs; ++i) {
155 Dependent = Dependent || Info[i].getArgument().isDependent();
156 ContainsUnexpandedParameterPack
157 = ContainsUnexpandedParameterPack ||
158 Info[i].getArgument().containsUnexpandedParameterPack();
160 new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
164 void ExplicitTemplateArgumentList::copyInto(
165 TemplateArgumentListInfo &Info) const {
166 Info.setLAngleLoc(LAngleLoc);
167 Info.setRAngleLoc(RAngleLoc);
168 for (unsigned I = 0; I != NumTemplateArgs; ++I)
169 Info.addArgument(getTemplateArgs()[I]);
172 std::size_t ExplicitTemplateArgumentList::sizeFor(unsigned NumTemplateArgs) {
173 return sizeof(ExplicitTemplateArgumentList) +
174 sizeof(TemplateArgumentLoc) * NumTemplateArgs;
177 std::size_t ExplicitTemplateArgumentList::sizeFor(
178 const TemplateArgumentListInfo &Info) {
179 return sizeFor(Info.size());
182 /// \brief Compute the type- and value-dependence of a declaration reference
183 /// based on the declaration being referenced.
184 static void computeDeclRefDependence(NamedDecl *D, QualType T,
186 bool &ValueDependent) {
187 TypeDependent = false;
188 ValueDependent = false;
191 // (TD) C++ [temp.dep.expr]p3:
192 // An id-expression is type-dependent if it contains:
196 // (VD) C++ [temp.dep.constexpr]p2:
197 // An identifier is value-dependent if it is:
199 // (TD) - an identifier that was declared with dependent type
200 // (VD) - a name declared with a dependent type,
201 if (T->isDependentType()) {
202 TypeDependent = true;
203 ValueDependent = true;
207 // (TD) - a conversion-function-id that specifies a dependent type
208 if (D->getDeclName().getNameKind()
209 == DeclarationName::CXXConversionFunctionName &&
210 D->getDeclName().getCXXNameType()->isDependentType()) {
211 TypeDependent = true;
212 ValueDependent = true;
215 // (VD) - the name of a non-type template parameter,
216 if (isa<NonTypeTemplateParmDecl>(D)) {
217 ValueDependent = true;
221 // (VD) - a constant with integral or enumeration type and is
222 // initialized with an expression that is value-dependent.
223 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
224 if (Var->getType()->isIntegralOrEnumerationType() &&
225 Var->getType().getCVRQualifiers() == Qualifiers::Const) {
226 if (const Expr *Init = Var->getAnyInitializer())
227 if (Init->isValueDependent())
228 ValueDependent = true;
231 // (VD) - FIXME: Missing from the standard:
232 // - a member function or a static data member of the current
234 else if (Var->isStaticDataMember() &&
235 Var->getDeclContext()->isDependentContext())
236 ValueDependent = true;
241 // (VD) - FIXME: Missing from the standard:
242 // - a member function or a static data member of the current
244 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
245 ValueDependent = true;
250 void DeclRefExpr::computeDependence() {
251 bool TypeDependent = false;
252 bool ValueDependent = false;
253 computeDeclRefDependence(getDecl(), getType(), TypeDependent, ValueDependent);
255 // (TD) C++ [temp.dep.expr]p3:
256 // An id-expression is type-dependent if it contains:
260 // (VD) C++ [temp.dep.constexpr]p2:
261 // An identifier is value-dependent if it is:
262 if (!TypeDependent && !ValueDependent &&
263 hasExplicitTemplateArgs() &&
264 TemplateSpecializationType::anyDependentTemplateArguments(
266 getNumTemplateArgs())) {
267 TypeDependent = true;
268 ValueDependent = true;
271 ExprBits.TypeDependent = TypeDependent;
272 ExprBits.ValueDependent = ValueDependent;
274 // Is the declaration a parameter pack?
275 if (getDecl()->isParameterPack())
276 ExprBits.ContainsUnexpandedParameterPack = true;
279 DeclRefExpr::DeclRefExpr(NestedNameSpecifier *Qualifier,
280 SourceRange QualifierRange,
281 ValueDecl *D, SourceLocation NameLoc,
282 const TemplateArgumentListInfo *TemplateArgs,
283 QualType T, ExprValueKind VK)
284 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false),
286 (Qualifier? HasQualifierFlag : 0) |
287 (TemplateArgs ? HasExplicitTemplateArgumentListFlag : 0)),
290 NameQualifier *NQ = getNameQualifier();
292 NQ->Range = QualifierRange;
296 getExplicitTemplateArgs().initializeFrom(*TemplateArgs);
301 DeclRefExpr::DeclRefExpr(NestedNameSpecifier *Qualifier,
302 SourceRange QualifierRange,
303 ValueDecl *D, const DeclarationNameInfo &NameInfo,
304 const TemplateArgumentListInfo *TemplateArgs,
305 QualType T, ExprValueKind VK)
306 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false),
308 (Qualifier? HasQualifierFlag : 0) |
309 (TemplateArgs ? HasExplicitTemplateArgumentListFlag : 0)),
310 Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
312 NameQualifier *NQ = getNameQualifier();
314 NQ->Range = QualifierRange;
318 getExplicitTemplateArgs().initializeFrom(*TemplateArgs);
323 DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
324 NestedNameSpecifier *Qualifier,
325 SourceRange QualifierRange,
327 SourceLocation NameLoc,
330 const TemplateArgumentListInfo *TemplateArgs) {
331 return Create(Context, Qualifier, QualifierRange, D,
332 DeclarationNameInfo(D->getDeclName(), NameLoc),
333 T, VK, TemplateArgs);
336 DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
337 NestedNameSpecifier *Qualifier,
338 SourceRange QualifierRange,
340 const DeclarationNameInfo &NameInfo,
343 const TemplateArgumentListInfo *TemplateArgs) {
344 std::size_t Size = sizeof(DeclRefExpr);
346 Size += sizeof(NameQualifier);
349 Size += ExplicitTemplateArgumentList::sizeFor(*TemplateArgs);
351 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
352 return new (Mem) DeclRefExpr(Qualifier, QualifierRange, D, NameInfo,
353 TemplateArgs, T, VK);
356 DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context,
358 bool HasExplicitTemplateArgs,
359 unsigned NumTemplateArgs) {
360 std::size_t Size = sizeof(DeclRefExpr);
362 Size += sizeof(NameQualifier);
364 if (HasExplicitTemplateArgs)
365 Size += ExplicitTemplateArgumentList::sizeFor(NumTemplateArgs);
367 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
368 return new (Mem) DeclRefExpr(EmptyShell());
371 SourceRange DeclRefExpr::getSourceRange() const {
372 SourceRange R = getNameInfo().getSourceRange();
374 R.setBegin(getQualifierRange().getBegin());
375 if (hasExplicitTemplateArgs())
376 R.setEnd(getRAngleLoc());
380 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
381 // expr" policy instead.
382 std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
383 ASTContext &Context = CurrentDecl->getASTContext();
385 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
386 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual)
387 return FD->getNameAsString();
389 llvm::SmallString<256> Name;
390 llvm::raw_svector_ostream Out(Name);
392 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
393 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
399 PrintingPolicy Policy(Context.getLangOptions());
401 std::string Proto = FD->getQualifiedNameAsString(Policy);
403 const FunctionType *AFT = FD->getType()->getAs<FunctionType>();
404 const FunctionProtoType *FT = 0;
405 if (FD->hasWrittenPrototype())
406 FT = dyn_cast<FunctionProtoType>(AFT);
410 llvm::raw_string_ostream POut(Proto);
411 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
414 FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
418 if (FT->isVariadic()) {
419 if (FD->getNumParams()) POut << ", ";
425 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
426 Qualifiers ThisQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
427 if (ThisQuals.hasConst())
429 if (ThisQuals.hasVolatile())
430 Proto += " volatile";
433 if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
434 AFT->getResultType().getAsStringInternal(Proto, Policy);
439 return Name.str().str();
441 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
442 llvm::SmallString<256> Name;
443 llvm::raw_svector_ostream Out(Name);
444 Out << (MD->isInstanceMethod() ? '-' : '+');
447 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
448 // a null check to avoid a crash.
449 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
452 if (const ObjCCategoryImplDecl *CID =
453 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
454 Out << '(' << CID << ')';
457 Out << MD->getSelector().getAsString();
461 return Name.str().str();
463 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
464 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
470 void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) {
474 BitWidth = Val.getBitWidth();
475 unsigned NumWords = Val.getNumWords();
476 const uint64_t* Words = Val.getRawData();
478 pVal = new (C) uint64_t[NumWords];
479 std::copy(Words, Words + NumWords, pVal);
480 } else if (NumWords == 1)
487 IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V,
488 QualType type, SourceLocation l) {
489 return new (C) IntegerLiteral(C, V, type, l);
493 IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) {
494 return new (C) IntegerLiteral(Empty);
498 FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V,
499 bool isexact, QualType Type, SourceLocation L) {
500 return new (C) FloatingLiteral(C, V, isexact, Type, L);
504 FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
505 return new (C) FloatingLiteral(Empty);
508 /// getValueAsApproximateDouble - This returns the value as an inaccurate
509 /// double. Note that this may cause loss of precision, but is useful for
510 /// debugging dumps, etc.
511 double FloatingLiteral::getValueAsApproximateDouble() const {
512 llvm::APFloat V = getValue();
514 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
516 return V.convertToDouble();
519 StringLiteral *StringLiteral::Create(ASTContext &C, const char *StrData,
520 unsigned ByteLength, bool Wide,
522 const SourceLocation *Loc,
524 // Allocate enough space for the StringLiteral plus an array of locations for
525 // any concatenated string tokens.
526 void *Mem = C.Allocate(sizeof(StringLiteral)+
527 sizeof(SourceLocation)*(NumStrs-1),
528 llvm::alignOf<StringLiteral>());
529 StringLiteral *SL = new (Mem) StringLiteral(Ty);
531 // OPTIMIZE: could allocate this appended to the StringLiteral.
532 char *AStrData = new (C, 1) char[ByteLength];
533 memcpy(AStrData, StrData, ByteLength);
534 SL->StrData = AStrData;
535 SL->ByteLength = ByteLength;
537 SL->TokLocs[0] = Loc[0];
538 SL->NumConcatenated = NumStrs;
541 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
545 StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
546 void *Mem = C.Allocate(sizeof(StringLiteral)+
547 sizeof(SourceLocation)*(NumStrs-1),
548 llvm::alignOf<StringLiteral>());
549 StringLiteral *SL = new (Mem) StringLiteral(QualType());
552 SL->NumConcatenated = NumStrs;
556 void StringLiteral::setString(ASTContext &C, llvm::StringRef Str) {
557 char *AStrData = new (C, 1) char[Str.size()];
558 memcpy(AStrData, Str.data(), Str.size());
560 ByteLength = Str.size();
563 /// getLocationOfByte - Return a source location that points to the specified
564 /// byte of this string literal.
566 /// Strings are amazingly complex. They can be formed from multiple tokens and
567 /// can have escape sequences in them in addition to the usual trigraph and
568 /// escaped newline business. This routine handles this complexity.
570 SourceLocation StringLiteral::
571 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
572 const LangOptions &Features, const TargetInfo &Target) const {
573 assert(!isWide() && "This doesn't work for wide strings yet");
575 // Loop over all of the tokens in this string until we find the one that
576 // contains the byte we're looking for.
579 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
580 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
582 // Get the spelling of the string so that we can get the data that makes up
583 // the string literal, not the identifier for the macro it is potentially
585 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
587 // Re-lex the token to get its length and original spelling.
588 std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
589 bool Invalid = false;
590 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
592 return StrTokSpellingLoc;
594 const char *StrData = Buffer.data()+LocInfo.second;
596 // Create a langops struct and enable trigraphs. This is sufficient for
598 LangOptions LangOpts;
599 LangOpts.Trigraphs = true;
601 // Create a lexer starting at the beginning of this token.
602 Lexer TheLexer(StrTokSpellingLoc, Features, Buffer.begin(), StrData,
605 TheLexer.LexFromRawLexer(TheTok);
607 // Use the StringLiteralParser to compute the length of the string in bytes.
608 StringLiteralParser SLP(&TheTok, 1, SM, Features, Target);
609 unsigned TokNumBytes = SLP.GetStringLength();
611 // If the byte is in this token, return the location of the byte.
612 if (ByteNo < TokNumBytes ||
613 (ByteNo == TokNumBytes && TokNo == getNumConcatenated())) {
614 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
616 // Now that we know the offset of the token in the spelling, use the
617 // preprocessor to get the offset in the original source.
618 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
621 // Move to the next string token.
623 ByteNo -= TokNumBytes;
629 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
630 /// corresponds to, e.g. "sizeof" or "[pre]++".
631 const char *UnaryOperator::getOpcodeStr(Opcode Op) {
633 default: assert(0 && "Unknown unary operator");
634 case UO_PostInc: return "++";
635 case UO_PostDec: return "--";
636 case UO_PreInc: return "++";
637 case UO_PreDec: return "--";
638 case UO_AddrOf: return "&";
639 case UO_Deref: return "*";
640 case UO_Plus: return "+";
641 case UO_Minus: return "-";
642 case UO_Not: return "~";
643 case UO_LNot: return "!";
644 case UO_Real: return "__real";
645 case UO_Imag: return "__imag";
646 case UO_Extension: return "__extension__";
651 UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
653 default: assert(false && "No unary operator for overloaded function");
654 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
655 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
656 case OO_Amp: return UO_AddrOf;
657 case OO_Star: return UO_Deref;
658 case OO_Plus: return UO_Plus;
659 case OO_Minus: return UO_Minus;
660 case OO_Tilde: return UO_Not;
661 case OO_Exclaim: return UO_LNot;
665 OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
667 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
668 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
669 case UO_AddrOf: return OO_Amp;
670 case UO_Deref: return OO_Star;
671 case UO_Plus: return OO_Plus;
672 case UO_Minus: return OO_Minus;
673 case UO_Not: return OO_Tilde;
674 case UO_LNot: return OO_Exclaim;
675 default: return OO_None;
680 //===----------------------------------------------------------------------===//
681 // Postfix Operators.
682 //===----------------------------------------------------------------------===//
684 CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
685 Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
686 SourceLocation rparenloc)
687 : Expr(SC, t, VK, OK_Ordinary,
688 fn->isTypeDependent(),
689 fn->isValueDependent(),
690 fn->containsUnexpandedParameterPack()),
693 SubExprs = new (C) Stmt*[numargs+PREARGS_START+NumPreArgs];
695 for (unsigned i = 0; i != numargs; ++i) {
696 if (args[i]->isTypeDependent())
697 ExprBits.TypeDependent = true;
698 if (args[i]->isValueDependent())
699 ExprBits.ValueDependent = true;
700 if (args[i]->containsUnexpandedParameterPack())
701 ExprBits.ContainsUnexpandedParameterPack = true;
703 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
706 CallExprBits.NumPreArgs = NumPreArgs;
707 RParenLoc = rparenloc;
710 CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs,
711 QualType t, ExprValueKind VK, SourceLocation rparenloc)
712 : Expr(CallExprClass, t, VK, OK_Ordinary,
713 fn->isTypeDependent(),
714 fn->isValueDependent(),
715 fn->containsUnexpandedParameterPack()),
718 SubExprs = new (C) Stmt*[numargs+PREARGS_START];
720 for (unsigned i = 0; i != numargs; ++i) {
721 if (args[i]->isTypeDependent())
722 ExprBits.TypeDependent = true;
723 if (args[i]->isValueDependent())
724 ExprBits.ValueDependent = true;
725 if (args[i]->containsUnexpandedParameterPack())
726 ExprBits.ContainsUnexpandedParameterPack = true;
728 SubExprs[i+PREARGS_START] = args[i];
731 CallExprBits.NumPreArgs = 0;
732 RParenLoc = rparenloc;
735 CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
736 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
737 // FIXME: Why do we allocate this?
738 SubExprs = new (C) Stmt*[PREARGS_START];
739 CallExprBits.NumPreArgs = 0;
742 CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs,
744 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
745 // FIXME: Why do we allocate this?
746 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
747 CallExprBits.NumPreArgs = NumPreArgs;
750 Decl *CallExpr::getCalleeDecl() {
751 Expr *CEE = getCallee()->IgnoreParenCasts();
752 // If we're calling a dereference, look at the pointer instead.
753 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
754 if (BO->isPtrMemOp())
755 CEE = BO->getRHS()->IgnoreParenCasts();
756 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
757 if (UO->getOpcode() == UO_Deref)
758 CEE = UO->getSubExpr()->IgnoreParenCasts();
760 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
761 return DRE->getDecl();
762 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
763 return ME->getMemberDecl();
768 FunctionDecl *CallExpr::getDirectCallee() {
769 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
772 /// setNumArgs - This changes the number of arguments present in this call.
773 /// Any orphaned expressions are deleted by this, and any new operands are set
775 void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
776 // No change, just return.
777 if (NumArgs == getNumArgs()) return;
779 // If shrinking # arguments, just delete the extras and forgot them.
780 if (NumArgs < getNumArgs()) {
781 this->NumArgs = NumArgs;
785 // Otherwise, we are growing the # arguments. New an bigger argument array.
786 unsigned NumPreArgs = getNumPreArgs();
787 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
789 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
790 NewSubExprs[i] = SubExprs[i];
791 // Null out new args.
792 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
793 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
796 if (SubExprs) C.Deallocate(SubExprs);
797 SubExprs = NewSubExprs;
798 this->NumArgs = NumArgs;
801 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If
803 unsigned CallExpr::isBuiltinCall(const ASTContext &Context) const {
804 // All simple function calls (e.g. func()) are implicitly cast to pointer to
805 // function. As a result, we try and obtain the DeclRefExpr from the
807 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
808 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
811 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
815 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
819 if (!FDecl->getIdentifier())
822 return FDecl->getBuiltinID();
825 QualType CallExpr::getCallReturnType() const {
826 QualType CalleeType = getCallee()->getType();
827 if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
828 CalleeType = FnTypePtr->getPointeeType();
829 else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
830 CalleeType = BPT->getPointeeType();
831 else if (const MemberPointerType *MPT
832 = CalleeType->getAs<MemberPointerType>())
833 CalleeType = MPT->getPointeeType();
835 const FunctionType *FnType = CalleeType->getAs<FunctionType>();
836 return FnType->getResultType();
839 SourceRange CallExpr::getSourceRange() const {
840 if (isa<CXXOperatorCallExpr>(this))
841 return cast<CXXOperatorCallExpr>(this)->getSourceRange();
843 SourceLocation begin = getCallee()->getLocStart();
844 if (begin.isInvalid() && getNumArgs() > 0)
845 begin = getArg(0)->getLocStart();
846 SourceLocation end = getRParenLoc();
847 if (end.isInvalid() && getNumArgs() > 0)
848 end = getArg(getNumArgs() - 1)->getLocEnd();
849 return SourceRange(begin, end);
852 OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,
853 SourceLocation OperatorLoc,
855 OffsetOfNode* compsPtr, unsigned numComps,
856 Expr** exprsPtr, unsigned numExprs,
857 SourceLocation RParenLoc) {
858 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
859 sizeof(OffsetOfNode) * numComps +
860 sizeof(Expr*) * numExprs);
862 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, compsPtr, numComps,
863 exprsPtr, numExprs, RParenLoc);
866 OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C,
867 unsigned numComps, unsigned numExprs) {
868 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
869 sizeof(OffsetOfNode) * numComps +
870 sizeof(Expr*) * numExprs);
871 return new (Mem) OffsetOfExpr(numComps, numExprs);
874 OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type,
875 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
876 OffsetOfNode* compsPtr, unsigned numComps,
877 Expr** exprsPtr, unsigned numExprs,
878 SourceLocation RParenLoc)
879 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
880 /*TypeDependent=*/false,
881 /*ValueDependent=*/tsi->getType()->isDependentType(),
882 tsi->getType()->containsUnexpandedParameterPack()),
883 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
884 NumComps(numComps), NumExprs(numExprs)
886 for(unsigned i = 0; i < numComps; ++i) {
887 setComponent(i, compsPtr[i]);
890 for(unsigned i = 0; i < numExprs; ++i) {
891 if (exprsPtr[i]->isTypeDependent() || exprsPtr[i]->isValueDependent())
892 ExprBits.ValueDependent = true;
893 if (exprsPtr[i]->containsUnexpandedParameterPack())
894 ExprBits.ContainsUnexpandedParameterPack = true;
896 setIndexExpr(i, exprsPtr[i]);
900 IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
901 assert(getKind() == Field || getKind() == Identifier);
902 if (getKind() == Field)
903 return getField()->getIdentifier();
905 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
908 MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
909 NestedNameSpecifier *qual,
910 SourceRange qualrange,
911 ValueDecl *memberdecl,
912 DeclAccessPair founddecl,
913 DeclarationNameInfo nameinfo,
914 const TemplateArgumentListInfo *targs,
918 std::size_t Size = sizeof(MemberExpr);
920 bool hasQualOrFound = (qual != 0 ||
921 founddecl.getDecl() != memberdecl ||
922 founddecl.getAccess() != memberdecl->getAccess());
924 Size += sizeof(MemberNameQualifier);
927 Size += ExplicitTemplateArgumentList::sizeFor(*targs);
929 void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
930 MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo,
933 if (hasQualOrFound) {
934 if (qual && qual->isDependent()) {
935 E->setValueDependent(true);
936 E->setTypeDependent(true);
938 E->HasQualifierOrFoundDecl = true;
940 MemberNameQualifier *NQ = E->getMemberQualifier();
942 NQ->Range = qualrange;
943 NQ->FoundDecl = founddecl;
947 E->HasExplicitTemplateArgumentList = true;
948 E->getExplicitTemplateArgs().initializeFrom(*targs);
954 const char *CastExpr::getCastKindName() const {
955 switch (getCastKind()) {
960 case CK_LValueBitCast:
961 return "LValueBitCast";
962 case CK_LValueToRValue:
963 return "LValueToRValue";
964 case CK_GetObjCProperty:
965 return "GetObjCProperty";
968 case CK_BaseToDerived:
969 return "BaseToDerived";
970 case CK_DerivedToBase:
971 return "DerivedToBase";
972 case CK_UncheckedDerivedToBase:
973 return "UncheckedDerivedToBase";
978 case CK_ArrayToPointerDecay:
979 return "ArrayToPointerDecay";
980 case CK_FunctionToPointerDecay:
981 return "FunctionToPointerDecay";
982 case CK_NullToMemberPointer:
983 return "NullToMemberPointer";
984 case CK_NullToPointer:
985 return "NullToPointer";
986 case CK_BaseToDerivedMemberPointer:
987 return "BaseToDerivedMemberPointer";
988 case CK_DerivedToBaseMemberPointer:
989 return "DerivedToBaseMemberPointer";
990 case CK_UserDefinedConversion:
991 return "UserDefinedConversion";
992 case CK_ConstructorConversion:
993 return "ConstructorConversion";
994 case CK_IntegralToPointer:
995 return "IntegralToPointer";
996 case CK_PointerToIntegral:
997 return "PointerToIntegral";
998 case CK_PointerToBoolean:
999 return "PointerToBoolean";
1002 case CK_VectorSplat:
1003 return "VectorSplat";
1004 case CK_IntegralCast:
1005 return "IntegralCast";
1006 case CK_IntegralToBoolean:
1007 return "IntegralToBoolean";
1008 case CK_IntegralToFloating:
1009 return "IntegralToFloating";
1010 case CK_FloatingToIntegral:
1011 return "FloatingToIntegral";
1012 case CK_FloatingCast:
1013 return "FloatingCast";
1014 case CK_FloatingToBoolean:
1015 return "FloatingToBoolean";
1016 case CK_MemberPointerToBoolean:
1017 return "MemberPointerToBoolean";
1018 case CK_AnyPointerToObjCPointerCast:
1019 return "AnyPointerToObjCPointerCast";
1020 case CK_AnyPointerToBlockPointerCast:
1021 return "AnyPointerToBlockPointerCast";
1022 case CK_ObjCObjectLValueCast:
1023 return "ObjCObjectLValueCast";
1024 case CK_FloatingRealToComplex:
1025 return "FloatingRealToComplex";
1026 case CK_FloatingComplexToReal:
1027 return "FloatingComplexToReal";
1028 case CK_FloatingComplexToBoolean:
1029 return "FloatingComplexToBoolean";
1030 case CK_FloatingComplexCast:
1031 return "FloatingComplexCast";
1032 case CK_FloatingComplexToIntegralComplex:
1033 return "FloatingComplexToIntegralComplex";
1034 case CK_IntegralRealToComplex:
1035 return "IntegralRealToComplex";
1036 case CK_IntegralComplexToReal:
1037 return "IntegralComplexToReal";
1038 case CK_IntegralComplexToBoolean:
1039 return "IntegralComplexToBoolean";
1040 case CK_IntegralComplexCast:
1041 return "IntegralComplexCast";
1042 case CK_IntegralComplexToFloatingComplex:
1043 return "IntegralComplexToFloatingComplex";
1046 llvm_unreachable("Unhandled cast kind!");
1050 Expr *CastExpr::getSubExprAsWritten() {
1054 SubExpr = E->getSubExpr();
1056 // Skip any temporary bindings; they're implicit.
1057 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1058 SubExpr = Binder->getSubExpr();
1060 // Conversions by constructor and conversion functions have a
1061 // subexpression describing the call; strip it off.
1062 if (E->getCastKind() == CK_ConstructorConversion)
1063 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
1064 else if (E->getCastKind() == CK_UserDefinedConversion)
1065 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1067 // If the subexpression we're left with is an implicit cast, look
1068 // through that, too.
1069 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1074 CXXBaseSpecifier **CastExpr::path_buffer() {
1075 switch (getStmtClass()) {
1076 #define ABSTRACT_STMT(x)
1077 #define CASTEXPR(Type, Base) \
1078 case Stmt::Type##Class: \
1079 return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
1080 #define STMT(Type, Base)
1081 #include "clang/AST/StmtNodes.inc"
1083 llvm_unreachable("non-cast expressions not possible here");
1088 void CastExpr::setCastPath(const CXXCastPath &Path) {
1089 assert(Path.size() == path_size());
1090 memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
1093 ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T,
1094 CastKind Kind, Expr *Operand,
1095 const CXXCastPath *BasePath,
1097 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1099 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1100 ImplicitCastExpr *E =
1101 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1102 if (PathSize) E->setCastPath(*BasePath);
1106 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C,
1107 unsigned PathSize) {
1109 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1110 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1114 CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T,
1115 ExprValueKind VK, CastKind K, Expr *Op,
1116 const CXXCastPath *BasePath,
1117 TypeSourceInfo *WrittenTy,
1118 SourceLocation L, SourceLocation R) {
1119 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1121 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1123 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
1124 if (PathSize) E->setCastPath(*BasePath);
1128 CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
1130 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1131 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1134 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1135 /// corresponds to, e.g. "<<=".
1136 const char *BinaryOperator::getOpcodeStr(Opcode Op) {
1138 case BO_PtrMemD: return ".*";
1139 case BO_PtrMemI: return "->*";
1140 case BO_Mul: return "*";
1141 case BO_Div: return "/";
1142 case BO_Rem: return "%";
1143 case BO_Add: return "+";
1144 case BO_Sub: return "-";
1145 case BO_Shl: return "<<";
1146 case BO_Shr: return ">>";
1147 case BO_LT: return "<";
1148 case BO_GT: return ">";
1149 case BO_LE: return "<=";
1150 case BO_GE: return ">=";
1151 case BO_EQ: return "==";
1152 case BO_NE: return "!=";
1153 case BO_And: return "&";
1154 case BO_Xor: return "^";
1155 case BO_Or: return "|";
1156 case BO_LAnd: return "&&";
1157 case BO_LOr: return "||";
1158 case BO_Assign: return "=";
1159 case BO_MulAssign: return "*=";
1160 case BO_DivAssign: return "/=";
1161 case BO_RemAssign: return "%=";
1162 case BO_AddAssign: return "+=";
1163 case BO_SubAssign: return "-=";
1164 case BO_ShlAssign: return "<<=";
1165 case BO_ShrAssign: return ">>=";
1166 case BO_AndAssign: return "&=";
1167 case BO_XorAssign: return "^=";
1168 case BO_OrAssign: return "|=";
1169 case BO_Comma: return ",";
1176 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1178 default: assert(false && "Not an overloadable binary operator");
1179 case OO_Plus: return BO_Add;
1180 case OO_Minus: return BO_Sub;
1181 case OO_Star: return BO_Mul;
1182 case OO_Slash: return BO_Div;
1183 case OO_Percent: return BO_Rem;
1184 case OO_Caret: return BO_Xor;
1185 case OO_Amp: return BO_And;
1186 case OO_Pipe: return BO_Or;
1187 case OO_Equal: return BO_Assign;
1188 case OO_Less: return BO_LT;
1189 case OO_Greater: return BO_GT;
1190 case OO_PlusEqual: return BO_AddAssign;
1191 case OO_MinusEqual: return BO_SubAssign;
1192 case OO_StarEqual: return BO_MulAssign;
1193 case OO_SlashEqual: return BO_DivAssign;
1194 case OO_PercentEqual: return BO_RemAssign;
1195 case OO_CaretEqual: return BO_XorAssign;
1196 case OO_AmpEqual: return BO_AndAssign;
1197 case OO_PipeEqual: return BO_OrAssign;
1198 case OO_LessLess: return BO_Shl;
1199 case OO_GreaterGreater: return BO_Shr;
1200 case OO_LessLessEqual: return BO_ShlAssign;
1201 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1202 case OO_EqualEqual: return BO_EQ;
1203 case OO_ExclaimEqual: return BO_NE;
1204 case OO_LessEqual: return BO_LE;
1205 case OO_GreaterEqual: return BO_GE;
1206 case OO_AmpAmp: return BO_LAnd;
1207 case OO_PipePipe: return BO_LOr;
1208 case OO_Comma: return BO_Comma;
1209 case OO_ArrowStar: return BO_PtrMemI;
1213 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1214 static const OverloadedOperatorKind OverOps[] = {
1215 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1216 OO_Star, OO_Slash, OO_Percent,
1218 OO_LessLess, OO_GreaterGreater,
1219 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1220 OO_EqualEqual, OO_ExclaimEqual,
1226 OO_Equal, OO_StarEqual,
1227 OO_SlashEqual, OO_PercentEqual,
1228 OO_PlusEqual, OO_MinusEqual,
1229 OO_LessLessEqual, OO_GreaterGreaterEqual,
1230 OO_AmpEqual, OO_CaretEqual,
1234 return OverOps[Opc];
1237 InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc,
1238 Expr **initExprs, unsigned numInits,
1239 SourceLocation rbraceloc)
1240 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1242 InitExprs(C, numInits),
1243 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0),
1244 UnionFieldInit(0), HadArrayRangeDesignator(false)
1246 for (unsigned I = 0; I != numInits; ++I) {
1247 if (initExprs[I]->isTypeDependent())
1248 ExprBits.TypeDependent = true;
1249 if (initExprs[I]->isValueDependent())
1250 ExprBits.ValueDependent = true;
1251 if (initExprs[I]->containsUnexpandedParameterPack())
1252 ExprBits.ContainsUnexpandedParameterPack = true;
1255 InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits);
1258 void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) {
1259 if (NumInits > InitExprs.size())
1260 InitExprs.reserve(C, NumInits);
1263 void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) {
1264 InitExprs.resize(C, NumInits, 0);
1267 Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) {
1268 if (Init >= InitExprs.size()) {
1269 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0);
1270 InitExprs.back() = expr;
1274 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1275 InitExprs[Init] = expr;
1279 SourceRange InitListExpr::getSourceRange() const {
1281 return SyntacticForm->getSourceRange();
1282 SourceLocation Beg = LBraceLoc, End = RBraceLoc;
1283 if (Beg.isInvalid()) {
1284 // Find the first non-null initializer.
1285 for (InitExprsTy::const_iterator I = InitExprs.begin(),
1286 E = InitExprs.end();
1289 Beg = S->getLocStart();
1294 if (End.isInvalid()) {
1295 // Find the first non-null initializer from the end.
1296 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1297 E = InitExprs.rend();
1300 End = S->getSourceRange().getEnd();
1305 return SourceRange(Beg, End);
1308 /// getFunctionType - Return the underlying function type for this block.
1310 const FunctionType *BlockExpr::getFunctionType() const {
1311 return getType()->getAs<BlockPointerType>()->
1312 getPointeeType()->getAs<FunctionType>();
1315 SourceLocation BlockExpr::getCaretLocation() const {
1316 return TheBlock->getCaretLocation();
1318 const Stmt *BlockExpr::getBody() const {
1319 return TheBlock->getBody();
1321 Stmt *BlockExpr::getBody() {
1322 return TheBlock->getBody();
1326 //===----------------------------------------------------------------------===//
1327 // Generic Expression Routines
1328 //===----------------------------------------------------------------------===//
1330 /// isUnusedResultAWarning - Return true if this immediate expression should
1331 /// be warned about if the result is unused. If so, fill in Loc and Ranges
1332 /// with location to warn on and the source range[s] to report with the
1334 bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
1335 SourceRange &R2, ASTContext &Ctx) const {
1336 // Don't warn if the expr is type dependent. The type could end up
1337 // instantiating to void.
1338 if (isTypeDependent())
1341 switch (getStmtClass()) {
1343 if (getType()->isVoidType())
1346 R1 = getSourceRange();
1348 case ParenExprClass:
1349 return cast<ParenExpr>(this)->getSubExpr()->
1350 isUnusedResultAWarning(Loc, R1, R2, Ctx);
1351 case UnaryOperatorClass: {
1352 const UnaryOperator *UO = cast<UnaryOperator>(this);
1354 switch (UO->getOpcode()) {
1359 case UO_PreDec: // ++/--
1360 return false; // Not a warning.
1362 // Dereferencing a volatile pointer is a side-effect.
1363 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1368 // accessing a piece of a volatile complex is a side-effect.
1369 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1370 .isVolatileQualified())
1374 return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1376 Loc = UO->getOperatorLoc();
1377 R1 = UO->getSubExpr()->getSourceRange();
1380 case BinaryOperatorClass: {
1381 const BinaryOperator *BO = cast<BinaryOperator>(this);
1382 switch (BO->getOpcode()) {
1385 // Consider the RHS of comma for side effects. LHS was checked by
1386 // Sema::CheckCommaOperands.
1388 // ((foo = <blah>), 0) is an idiom for hiding the result (and
1389 // lvalue-ness) of an assignment written in a macro.
1390 if (IntegerLiteral *IE =
1391 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1392 if (IE->getValue() == 0)
1394 return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1395 // Consider '||', '&&' to have side effects if the LHS or RHS does.
1398 if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) ||
1399 !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1403 if (BO->isAssignmentOp())
1405 Loc = BO->getOperatorLoc();
1406 R1 = BO->getLHS()->getSourceRange();
1407 R2 = BO->getRHS()->getSourceRange();
1410 case CompoundAssignOperatorClass:
1411 case VAArgExprClass:
1414 case ConditionalOperatorClass: {
1415 // The condition must be evaluated, but if either the LHS or RHS is a
1416 // warning, warn about them.
1417 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
1418 if (Exp->getLHS() &&
1419 Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1421 return Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1424 case MemberExprClass:
1425 // If the base pointer or element is to a volatile pointer/field, accessing
1426 // it is a side effect.
1427 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1429 Loc = cast<MemberExpr>(this)->getMemberLoc();
1430 R1 = SourceRange(Loc, Loc);
1431 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
1434 case ArraySubscriptExprClass:
1435 // If the base pointer or element is to a volatile pointer/field, accessing
1436 // it is a side effect.
1437 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1439 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
1440 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
1441 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
1445 case CXXOperatorCallExprClass:
1446 case CXXMemberCallExprClass: {
1447 // If this is a direct call, get the callee.
1448 const CallExpr *CE = cast<CallExpr>(this);
1449 if (const Decl *FD = CE->getCalleeDecl()) {
1450 // If the callee has attribute pure, const, or warn_unused_result, warn
1451 // about it. void foo() { strlen("bar"); } should warn.
1453 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
1454 // updated to match for QoI.
1455 if (FD->getAttr<WarnUnusedResultAttr>() ||
1456 FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
1457 Loc = CE->getCallee()->getLocStart();
1458 R1 = CE->getCallee()->getSourceRange();
1460 if (unsigned NumArgs = CE->getNumArgs())
1461 R2 = SourceRange(CE->getArg(0)->getLocStart(),
1462 CE->getArg(NumArgs-1)->getLocEnd());
1469 case CXXTemporaryObjectExprClass:
1470 case CXXConstructExprClass:
1473 case ObjCMessageExprClass: {
1474 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
1475 const ObjCMethodDecl *MD = ME->getMethodDecl();
1476 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
1483 case ObjCPropertyRefExprClass:
1485 R1 = getSourceRange();
1488 case StmtExprClass: {
1489 // Statement exprs don't logically have side effects themselves, but are
1490 // sometimes used in macros in ways that give them a type that is unused.
1491 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
1492 // however, if the result of the stmt expr is dead, we don't want to emit a
1494 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
1495 if (!CS->body_empty()) {
1496 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
1497 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1498 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
1499 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
1500 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1503 if (getType()->isVoidType())
1505 Loc = cast<StmtExpr>(this)->getLParenLoc();
1506 R1 = getSourceRange();
1509 case CStyleCastExprClass:
1510 // If this is an explicit cast to void, allow it. People do this when they
1511 // think they know what they're doing :).
1512 if (getType()->isVoidType())
1514 Loc = cast<CStyleCastExpr>(this)->getLParenLoc();
1515 R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange();
1517 case CXXFunctionalCastExprClass: {
1518 if (getType()->isVoidType())
1520 const CastExpr *CE = cast<CastExpr>(this);
1522 // If this is a cast to void or a constructor conversion, check the operand.
1523 // Otherwise, the result of the cast is unused.
1524 if (CE->getCastKind() == CK_ToVoid ||
1525 CE->getCastKind() == CK_ConstructorConversion)
1526 return (cast<CastExpr>(this)->getSubExpr()
1527 ->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1528 Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc();
1529 R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange();
1533 case ImplicitCastExprClass:
1534 // Check the operand, since implicit casts are inserted by Sema
1535 return (cast<ImplicitCastExpr>(this)
1536 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1538 case CXXDefaultArgExprClass:
1539 return (cast<CXXDefaultArgExpr>(this)
1540 ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1542 case CXXNewExprClass:
1543 // FIXME: In theory, there might be new expressions that don't have side
1544 // effects (e.g. a placement new with an uninitialized POD).
1545 case CXXDeleteExprClass:
1547 case CXXBindTemporaryExprClass:
1548 return (cast<CXXBindTemporaryExpr>(this)
1549 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1550 case ExprWithCleanupsClass:
1551 return (cast<ExprWithCleanups>(this)
1552 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1556 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
1557 /// returns true, if it is; false otherwise.
1558 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
1559 switch (getStmtClass()) {
1562 case ObjCIvarRefExprClass:
1564 case Expr::UnaryOperatorClass:
1565 return cast<UnaryOperator>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1566 case ParenExprClass:
1567 return cast<ParenExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1568 case ImplicitCastExprClass:
1569 return cast<ImplicitCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1570 case CStyleCastExprClass:
1571 return cast<CStyleCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
1572 case DeclRefExprClass: {
1573 const Decl *D = cast<DeclRefExpr>(this)->getDecl();
1574 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1575 if (VD->hasGlobalStorage())
1577 QualType T = VD->getType();
1578 // dereferencing to a pointer is always a gc'able candidate,
1579 // unless it is __weak.
1580 return T->isPointerType() &&
1581 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
1585 case MemberExprClass: {
1586 const MemberExpr *M = cast<MemberExpr>(this);
1587 return M->getBase()->isOBJCGCCandidate(Ctx);
1589 case ArraySubscriptExprClass:
1590 return cast<ArraySubscriptExpr>(this)->getBase()->isOBJCGCCandidate(Ctx);
1594 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
1595 if (isTypeDependent())
1597 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
1600 static Expr::CanThrowResult MergeCanThrow(Expr::CanThrowResult CT1,
1601 Expr::CanThrowResult CT2) {
1602 // CanThrowResult constants are ordered so that the maximum is the correct
1604 return CT1 > CT2 ? CT1 : CT2;
1607 static Expr::CanThrowResult CanSubExprsThrow(ASTContext &C, const Expr *CE) {
1608 Expr *E = const_cast<Expr*>(CE);
1609 Expr::CanThrowResult R = Expr::CT_Cannot;
1610 for (Expr::child_range I = E->children(); I && R != Expr::CT_Can; ++I) {
1611 R = MergeCanThrow(R, cast<Expr>(*I)->CanThrow(C));
1616 static Expr::CanThrowResult CanCalleeThrow(const Decl *D,
1617 bool NullThrows = true) {
1619 return NullThrows ? Expr::CT_Can : Expr::CT_Cannot;
1621 // See if we can get a function type from the decl somehow.
1622 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
1623 if (!VD) // If we have no clue what we're calling, assume the worst.
1624 return Expr::CT_Can;
1626 // As an extension, we assume that __attribute__((nothrow)) functions don't
1628 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
1629 return Expr::CT_Cannot;
1631 QualType T = VD->getType();
1632 const FunctionProtoType *FT;
1633 if ((FT = T->getAs<FunctionProtoType>())) {
1634 } else if (const PointerType *PT = T->getAs<PointerType>())
1635 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1636 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1637 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1638 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1639 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1640 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1641 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1644 return Expr::CT_Can;
1646 return FT->hasEmptyExceptionSpec() ? Expr::CT_Cannot : Expr::CT_Can;
1649 static Expr::CanThrowResult CanDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1650 if (DC->isTypeDependent())
1651 return Expr::CT_Dependent;
1653 if (!DC->getTypeAsWritten()->isReferenceType())
1654 return Expr::CT_Cannot;
1656 return DC->getCastKind() == clang::CK_Dynamic? Expr::CT_Can : Expr::CT_Cannot;
1659 static Expr::CanThrowResult CanTypeidThrow(ASTContext &C,
1660 const CXXTypeidExpr *DC) {
1661 if (DC->isTypeOperand())
1662 return Expr::CT_Cannot;
1664 Expr *Op = DC->getExprOperand();
1665 if (Op->isTypeDependent())
1666 return Expr::CT_Dependent;
1668 const RecordType *RT = Op->getType()->getAs<RecordType>();
1670 return Expr::CT_Cannot;
1672 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1673 return Expr::CT_Cannot;
1675 if (Op->Classify(C).isPRValue())
1676 return Expr::CT_Cannot;
1678 return Expr::CT_Can;
1681 Expr::CanThrowResult Expr::CanThrow(ASTContext &C) const {
1682 // C++ [expr.unary.noexcept]p3:
1683 // [Can throw] if in a potentially-evaluated context the expression would
1685 switch (getStmtClass()) {
1686 case CXXThrowExprClass:
1687 // - a potentially evaluated throw-expression
1690 case CXXDynamicCastExprClass: {
1691 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1692 // where T is a reference type, that requires a run-time check
1693 CanThrowResult CT = CanDynamicCastThrow(cast<CXXDynamicCastExpr>(this));
1696 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1699 case CXXTypeidExprClass:
1700 // - a potentially evaluated typeid expression applied to a glvalue
1701 // expression whose type is a polymorphic class type
1702 return CanTypeidThrow(C, cast<CXXTypeidExpr>(this));
1704 // - a potentially evaluated call to a function, member function, function
1705 // pointer, or member function pointer that does not have a non-throwing
1706 // exception-specification
1708 case CXXOperatorCallExprClass:
1709 case CXXMemberCallExprClass: {
1710 CanThrowResult CT = CanCalleeThrow(cast<CallExpr>(this)->getCalleeDecl());
1713 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1716 case CXXConstructExprClass:
1717 case CXXTemporaryObjectExprClass: {
1718 CanThrowResult CT = CanCalleeThrow(
1719 cast<CXXConstructExpr>(this)->getConstructor());
1722 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1725 case CXXNewExprClass: {
1726 CanThrowResult CT = MergeCanThrow(
1727 CanCalleeThrow(cast<CXXNewExpr>(this)->getOperatorNew()),
1728 CanCalleeThrow(cast<CXXNewExpr>(this)->getConstructor(),
1729 /*NullThrows*/false));
1732 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1735 case CXXDeleteExprClass: {
1736 CanThrowResult CT = CanCalleeThrow(
1737 cast<CXXDeleteExpr>(this)->getOperatorDelete());
1740 const Expr *Arg = cast<CXXDeleteExpr>(this)->getArgument();
1741 // Unwrap exactly one implicit cast, which converts all pointers to void*.
1742 if (const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1743 Arg = Cast->getSubExpr();
1744 if (const PointerType *PT = Arg->getType()->getAs<PointerType>()) {
1745 if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>()) {
1746 CanThrowResult CT2 = CanCalleeThrow(
1747 cast<CXXRecordDecl>(RT->getDecl())->getDestructor());
1750 CT = MergeCanThrow(CT, CT2);
1753 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1756 case CXXBindTemporaryExprClass: {
1757 // The bound temporary has to be destroyed again, which might throw.
1758 CanThrowResult CT = CanCalleeThrow(
1759 cast<CXXBindTemporaryExpr>(this)->getTemporary()->getDestructor());
1762 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1765 // ObjC message sends are like function calls, but never have exception
1767 case ObjCMessageExprClass:
1768 case ObjCPropertyRefExprClass:
1771 // Many other things have subexpressions, so we have to test those.
1773 case ParenExprClass:
1774 case MemberExprClass:
1775 case CXXReinterpretCastExprClass:
1776 case CXXConstCastExprClass:
1777 case ConditionalOperatorClass:
1778 case CompoundLiteralExprClass:
1779 case ExtVectorElementExprClass:
1780 case InitListExprClass:
1781 case DesignatedInitExprClass:
1782 case ParenListExprClass:
1783 case VAArgExprClass:
1784 case CXXDefaultArgExprClass:
1785 case ExprWithCleanupsClass:
1786 case ObjCIvarRefExprClass:
1787 case ObjCIsaExprClass:
1788 case ShuffleVectorExprClass:
1789 return CanSubExprsThrow(C, this);
1791 // Some might be dependent for other reasons.
1792 case UnaryOperatorClass:
1793 case ArraySubscriptExprClass:
1794 case ImplicitCastExprClass:
1795 case CStyleCastExprClass:
1796 case CXXStaticCastExprClass:
1797 case CXXFunctionalCastExprClass:
1798 case BinaryOperatorClass:
1799 case CompoundAssignOperatorClass: {
1800 CanThrowResult CT = isTypeDependent() ? CT_Dependent : CT_Cannot;
1801 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1804 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1808 case ChooseExprClass:
1809 if (isTypeDependent() || isValueDependent())
1810 return CT_Dependent;
1811 return cast<ChooseExpr>(this)->getChosenSubExpr(C)->CanThrow(C);
1813 // Some expressions are always dependent.
1814 case DependentScopeDeclRefExprClass:
1815 case CXXUnresolvedConstructExprClass:
1816 case CXXDependentScopeMemberExprClass:
1817 return CT_Dependent;
1820 // All other expressions don't have subexpressions, or else they are
1826 Expr* Expr::IgnoreParens() {
1829 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
1830 E = P->getSubExpr();
1833 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1834 if (P->getOpcode() == UO_Extension) {
1835 E = P->getSubExpr();
1843 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
1844 /// or CastExprs or ImplicitCastExprs, returning their operand.
1845 Expr *Expr::IgnoreParenCasts() {
1848 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
1849 E = P->getSubExpr();
1852 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
1853 E = P->getSubExpr();
1856 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1857 if (P->getOpcode() == UO_Extension) {
1858 E = P->getSubExpr();
1866 /// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
1867 /// casts. This is intended purely as a temporary workaround for code
1868 /// that hasn't yet been rewritten to do the right thing about those
1869 /// casts, and may disappear along with the last internal use.
1870 Expr *Expr::IgnoreParenLValueCasts() {
1873 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1874 E = P->getSubExpr();
1876 } else if (CastExpr *P = dyn_cast<CastExpr>(E)) {
1877 if (P->getCastKind() == CK_LValueToRValue) {
1878 E = P->getSubExpr();
1881 } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1882 if (P->getOpcode() == UO_Extension) {
1883 E = P->getSubExpr();
1892 Expr *Expr::IgnoreParenImpCasts() {
1895 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1896 E = P->getSubExpr();
1899 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
1900 E = P->getSubExpr();
1903 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1904 if (P->getOpcode() == UO_Extension) {
1905 E = P->getSubExpr();
1913 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
1914 /// value (including ptr->int casts of the same size). Strip off any
1915 /// ParenExpr or CastExprs, returning their operand.
1916 Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
1919 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1920 E = P->getSubExpr();
1924 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
1925 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
1926 // ptr<->int casts of the same width. We also ignore all identity casts.
1927 Expr *SE = P->getSubExpr();
1929 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
1934 if ((E->getType()->isPointerType() ||
1935 E->getType()->isIntegralType(Ctx)) &&
1936 (SE->getType()->isPointerType() ||
1937 SE->getType()->isIntegralType(Ctx)) &&
1938 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
1944 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1945 if (P->getOpcode() == UO_Extension) {
1946 E = P->getSubExpr();
1955 bool Expr::isDefaultArgument() const {
1956 const Expr *E = this;
1957 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
1958 E = ICE->getSubExprAsWritten();
1960 return isa<CXXDefaultArgExpr>(E);
1963 /// \brief Skip over any no-op casts and any temporary-binding
1965 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
1966 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
1967 if (ICE->getCastKind() == CK_NoOp)
1968 E = ICE->getSubExpr();
1973 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
1974 E = BE->getSubExpr();
1976 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
1977 if (ICE->getCastKind() == CK_NoOp)
1978 E = ICE->getSubExpr();
1983 return E->IgnoreParens();
1986 /// isTemporaryObject - Determines if this expression produces a
1987 /// temporary of the given class type.
1988 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
1989 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
1992 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
1994 // Temporaries are by definition pr-values of class type.
1995 if (!E->Classify(C).isPRValue()) {
1996 // In this context, property reference is a message call and is pr-value.
1997 if (!isa<ObjCPropertyRefExpr>(E))
2001 // Black-list a few cases which yield pr-values of class type that don't
2002 // refer to temporaries of that type:
2004 // - implicit derived-to-base conversions
2005 if (isa<ImplicitCastExpr>(E)) {
2006 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2007 case CK_DerivedToBase:
2008 case CK_UncheckedDerivedToBase:
2015 // - member expressions (all)
2016 if (isa<MemberExpr>(E))
2019 // - opaque values (all)
2020 if (isa<OpaqueValueExpr>(E))
2026 /// hasAnyTypeDependentArguments - Determines if any of the expressions
2027 /// in Exprs is type-dependent.
2028 bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) {
2029 for (unsigned I = 0; I < NumExprs; ++I)
2030 if (Exprs[I]->isTypeDependent())
2036 /// hasAnyValueDependentArguments - Determines if any of the expressions
2037 /// in Exprs is value-dependent.
2038 bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) {
2039 for (unsigned I = 0; I < NumExprs; ++I)
2040 if (Exprs[I]->isValueDependent())
2046 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
2047 // This function is attempting whether an expression is an initializer
2048 // which can be evaluated at compile-time. isEvaluatable handles most
2049 // of the cases, but it can't deal with some initializer-specific
2050 // expressions, and it can't deal with aggregates; we deal with those here,
2051 // and fall back to isEvaluatable for the other cases.
2053 // If we ever capture reference-binding directly in the AST, we can
2054 // kill the second parameter.
2058 return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects;
2061 switch (getStmtClass()) {
2063 case StringLiteralClass:
2064 case ObjCStringLiteralClass:
2065 case ObjCEncodeExprClass:
2067 case CXXTemporaryObjectExprClass:
2068 case CXXConstructExprClass: {
2069 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2072 // 1) an application of the trivial default constructor or
2073 if (!CE->getConstructor()->isTrivial()) return false;
2074 if (!CE->getNumArgs()) return true;
2076 // 2) an elidable trivial copy construction of an operand which is
2077 // itself a constant initializer. Note that we consider the
2078 // operand on its own, *not* as a reference binding.
2079 return CE->isElidable() &&
2080 CE->getArg(0)->isConstantInitializer(Ctx, false);
2082 case CompoundLiteralExprClass: {
2083 // This handles gcc's extension that allows global initializers like
2084 // "struct x {int x;} x = (struct x) {};".
2085 // FIXME: This accepts other cases it shouldn't!
2086 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
2087 return Exp->isConstantInitializer(Ctx, false);
2089 case InitListExprClass: {
2090 // FIXME: This doesn't deal with fields with reference types correctly.
2091 // FIXME: This incorrectly allows pointers cast to integers to be assigned
2093 const InitListExpr *Exp = cast<InitListExpr>(this);
2094 unsigned numInits = Exp->getNumInits();
2095 for (unsigned i = 0; i < numInits; i++) {
2096 if (!Exp->getInit(i)->isConstantInitializer(Ctx, false))
2101 case ImplicitValueInitExprClass:
2103 case ParenExprClass:
2104 return cast<ParenExpr>(this)->getSubExpr()
2105 ->isConstantInitializer(Ctx, IsForRef);
2106 case ChooseExprClass:
2107 return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)
2108 ->isConstantInitializer(Ctx, IsForRef);
2109 case UnaryOperatorClass: {
2110 const UnaryOperator* Exp = cast<UnaryOperator>(this);
2111 if (Exp->getOpcode() == UO_Extension)
2112 return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
2115 case BinaryOperatorClass: {
2116 // Special case &&foo - &&bar. It would be nice to generalize this somehow
2117 // but this handles the common case.
2118 const BinaryOperator *Exp = cast<BinaryOperator>(this);
2119 if (Exp->getOpcode() == BO_Sub &&
2120 isa<AddrLabelExpr>(Exp->getLHS()->IgnoreParenNoopCasts(Ctx)) &&
2121 isa<AddrLabelExpr>(Exp->getRHS()->IgnoreParenNoopCasts(Ctx)))
2125 case CXXFunctionalCastExprClass:
2126 case CXXStaticCastExprClass:
2127 case ImplicitCastExprClass:
2128 case CStyleCastExprClass:
2129 // Handle casts with a destination that's a struct or union; this
2130 // deals with both the gcc no-op struct cast extension and the
2131 // cast-to-union extension.
2132 if (getType()->isRecordType())
2133 return cast<CastExpr>(this)->getSubExpr()
2134 ->isConstantInitializer(Ctx, false);
2136 // Integer->integer casts can be handled here, which is important for
2137 // things like (int)(&&x-&&y). Scary but true.
2138 if (getType()->isIntegerType() &&
2139 cast<CastExpr>(this)->getSubExpr()->getType()->isIntegerType())
2140 return cast<CastExpr>(this)->getSubExpr()
2141 ->isConstantInitializer(Ctx, false);
2145 return isEvaluatable(Ctx);
2148 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
2149 /// pointer constant or not, as well as the specific kind of constant detected.
2150 /// Null pointer constants can be integer constant expressions with the
2151 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
2152 /// (a GNU extension).
2153 Expr::NullPointerConstantKind
2154 Expr::isNullPointerConstant(ASTContext &Ctx,
2155 NullPointerConstantValueDependence NPC) const {
2156 if (isValueDependent()) {
2158 case NPC_NeverValueDependent:
2159 assert(false && "Unexpected value dependent expression!");
2160 // If the unthinkable happens, fall through to the safest alternative.
2162 case NPC_ValueDependentIsNull:
2163 if (isTypeDependent() || getType()->isIntegralType(Ctx))
2164 return NPCK_ZeroInteger;
2166 return NPCK_NotNull;
2168 case NPC_ValueDependentIsNotNull:
2169 return NPCK_NotNull;
2173 // Strip off a cast to void*, if it exists. Except in C++.
2174 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
2175 if (!Ctx.getLangOptions().CPlusPlus) {
2176 // Check that it is a cast to void*.
2177 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
2178 QualType Pointee = PT->getPointeeType();
2179 if (!Pointee.hasQualifiers() &&
2180 Pointee->isVoidType() && // to void*
2181 CE->getSubExpr()->getType()->isIntegerType()) // from int.
2182 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2185 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
2186 // Ignore the ImplicitCastExpr type entirely.
2187 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2188 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
2189 // Accept ((void*)0) as a null pointer constant, as many other
2190 // implementations do.
2191 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2192 } else if (const CXXDefaultArgExpr *DefaultArg
2193 = dyn_cast<CXXDefaultArgExpr>(this)) {
2194 // See through default argument expressions
2195 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
2196 } else if (isa<GNUNullExpr>(this)) {
2197 // The GNU __null extension is always a null pointer constant.
2198 return NPCK_GNUNull;
2201 // C++0x nullptr_t is always a null pointer constant.
2202 if (getType()->isNullPtrType())
2203 return NPCK_CXX0X_nullptr;
2205 if (const RecordType *UT = getType()->getAsUnionType())
2206 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
2207 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
2208 const Expr *InitExpr = CLE->getInitializer();
2209 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
2210 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
2212 // This expression must be an integer type.
2213 if (!getType()->isIntegerType() ||
2214 (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType()))
2215 return NPCK_NotNull;
2217 // If we have an integer constant expression, we need to *evaluate* it and
2218 // test for the value 0.
2219 llvm::APSInt Result;
2220 bool IsNull = isIntegerConstantExpr(Result, Ctx) && Result == 0;
2222 return (IsNull ? NPCK_ZeroInteger : NPCK_NotNull);
2225 /// \brief If this expression is an l-value for an Objective C
2226 /// property, find the underlying property reference expression.
2227 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
2228 const Expr *E = this;
2230 assert((E->getValueKind() == VK_LValue &&
2231 E->getObjectKind() == OK_ObjCProperty) &&
2232 "expression is not a property reference");
2233 E = E->IgnoreParenCasts();
2234 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2235 if (BO->getOpcode() == BO_Comma) {
2244 return cast<ObjCPropertyRefExpr>(E);
2247 FieldDecl *Expr::getBitField() {
2248 Expr *E = this->IgnoreParens();
2250 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2251 if (ICE->getCastKind() == CK_LValueToRValue ||
2252 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
2253 E = ICE->getSubExpr()->IgnoreParens();
2258 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
2259 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
2260 if (Field->isBitField())
2263 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
2264 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
2265 if (Field->isBitField())
2268 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E))
2269 if (BinOp->isAssignmentOp() && BinOp->getLHS())
2270 return BinOp->getLHS()->getBitField();
2275 bool Expr::refersToVectorElement() const {
2276 const Expr *E = this->IgnoreParens();
2278 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2279 if (ICE->getValueKind() != VK_RValue &&
2280 ICE->getCastKind() == CK_NoOp)
2281 E = ICE->getSubExpr()->IgnoreParens();
2286 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
2287 return ASE->getBase()->getType()->isVectorType();
2289 if (isa<ExtVectorElementExpr>(E))
2295 /// isArrow - Return true if the base expression is a pointer to vector,
2296 /// return false if the base expression is a vector.
2297 bool ExtVectorElementExpr::isArrow() const {
2298 return getBase()->getType()->isPointerType();
2301 unsigned ExtVectorElementExpr::getNumElements() const {
2302 if (const VectorType *VT = getType()->getAs<VectorType>())
2303 return VT->getNumElements();
2307 /// containsDuplicateElements - Return true if any element access is repeated.
2308 bool ExtVectorElementExpr::containsDuplicateElements() const {
2309 // FIXME: Refactor this code to an accessor on the AST node which returns the
2310 // "type" of component access, and share with code below and in Sema.
2311 llvm::StringRef Comp = Accessor->getName();
2313 // Halving swizzles do not contain duplicate elements.
2314 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
2317 // Advance past s-char prefix on hex swizzles.
2318 if (Comp[0] == 's' || Comp[0] == 'S')
2319 Comp = Comp.substr(1);
2321 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
2322 if (Comp.substr(i + 1).find(Comp[i]) != llvm::StringRef::npos)
2328 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
2329 void ExtVectorElementExpr::getEncodedElementAccess(
2330 llvm::SmallVectorImpl<unsigned> &Elts) const {
2331 llvm::StringRef Comp = Accessor->getName();
2332 if (Comp[0] == 's' || Comp[0] == 'S')
2333 Comp = Comp.substr(1);
2335 bool isHi = Comp == "hi";
2336 bool isLo = Comp == "lo";
2337 bool isEven = Comp == "even";
2338 bool isOdd = Comp == "odd";
2340 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2352 Index = ExtVectorType::getAccessorIdx(Comp[i]);
2354 Elts.push_back(Index);
2358 ObjCMessageExpr::ObjCMessageExpr(QualType T,
2360 SourceLocation LBracLoc,
2361 SourceLocation SuperLoc,
2362 bool IsInstanceSuper,
2365 SourceLocation SelLoc,
2366 ObjCMethodDecl *Method,
2367 Expr **Args, unsigned NumArgs,
2368 SourceLocation RBracLoc)
2369 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
2370 /*TypeDependent=*/false, /*ValueDependent=*/false,
2371 /*ContainsUnexpandedParameterPack=*/false),
2372 NumArgs(NumArgs), Kind(IsInstanceSuper? SuperInstance : SuperClass),
2373 HasMethod(Method != 0), SuperLoc(SuperLoc),
2374 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2375 : Sel.getAsOpaquePtr())),
2376 SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2378 setReceiverPointer(SuperType.getAsOpaquePtr());
2380 memcpy(getArgs(), Args, NumArgs * sizeof(Expr *));
2383 ObjCMessageExpr::ObjCMessageExpr(QualType T,
2385 SourceLocation LBracLoc,
2386 TypeSourceInfo *Receiver,
2388 SourceLocation SelLoc,
2389 ObjCMethodDecl *Method,
2390 Expr **Args, unsigned NumArgs,
2391 SourceLocation RBracLoc)
2392 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
2393 T->isDependentType(), T->containsUnexpandedParameterPack()),
2394 NumArgs(NumArgs), Kind(Class), HasMethod(Method != 0),
2395 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2396 : Sel.getAsOpaquePtr())),
2397 SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2399 setReceiverPointer(Receiver);
2400 Expr **MyArgs = getArgs();
2401 for (unsigned I = 0; I != NumArgs; ++I) {
2402 if (Args[I]->isTypeDependent())
2403 ExprBits.TypeDependent = true;
2404 if (Args[I]->isValueDependent())
2405 ExprBits.ValueDependent = true;
2406 if (Args[I]->containsUnexpandedParameterPack())
2407 ExprBits.ContainsUnexpandedParameterPack = true;
2409 MyArgs[I] = Args[I];
2413 ObjCMessageExpr::ObjCMessageExpr(QualType T,
2415 SourceLocation LBracLoc,
2418 SourceLocation SelLoc,
2419 ObjCMethodDecl *Method,
2420 Expr **Args, unsigned NumArgs,
2421 SourceLocation RBracLoc)
2422 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(),
2423 Receiver->isTypeDependent(),
2424 Receiver->containsUnexpandedParameterPack()),
2425 NumArgs(NumArgs), Kind(Instance), HasMethod(Method != 0),
2426 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2427 : Sel.getAsOpaquePtr())),
2428 SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2430 setReceiverPointer(Receiver);
2431 Expr **MyArgs = getArgs();
2432 for (unsigned I = 0; I != NumArgs; ++I) {
2433 if (Args[I]->isTypeDependent())
2434 ExprBits.TypeDependent = true;
2435 if (Args[I]->isValueDependent())
2436 ExprBits.ValueDependent = true;
2437 if (Args[I]->containsUnexpandedParameterPack())
2438 ExprBits.ContainsUnexpandedParameterPack = true;
2440 MyArgs[I] = Args[I];
2444 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2446 SourceLocation LBracLoc,
2447 SourceLocation SuperLoc,
2448 bool IsInstanceSuper,
2451 SourceLocation SelLoc,
2452 ObjCMethodDecl *Method,
2453 Expr **Args, unsigned NumArgs,
2454 SourceLocation RBracLoc) {
2455 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2456 NumArgs * sizeof(Expr *);
2457 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2458 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper,
2459 SuperType, Sel, SelLoc, Method, Args,NumArgs,
2463 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2465 SourceLocation LBracLoc,
2466 TypeSourceInfo *Receiver,
2468 SourceLocation SelLoc,
2469 ObjCMethodDecl *Method,
2470 Expr **Args, unsigned NumArgs,
2471 SourceLocation RBracLoc) {
2472 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2473 NumArgs * sizeof(Expr *);
2474 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2475 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, SelLoc,
2476 Method, Args, NumArgs, RBracLoc);
2479 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2481 SourceLocation LBracLoc,
2484 SourceLocation SelLoc,
2485 ObjCMethodDecl *Method,
2486 Expr **Args, unsigned NumArgs,
2487 SourceLocation RBracLoc) {
2488 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2489 NumArgs * sizeof(Expr *);
2490 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2491 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, SelLoc,
2492 Method, Args, NumArgs, RBracLoc);
2495 ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,
2497 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2498 NumArgs * sizeof(Expr *);
2499 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2500 return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
2503 SourceRange ObjCMessageExpr::getReceiverRange() const {
2504 switch (getReceiverKind()) {
2506 return getInstanceReceiver()->getSourceRange();
2509 return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange();
2513 return getSuperLoc();
2516 return SourceLocation();
2519 Selector ObjCMessageExpr::getSelector() const {
2521 return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
2523 return Selector(SelectorOrMethod);
2526 ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
2527 switch (getReceiverKind()) {
2529 if (const ObjCObjectPointerType *Ptr
2530 = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>())
2531 return Ptr->getInterfaceDecl();
2535 if (const ObjCObjectType *Ty
2536 = getClassReceiver()->getAs<ObjCObjectType>())
2537 return Ty->getInterface();
2541 if (const ObjCObjectPointerType *Ptr
2542 = getSuperType()->getAs<ObjCObjectPointerType>())
2543 return Ptr->getInterfaceDecl();
2547 if (const ObjCObjectType *Iface
2548 = getSuperType()->getAs<ObjCObjectType>())
2549 return Iface->getInterface();
2556 bool ChooseExpr::isConditionTrue(const ASTContext &C) const {
2557 return getCond()->EvaluateAsInt(C) != 0;
2560 ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2561 QualType Type, SourceLocation BLoc,
2563 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
2564 Type->isDependentType(), Type->isDependentType(),
2565 Type->containsUnexpandedParameterPack()),
2566 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr)
2568 SubExprs = new (C) Stmt*[nexpr];
2569 for (unsigned i = 0; i < nexpr; i++) {
2570 if (args[i]->isTypeDependent())
2571 ExprBits.TypeDependent = true;
2572 if (args[i]->isValueDependent())
2573 ExprBits.ValueDependent = true;
2574 if (args[i]->containsUnexpandedParameterPack())
2575 ExprBits.ContainsUnexpandedParameterPack = true;
2577 SubExprs[i] = args[i];
2581 void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
2582 unsigned NumExprs) {
2583 if (SubExprs) C.Deallocate(SubExprs);
2585 SubExprs = new (C) Stmt* [NumExprs];
2586 this->NumExprs = NumExprs;
2587 memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
2590 //===----------------------------------------------------------------------===//
2591 // DesignatedInitExpr
2592 //===----------------------------------------------------------------------===//
2594 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() {
2595 assert(Kind == FieldDesignator && "Only valid on a field designator");
2596 if (Field.NameOrField & 0x01)
2597 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
2599 return getField()->getIdentifier();
2602 DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty,
2603 unsigned NumDesignators,
2604 const Designator *Designators,
2605 SourceLocation EqualOrColonLoc,
2608 unsigned NumIndexExprs,
2610 : Expr(DesignatedInitExprClass, Ty,
2611 Init->getValueKind(), Init->getObjectKind(),
2612 Init->isTypeDependent(), Init->isValueDependent(),
2613 Init->containsUnexpandedParameterPack()),
2614 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
2615 NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) {
2616 this->Designators = new (C) Designator[NumDesignators];
2618 // Record the initializer itself.
2619 child_range Child = children();
2622 // Copy the designators and their subexpressions, computing
2623 // value-dependence along the way.
2624 unsigned IndexIdx = 0;
2625 for (unsigned I = 0; I != NumDesignators; ++I) {
2626 this->Designators[I] = Designators[I];
2628 if (this->Designators[I].isArrayDesignator()) {
2629 // Compute type- and value-dependence.
2630 Expr *Index = IndexExprs[IndexIdx];
2631 if (Index->isTypeDependent() || Index->isValueDependent())
2632 ExprBits.ValueDependent = true;
2634 // Propagate unexpanded parameter packs.
2635 if (Index->containsUnexpandedParameterPack())
2636 ExprBits.ContainsUnexpandedParameterPack = true;
2638 // Copy the index expressions into permanent storage.
2639 *Child++ = IndexExprs[IndexIdx++];
2640 } else if (this->Designators[I].isArrayRangeDesignator()) {
2641 // Compute type- and value-dependence.
2642 Expr *Start = IndexExprs[IndexIdx];
2643 Expr *End = IndexExprs[IndexIdx + 1];
2644 if (Start->isTypeDependent() || Start->isValueDependent() ||
2645 End->isTypeDependent() || End->isValueDependent())
2646 ExprBits.ValueDependent = true;
2648 // Propagate unexpanded parameter packs.
2649 if (Start->containsUnexpandedParameterPack() ||
2650 End->containsUnexpandedParameterPack())
2651 ExprBits.ContainsUnexpandedParameterPack = true;
2653 // Copy the start/end expressions into permanent storage.
2654 *Child++ = IndexExprs[IndexIdx++];
2655 *Child++ = IndexExprs[IndexIdx++];
2659 assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions");
2662 DesignatedInitExpr *
2663 DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
2664 unsigned NumDesignators,
2665 Expr **IndexExprs, unsigned NumIndexExprs,
2666 SourceLocation ColonOrEqualLoc,
2667 bool UsesColonSyntax, Expr *Init) {
2668 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
2669 sizeof(Stmt *) * (NumIndexExprs + 1), 8);
2670 return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
2671 ColonOrEqualLoc, UsesColonSyntax,
2672 IndexExprs, NumIndexExprs, Init);
2675 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
2676 unsigned NumIndexExprs) {
2677 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
2678 sizeof(Stmt *) * (NumIndexExprs + 1), 8);
2679 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
2682 void DesignatedInitExpr::setDesignators(ASTContext &C,
2683 const Designator *Desigs,
2684 unsigned NumDesigs) {
2685 Designators = new (C) Designator[NumDesigs];
2686 NumDesignators = NumDesigs;
2687 for (unsigned I = 0; I != NumDesigs; ++I)
2688 Designators[I] = Desigs[I];
2691 SourceRange DesignatedInitExpr::getSourceRange() const {
2692 SourceLocation StartLoc;
2694 *const_cast<DesignatedInitExpr*>(this)->designators_begin();
2695 if (First.isFieldDesignator()) {
2697 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
2699 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
2702 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
2703 return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
2706 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
2707 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
2708 char* Ptr = static_cast<char*>(static_cast<void *>(this));
2709 Ptr += sizeof(DesignatedInitExpr);
2710 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2711 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2714 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
2715 assert(D.Kind == Designator::ArrayRangeDesignator &&
2716 "Requires array range designator");
2717 char* Ptr = static_cast<char*>(static_cast<void *>(this));
2718 Ptr += sizeof(DesignatedInitExpr);
2719 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2720 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2723 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
2724 assert(D.Kind == Designator::ArrayRangeDesignator &&
2725 "Requires array range designator");
2726 char* Ptr = static_cast<char*>(static_cast<void *>(this));
2727 Ptr += sizeof(DesignatedInitExpr);
2728 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2729 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
2732 /// \brief Replaces the designator at index @p Idx with the series
2733 /// of designators in [First, Last).
2734 void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx,
2735 const Designator *First,
2736 const Designator *Last) {
2737 unsigned NumNewDesignators = Last - First;
2738 if (NumNewDesignators == 0) {
2739 std::copy_backward(Designators + Idx + 1,
2740 Designators + NumDesignators,
2742 --NumNewDesignators;
2744 } else if (NumNewDesignators == 1) {
2745 Designators[Idx] = *First;
2749 Designator *NewDesignators
2750 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
2751 std::copy(Designators, Designators + Idx, NewDesignators);
2752 std::copy(First, Last, NewDesignators + Idx);
2753 std::copy(Designators + Idx + 1, Designators + NumDesignators,
2754 NewDesignators + Idx + NumNewDesignators);
2755 Designators = NewDesignators;
2756 NumDesignators = NumDesignators - 1 + NumNewDesignators;
2759 ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
2760 Expr **exprs, unsigned nexprs,
2761 SourceLocation rparenloc)
2762 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
2763 false, false, false),
2764 NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
2766 Exprs = new (C) Stmt*[nexprs];
2767 for (unsigned i = 0; i != nexprs; ++i) {
2768 if (exprs[i]->isTypeDependent())
2769 ExprBits.TypeDependent = true;
2770 if (exprs[i]->isValueDependent())
2771 ExprBits.ValueDependent = true;
2772 if (exprs[i]->containsUnexpandedParameterPack())
2773 ExprBits.ContainsUnexpandedParameterPack = true;
2775 Exprs[i] = exprs[i];
2779 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
2780 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
2781 e = ewc->getSubExpr();
2782 e = cast<CXXConstructExpr>(e)->getArg(0);
2783 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2784 e = ice->getSubExpr();
2785 return cast<OpaqueValueExpr>(e);
2788 //===----------------------------------------------------------------------===//
2790 //===----------------------------------------------------------------------===//
2792 Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
2793 Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
2794 Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
2795 const Expr* ConstExprIterator::operator[](size_t idx) const {
2796 return cast<Expr>(I[idx]);
2798 const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
2799 const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
2801 //===----------------------------------------------------------------------===//
2802 // Child Iterators for iterating over subexpressions/substatements
2803 //===----------------------------------------------------------------------===//
2805 // SizeOfAlignOfExpr
2806 Stmt::child_range SizeOfAlignOfExpr::children() {
2807 // If this is of a type and the type is a VLA type (and not a typedef), the
2808 // size expression of the VLA needs to be treated as an executable expression.
2809 // Why isn't this weirdness documented better in StmtIterator?
2810 if (isArgumentType()) {
2811 if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
2812 getArgumentType().getTypePtr()))
2813 return child_range(child_iterator(T), child_iterator());
2814 return child_range();
2816 return child_range(&Argument.Ex, &Argument.Ex + 1);
2820 Stmt::child_range ObjCMessageExpr::children() {
2822 if (getReceiverKind() == Instance)
2823 begin = reinterpret_cast<Stmt **>(this + 1);
2825 begin = reinterpret_cast<Stmt **>(getArgs());
2826 return child_range(begin,
2827 reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
2831 BlockDeclRefExpr::BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
2832 SourceLocation l, bool ByRef,
2834 : Expr(BlockDeclRefExprClass, t, VK, OK_Ordinary, false, false,
2835 d->isParameterPack()),
2836 D(d), Loc(l), IsByRef(ByRef), ConstQualAdded(constAdded)
2838 bool TypeDependent = false;
2839 bool ValueDependent = false;
2840 computeDeclRefDependence(D, getType(), TypeDependent, ValueDependent);
2841 ExprBits.TypeDependent = TypeDependent;
2842 ExprBits.ValueDependent = ValueDependent;