Expr.cpp revision 663e380d7b2de2bbf20e886e05371195bea9adc4
1//===--- Expr.cpp - Expression AST Node Implementation --------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the Expr class and subclasses. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/AST/Expr.h" 15#include "clang/AST/ExprCXX.h" 16#include "clang/AST/APValue.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/DeclObjC.h" 19#include "clang/AST/DeclCXX.h" 20#include "clang/AST/DeclTemplate.h" 21#include "clang/AST/RecordLayout.h" 22#include "clang/AST/StmtVisitor.h" 23#include "clang/Basic/Builtins.h" 24#include "clang/Basic/TargetInfo.h" 25#include "llvm/Support/ErrorHandling.h" 26#include "llvm/Support/raw_ostream.h" 27#include <algorithm> 28using namespace clang; 29 30void Expr::ANCHOR() {} // key function for Expr class. 31 32/// isKnownToHaveBooleanValue - Return true if this is an integer expression 33/// that is known to return 0 or 1. This happens for _Bool/bool expressions 34/// but also int expressions which are produced by things like comparisons in 35/// C. 36bool Expr::isKnownToHaveBooleanValue() const { 37 // If this value has _Bool type, it is obvious 0/1. 38 if (getType()->isBooleanType()) return true; 39 // If this is a non-scalar-integer type, we don't care enough to try. 40 if (!getType()->isIntegralOrEnumerationType()) return false; 41 42 if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) 43 return PE->getSubExpr()->isKnownToHaveBooleanValue(); 44 45 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(this)) { 46 switch (UO->getOpcode()) { 47 case UnaryOperator::Plus: 48 case UnaryOperator::Extension: 49 return UO->getSubExpr()->isKnownToHaveBooleanValue(); 50 default: 51 return false; 52 } 53 } 54 55 // Only look through implicit casts. If the user writes 56 // '(int) (a && b)' treat it as an arbitrary int. 57 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(this)) 58 return CE->getSubExpr()->isKnownToHaveBooleanValue(); 59 60 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(this)) { 61 switch (BO->getOpcode()) { 62 default: return false; 63 case BinaryOperator::LT: // Relational operators. 64 case BinaryOperator::GT: 65 case BinaryOperator::LE: 66 case BinaryOperator::GE: 67 case BinaryOperator::EQ: // Equality operators. 68 case BinaryOperator::NE: 69 case BinaryOperator::LAnd: // AND operator. 70 case BinaryOperator::LOr: // Logical OR operator. 71 return true; 72 73 case BinaryOperator::And: // Bitwise AND operator. 74 case BinaryOperator::Xor: // Bitwise XOR operator. 75 case BinaryOperator::Or: // Bitwise OR operator. 76 // Handle things like (x==2)|(y==12). 77 return BO->getLHS()->isKnownToHaveBooleanValue() && 78 BO->getRHS()->isKnownToHaveBooleanValue(); 79 80 case BinaryOperator::Comma: 81 case BinaryOperator::Assign: 82 return BO->getRHS()->isKnownToHaveBooleanValue(); 83 } 84 } 85 86 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(this)) 87 return CO->getTrueExpr()->isKnownToHaveBooleanValue() && 88 CO->getFalseExpr()->isKnownToHaveBooleanValue(); 89 90 return false; 91} 92 93//===----------------------------------------------------------------------===// 94// Primary Expressions. 95//===----------------------------------------------------------------------===// 96 97void ExplicitTemplateArgumentList::initializeFrom( 98 const TemplateArgumentListInfo &Info) { 99 LAngleLoc = Info.getLAngleLoc(); 100 RAngleLoc = Info.getRAngleLoc(); 101 NumTemplateArgs = Info.size(); 102 103 TemplateArgumentLoc *ArgBuffer = getTemplateArgs(); 104 for (unsigned i = 0; i != NumTemplateArgs; ++i) 105 new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]); 106} 107 108void ExplicitTemplateArgumentList::copyInto( 109 TemplateArgumentListInfo &Info) const { 110 Info.setLAngleLoc(LAngleLoc); 111 Info.setRAngleLoc(RAngleLoc); 112 for (unsigned I = 0; I != NumTemplateArgs; ++I) 113 Info.addArgument(getTemplateArgs()[I]); 114} 115 116std::size_t ExplicitTemplateArgumentList::sizeFor(unsigned NumTemplateArgs) { 117 return sizeof(ExplicitTemplateArgumentList) + 118 sizeof(TemplateArgumentLoc) * NumTemplateArgs; 119} 120 121std::size_t ExplicitTemplateArgumentList::sizeFor( 122 const TemplateArgumentListInfo &Info) { 123 return sizeFor(Info.size()); 124} 125 126void DeclRefExpr::computeDependence() { 127 TypeDependent = false; 128 ValueDependent = false; 129 130 NamedDecl *D = getDecl(); 131 132 // (TD) C++ [temp.dep.expr]p3: 133 // An id-expression is type-dependent if it contains: 134 // 135 // and 136 // 137 // (VD) C++ [temp.dep.constexpr]p2: 138 // An identifier is value-dependent if it is: 139 140 // (TD) - an identifier that was declared with dependent type 141 // (VD) - a name declared with a dependent type, 142 if (getType()->isDependentType()) { 143 TypeDependent = true; 144 ValueDependent = true; 145 } 146 // (TD) - a conversion-function-id that specifies a dependent type 147 else if (D->getDeclName().getNameKind() 148 == DeclarationName::CXXConversionFunctionName && 149 D->getDeclName().getCXXNameType()->isDependentType()) { 150 TypeDependent = true; 151 ValueDependent = true; 152 } 153 // (TD) - a template-id that is dependent, 154 else if (hasExplicitTemplateArgumentList() && 155 TemplateSpecializationType::anyDependentTemplateArguments( 156 getTemplateArgs(), 157 getNumTemplateArgs())) { 158 TypeDependent = true; 159 ValueDependent = true; 160 } 161 // (VD) - the name of a non-type template parameter, 162 else if (isa<NonTypeTemplateParmDecl>(D)) 163 ValueDependent = true; 164 // (VD) - a constant with integral or enumeration type and is 165 // initialized with an expression that is value-dependent. 166 else if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 167 if (Var->getType()->isIntegralOrEnumerationType() && 168 Var->getType().getCVRQualifiers() == Qualifiers::Const) { 169 if (const Expr *Init = Var->getAnyInitializer()) 170 if (Init->isValueDependent()) 171 ValueDependent = true; 172 } 173 // (VD) - FIXME: Missing from the standard: 174 // - a member function or a static data member of the current 175 // instantiation 176 else if (Var->isStaticDataMember() && 177 Var->getDeclContext()->isDependentContext()) 178 ValueDependent = true; 179 } 180 // (VD) - FIXME: Missing from the standard: 181 // - a member function or a static data member of the current 182 // instantiation 183 else if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) 184 ValueDependent = true; 185 // (TD) - a nested-name-specifier or a qualified-id that names a 186 // member of an unknown specialization. 187 // (handled by DependentScopeDeclRefExpr) 188} 189 190DeclRefExpr::DeclRefExpr(NestedNameSpecifier *Qualifier, 191 SourceRange QualifierRange, 192 ValueDecl *D, SourceLocation NameLoc, 193 const TemplateArgumentListInfo *TemplateArgs, 194 QualType T) 195 : Expr(DeclRefExprClass, T, false, false), 196 DecoratedD(D, 197 (Qualifier? HasQualifierFlag : 0) | 198 (TemplateArgs ? HasExplicitTemplateArgumentListFlag : 0)), 199 Loc(NameLoc) { 200 if (Qualifier) { 201 NameQualifier *NQ = getNameQualifier(); 202 NQ->NNS = Qualifier; 203 NQ->Range = QualifierRange; 204 } 205 206 if (TemplateArgs) 207 getExplicitTemplateArgumentList()->initializeFrom(*TemplateArgs); 208 209 computeDependence(); 210} 211 212DeclRefExpr *DeclRefExpr::Create(ASTContext &Context, 213 NestedNameSpecifier *Qualifier, 214 SourceRange QualifierRange, 215 ValueDecl *D, 216 SourceLocation NameLoc, 217 QualType T, 218 const TemplateArgumentListInfo *TemplateArgs) { 219 std::size_t Size = sizeof(DeclRefExpr); 220 if (Qualifier != 0) 221 Size += sizeof(NameQualifier); 222 223 if (TemplateArgs) 224 Size += ExplicitTemplateArgumentList::sizeFor(*TemplateArgs); 225 226 void *Mem = Context.Allocate(Size, llvm::alignof<DeclRefExpr>()); 227 return new (Mem) DeclRefExpr(Qualifier, QualifierRange, D, NameLoc, 228 TemplateArgs, T); 229} 230 231DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context, bool HasQualifier, 232 unsigned NumTemplateArgs) { 233 std::size_t Size = sizeof(DeclRefExpr); 234 if (HasQualifier) 235 Size += sizeof(NameQualifier); 236 237 if (NumTemplateArgs) 238 Size += ExplicitTemplateArgumentList::sizeFor(NumTemplateArgs); 239 240 void *Mem = Context.Allocate(Size, llvm::alignof<DeclRefExpr>()); 241 return new (Mem) DeclRefExpr(EmptyShell()); 242} 243 244SourceRange DeclRefExpr::getSourceRange() const { 245 // FIXME: Does not handle multi-token names well, e.g., operator[]. 246 SourceRange R(Loc); 247 248 if (hasQualifier()) 249 R.setBegin(getQualifierRange().getBegin()); 250 if (hasExplicitTemplateArgumentList()) 251 R.setEnd(getRAngleLoc()); 252 return R; 253} 254 255// FIXME: Maybe this should use DeclPrinter with a special "print predefined 256// expr" policy instead. 257std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) { 258 ASTContext &Context = CurrentDecl->getASTContext(); 259 260 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) { 261 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual) 262 return FD->getNameAsString(); 263 264 llvm::SmallString<256> Name; 265 llvm::raw_svector_ostream Out(Name); 266 267 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 268 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual) 269 Out << "virtual "; 270 if (MD->isStatic()) 271 Out << "static "; 272 } 273 274 PrintingPolicy Policy(Context.getLangOptions()); 275 276 std::string Proto = FD->getQualifiedNameAsString(Policy); 277 278 const FunctionType *AFT = FD->getType()->getAs<FunctionType>(); 279 const FunctionProtoType *FT = 0; 280 if (FD->hasWrittenPrototype()) 281 FT = dyn_cast<FunctionProtoType>(AFT); 282 283 Proto += "("; 284 if (FT) { 285 llvm::raw_string_ostream POut(Proto); 286 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 287 if (i) POut << ", "; 288 std::string Param; 289 FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy); 290 POut << Param; 291 } 292 293 if (FT->isVariadic()) { 294 if (FD->getNumParams()) POut << ", "; 295 POut << "..."; 296 } 297 } 298 Proto += ")"; 299 300 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 301 Qualifiers ThisQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers()); 302 if (ThisQuals.hasConst()) 303 Proto += " const"; 304 if (ThisQuals.hasVolatile()) 305 Proto += " volatile"; 306 } 307 308 if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD)) 309 AFT->getResultType().getAsStringInternal(Proto, Policy); 310 311 Out << Proto; 312 313 Out.flush(); 314 return Name.str().str(); 315 } 316 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) { 317 llvm::SmallString<256> Name; 318 llvm::raw_svector_ostream Out(Name); 319 Out << (MD->isInstanceMethod() ? '-' : '+'); 320 Out << '['; 321 322 // For incorrect code, there might not be an ObjCInterfaceDecl. Do 323 // a null check to avoid a crash. 324 if (const ObjCInterfaceDecl *ID = MD->getClassInterface()) 325 Out << ID; 326 327 if (const ObjCCategoryImplDecl *CID = 328 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext())) 329 Out << '(' << CID << ')'; 330 331 Out << ' '; 332 Out << MD->getSelector().getAsString(); 333 Out << ']'; 334 335 Out.flush(); 336 return Name.str().str(); 337 } 338 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) { 339 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string. 340 return "top level"; 341 } 342 return ""; 343} 344 345/// getValueAsApproximateDouble - This returns the value as an inaccurate 346/// double. Note that this may cause loss of precision, but is useful for 347/// debugging dumps, etc. 348double FloatingLiteral::getValueAsApproximateDouble() const { 349 llvm::APFloat V = getValue(); 350 bool ignored; 351 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven, 352 &ignored); 353 return V.convertToDouble(); 354} 355 356StringLiteral *StringLiteral::Create(ASTContext &C, const char *StrData, 357 unsigned ByteLength, bool Wide, 358 QualType Ty, 359 const SourceLocation *Loc, 360 unsigned NumStrs) { 361 // Allocate enough space for the StringLiteral plus an array of locations for 362 // any concatenated string tokens. 363 void *Mem = C.Allocate(sizeof(StringLiteral)+ 364 sizeof(SourceLocation)*(NumStrs-1), 365 llvm::alignof<StringLiteral>()); 366 StringLiteral *SL = new (Mem) StringLiteral(Ty); 367 368 // OPTIMIZE: could allocate this appended to the StringLiteral. 369 char *AStrData = new (C, 1) char[ByteLength]; 370 memcpy(AStrData, StrData, ByteLength); 371 SL->StrData = AStrData; 372 SL->ByteLength = ByteLength; 373 SL->IsWide = Wide; 374 SL->TokLocs[0] = Loc[0]; 375 SL->NumConcatenated = NumStrs; 376 377 if (NumStrs != 1) 378 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1)); 379 return SL; 380} 381 382StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) { 383 void *Mem = C.Allocate(sizeof(StringLiteral)+ 384 sizeof(SourceLocation)*(NumStrs-1), 385 llvm::alignof<StringLiteral>()); 386 StringLiteral *SL = new (Mem) StringLiteral(QualType()); 387 SL->StrData = 0; 388 SL->ByteLength = 0; 389 SL->NumConcatenated = NumStrs; 390 return SL; 391} 392 393void StringLiteral::DoDestroy(ASTContext &C) { 394 C.Deallocate(const_cast<char*>(StrData)); 395 Expr::DoDestroy(C); 396} 397 398void StringLiteral::setString(ASTContext &C, llvm::StringRef Str) { 399 if (StrData) 400 C.Deallocate(const_cast<char*>(StrData)); 401 402 char *AStrData = new (C, 1) char[Str.size()]; 403 memcpy(AStrData, Str.data(), Str.size()); 404 StrData = AStrData; 405 ByteLength = Str.size(); 406} 407 408/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 409/// corresponds to, e.g. "sizeof" or "[pre]++". 410const char *UnaryOperator::getOpcodeStr(Opcode Op) { 411 switch (Op) { 412 default: assert(0 && "Unknown unary operator"); 413 case PostInc: return "++"; 414 case PostDec: return "--"; 415 case PreInc: return "++"; 416 case PreDec: return "--"; 417 case AddrOf: return "&"; 418 case Deref: return "*"; 419 case Plus: return "+"; 420 case Minus: return "-"; 421 case Not: return "~"; 422 case LNot: return "!"; 423 case Real: return "__real"; 424 case Imag: return "__imag"; 425 case Extension: return "__extension__"; 426 case OffsetOf: return "__builtin_offsetof"; 427 } 428} 429 430UnaryOperator::Opcode 431UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) { 432 switch (OO) { 433 default: assert(false && "No unary operator for overloaded function"); 434 case OO_PlusPlus: return Postfix ? PostInc : PreInc; 435 case OO_MinusMinus: return Postfix ? PostDec : PreDec; 436 case OO_Amp: return AddrOf; 437 case OO_Star: return Deref; 438 case OO_Plus: return Plus; 439 case OO_Minus: return Minus; 440 case OO_Tilde: return Not; 441 case OO_Exclaim: return LNot; 442 } 443} 444 445OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) { 446 switch (Opc) { 447 case PostInc: case PreInc: return OO_PlusPlus; 448 case PostDec: case PreDec: return OO_MinusMinus; 449 case AddrOf: return OO_Amp; 450 case Deref: return OO_Star; 451 case Plus: return OO_Plus; 452 case Minus: return OO_Minus; 453 case Not: return OO_Tilde; 454 case LNot: return OO_Exclaim; 455 default: return OO_None; 456 } 457} 458 459 460//===----------------------------------------------------------------------===// 461// Postfix Operators. 462//===----------------------------------------------------------------------===// 463 464CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, 465 unsigned numargs, QualType t, SourceLocation rparenloc) 466 : Expr(SC, t, 467 fn->isTypeDependent() || hasAnyTypeDependentArguments(args, numargs), 468 fn->isValueDependent() || hasAnyValueDependentArguments(args,numargs)), 469 NumArgs(numargs) { 470 471 SubExprs = new (C) Stmt*[numargs+1]; 472 SubExprs[FN] = fn; 473 for (unsigned i = 0; i != numargs; ++i) 474 SubExprs[i+ARGS_START] = args[i]; 475 476 RParenLoc = rparenloc; 477} 478 479CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, 480 QualType t, SourceLocation rparenloc) 481 : Expr(CallExprClass, t, 482 fn->isTypeDependent() || hasAnyTypeDependentArguments(args, numargs), 483 fn->isValueDependent() || hasAnyValueDependentArguments(args,numargs)), 484 NumArgs(numargs) { 485 486 SubExprs = new (C) Stmt*[numargs+1]; 487 SubExprs[FN] = fn; 488 for (unsigned i = 0; i != numargs; ++i) 489 SubExprs[i+ARGS_START] = args[i]; 490 491 RParenLoc = rparenloc; 492} 493 494CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty) 495 : Expr(SC, Empty), SubExprs(0), NumArgs(0) { 496 SubExprs = new (C) Stmt*[1]; 497} 498 499void CallExpr::DoDestroy(ASTContext& C) { 500 DestroyChildren(C); 501 if (SubExprs) C.Deallocate(SubExprs); 502 this->~CallExpr(); 503 C.Deallocate(this); 504} 505 506Decl *CallExpr::getCalleeDecl() { 507 Expr *CEE = getCallee()->IgnoreParenCasts(); 508 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) 509 return DRE->getDecl(); 510 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE)) 511 return ME->getMemberDecl(); 512 513 return 0; 514} 515 516FunctionDecl *CallExpr::getDirectCallee() { 517 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); 518} 519 520/// setNumArgs - This changes the number of arguments present in this call. 521/// Any orphaned expressions are deleted by this, and any new operands are set 522/// to null. 523void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) { 524 // No change, just return. 525 if (NumArgs == getNumArgs()) return; 526 527 // If shrinking # arguments, just delete the extras and forgot them. 528 if (NumArgs < getNumArgs()) { 529 for (unsigned i = NumArgs, e = getNumArgs(); i != e; ++i) 530 getArg(i)->Destroy(C); 531 this->NumArgs = NumArgs; 532 return; 533 } 534 535 // Otherwise, we are growing the # arguments. New an bigger argument array. 536 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+1]; 537 // Copy over args. 538 for (unsigned i = 0; i != getNumArgs()+ARGS_START; ++i) 539 NewSubExprs[i] = SubExprs[i]; 540 // Null out new args. 541 for (unsigned i = getNumArgs()+ARGS_START; i != NumArgs+ARGS_START; ++i) 542 NewSubExprs[i] = 0; 543 544 if (SubExprs) C.Deallocate(SubExprs); 545 SubExprs = NewSubExprs; 546 this->NumArgs = NumArgs; 547} 548 549/// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If 550/// not, return 0. 551unsigned CallExpr::isBuiltinCall(ASTContext &Context) const { 552 // All simple function calls (e.g. func()) are implicitly cast to pointer to 553 // function. As a result, we try and obtain the DeclRefExpr from the 554 // ImplicitCastExpr. 555 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee()); 556 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()). 557 return 0; 558 559 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()); 560 if (!DRE) 561 return 0; 562 563 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl()); 564 if (!FDecl) 565 return 0; 566 567 if (!FDecl->getIdentifier()) 568 return 0; 569 570 return FDecl->getBuiltinID(); 571} 572 573QualType CallExpr::getCallReturnType() const { 574 QualType CalleeType = getCallee()->getType(); 575 if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>()) 576 CalleeType = FnTypePtr->getPointeeType(); 577 else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>()) 578 CalleeType = BPT->getPointeeType(); 579 580 const FunctionType *FnType = CalleeType->getAs<FunctionType>(); 581 return FnType->getResultType(); 582} 583 584OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type, 585 SourceLocation OperatorLoc, 586 TypeSourceInfo *tsi, 587 OffsetOfNode* compsPtr, unsigned numComps, 588 Expr** exprsPtr, unsigned numExprs, 589 SourceLocation RParenLoc) { 590 void *Mem = C.Allocate(sizeof(OffsetOfExpr) + 591 sizeof(OffsetOfNode) * numComps + 592 sizeof(Expr*) * numExprs); 593 594 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, compsPtr, numComps, 595 exprsPtr, numExprs, RParenLoc); 596} 597 598OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C, 599 unsigned numComps, unsigned numExprs) { 600 void *Mem = C.Allocate(sizeof(OffsetOfExpr) + 601 sizeof(OffsetOfNode) * numComps + 602 sizeof(Expr*) * numExprs); 603 return new (Mem) OffsetOfExpr(numComps, numExprs); 604} 605 606OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type, 607 SourceLocation OperatorLoc, TypeSourceInfo *tsi, 608 OffsetOfNode* compsPtr, unsigned numComps, 609 Expr** exprsPtr, unsigned numExprs, 610 SourceLocation RParenLoc) 611 : Expr(OffsetOfExprClass, type, /*TypeDependent=*/false, 612 /*ValueDependent=*/tsi->getType()->isDependentType() || 613 hasAnyTypeDependentArguments(exprsPtr, numExprs) || 614 hasAnyValueDependentArguments(exprsPtr, numExprs)), 615 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi), 616 NumComps(numComps), NumExprs(numExprs) 617{ 618 for(unsigned i = 0; i < numComps; ++i) { 619 setComponent(i, compsPtr[i]); 620 } 621 622 for(unsigned i = 0; i < numExprs; ++i) { 623 setIndexExpr(i, exprsPtr[i]); 624 } 625} 626 627IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const { 628 assert(getKind() == Field || getKind() == Identifier); 629 if (getKind() == Field) 630 return getField()->getIdentifier(); 631 632 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask); 633} 634 635MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow, 636 NestedNameSpecifier *qual, 637 SourceRange qualrange, 638 ValueDecl *memberdecl, 639 DeclAccessPair founddecl, 640 SourceLocation l, 641 const TemplateArgumentListInfo *targs, 642 QualType ty) { 643 std::size_t Size = sizeof(MemberExpr); 644 645 bool hasQualOrFound = (qual != 0 || 646 founddecl.getDecl() != memberdecl || 647 founddecl.getAccess() != memberdecl->getAccess()); 648 if (hasQualOrFound) 649 Size += sizeof(MemberNameQualifier); 650 651 if (targs) 652 Size += ExplicitTemplateArgumentList::sizeFor(*targs); 653 654 void *Mem = C.Allocate(Size, llvm::alignof<MemberExpr>()); 655 MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, l, ty); 656 657 if (hasQualOrFound) { 658 if (qual && qual->isDependent()) { 659 E->setValueDependent(true); 660 E->setTypeDependent(true); 661 } 662 E->HasQualifierOrFoundDecl = true; 663 664 MemberNameQualifier *NQ = E->getMemberQualifier(); 665 NQ->NNS = qual; 666 NQ->Range = qualrange; 667 NQ->FoundDecl = founddecl; 668 } 669 670 if (targs) { 671 E->HasExplicitTemplateArgumentList = true; 672 E->getExplicitTemplateArgumentList()->initializeFrom(*targs); 673 } 674 675 return E; 676} 677 678const char *CastExpr::getCastKindName() const { 679 switch (getCastKind()) { 680 case CastExpr::CK_Unknown: 681 return "Unknown"; 682 case CastExpr::CK_BitCast: 683 return "BitCast"; 684 case CastExpr::CK_NoOp: 685 return "NoOp"; 686 case CastExpr::CK_BaseToDerived: 687 return "BaseToDerived"; 688 case CastExpr::CK_DerivedToBase: 689 return "DerivedToBase"; 690 case CastExpr::CK_UncheckedDerivedToBase: 691 return "UncheckedDerivedToBase"; 692 case CastExpr::CK_Dynamic: 693 return "Dynamic"; 694 case CastExpr::CK_ToUnion: 695 return "ToUnion"; 696 case CastExpr::CK_ArrayToPointerDecay: 697 return "ArrayToPointerDecay"; 698 case CastExpr::CK_FunctionToPointerDecay: 699 return "FunctionToPointerDecay"; 700 case CastExpr::CK_NullToMemberPointer: 701 return "NullToMemberPointer"; 702 case CastExpr::CK_BaseToDerivedMemberPointer: 703 return "BaseToDerivedMemberPointer"; 704 case CastExpr::CK_DerivedToBaseMemberPointer: 705 return "DerivedToBaseMemberPointer"; 706 case CastExpr::CK_UserDefinedConversion: 707 return "UserDefinedConversion"; 708 case CastExpr::CK_ConstructorConversion: 709 return "ConstructorConversion"; 710 case CastExpr::CK_IntegralToPointer: 711 return "IntegralToPointer"; 712 case CastExpr::CK_PointerToIntegral: 713 return "PointerToIntegral"; 714 case CastExpr::CK_ToVoid: 715 return "ToVoid"; 716 case CastExpr::CK_VectorSplat: 717 return "VectorSplat"; 718 case CastExpr::CK_IntegralCast: 719 return "IntegralCast"; 720 case CastExpr::CK_IntegralToFloating: 721 return "IntegralToFloating"; 722 case CastExpr::CK_FloatingToIntegral: 723 return "FloatingToIntegral"; 724 case CastExpr::CK_FloatingCast: 725 return "FloatingCast"; 726 case CastExpr::CK_MemberPointerToBoolean: 727 return "MemberPointerToBoolean"; 728 case CastExpr::CK_AnyPointerToObjCPointerCast: 729 return "AnyPointerToObjCPointerCast"; 730 case CastExpr::CK_AnyPointerToBlockPointerCast: 731 return "AnyPointerToBlockPointerCast"; 732 } 733 734 assert(0 && "Unhandled cast kind!"); 735 return 0; 736} 737 738void CastExpr::DoDestroy(ASTContext &C) 739{ 740 BasePath.Destroy(); 741 Expr::DoDestroy(C); 742} 743 744Expr *CastExpr::getSubExprAsWritten() { 745 Expr *SubExpr = 0; 746 CastExpr *E = this; 747 do { 748 SubExpr = E->getSubExpr(); 749 750 // Skip any temporary bindings; they're implicit. 751 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) 752 SubExpr = Binder->getSubExpr(); 753 754 // Conversions by constructor and conversion functions have a 755 // subexpression describing the call; strip it off. 756 if (E->getCastKind() == CastExpr::CK_ConstructorConversion) 757 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0); 758 else if (E->getCastKind() == CastExpr::CK_UserDefinedConversion) 759 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument(); 760 761 // If the subexpression we're left with is an implicit cast, look 762 // through that, too. 763 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr))); 764 765 return SubExpr; 766} 767 768/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 769/// corresponds to, e.g. "<<=". 770const char *BinaryOperator::getOpcodeStr(Opcode Op) { 771 switch (Op) { 772 case PtrMemD: return ".*"; 773 case PtrMemI: return "->*"; 774 case Mul: return "*"; 775 case Div: return "/"; 776 case Rem: return "%"; 777 case Add: return "+"; 778 case Sub: return "-"; 779 case Shl: return "<<"; 780 case Shr: return ">>"; 781 case LT: return "<"; 782 case GT: return ">"; 783 case LE: return "<="; 784 case GE: return ">="; 785 case EQ: return "=="; 786 case NE: return "!="; 787 case And: return "&"; 788 case Xor: return "^"; 789 case Or: return "|"; 790 case LAnd: return "&&"; 791 case LOr: return "||"; 792 case Assign: return "="; 793 case MulAssign: return "*="; 794 case DivAssign: return "/="; 795 case RemAssign: return "%="; 796 case AddAssign: return "+="; 797 case SubAssign: return "-="; 798 case ShlAssign: return "<<="; 799 case ShrAssign: return ">>="; 800 case AndAssign: return "&="; 801 case XorAssign: return "^="; 802 case OrAssign: return "|="; 803 case Comma: return ","; 804 } 805 806 return ""; 807} 808 809BinaryOperator::Opcode 810BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) { 811 switch (OO) { 812 default: assert(false && "Not an overloadable binary operator"); 813 case OO_Plus: return Add; 814 case OO_Minus: return Sub; 815 case OO_Star: return Mul; 816 case OO_Slash: return Div; 817 case OO_Percent: return Rem; 818 case OO_Caret: return Xor; 819 case OO_Amp: return And; 820 case OO_Pipe: return Or; 821 case OO_Equal: return Assign; 822 case OO_Less: return LT; 823 case OO_Greater: return GT; 824 case OO_PlusEqual: return AddAssign; 825 case OO_MinusEqual: return SubAssign; 826 case OO_StarEqual: return MulAssign; 827 case OO_SlashEqual: return DivAssign; 828 case OO_PercentEqual: return RemAssign; 829 case OO_CaretEqual: return XorAssign; 830 case OO_AmpEqual: return AndAssign; 831 case OO_PipeEqual: return OrAssign; 832 case OO_LessLess: return Shl; 833 case OO_GreaterGreater: return Shr; 834 case OO_LessLessEqual: return ShlAssign; 835 case OO_GreaterGreaterEqual: return ShrAssign; 836 case OO_EqualEqual: return EQ; 837 case OO_ExclaimEqual: return NE; 838 case OO_LessEqual: return LE; 839 case OO_GreaterEqual: return GE; 840 case OO_AmpAmp: return LAnd; 841 case OO_PipePipe: return LOr; 842 case OO_Comma: return Comma; 843 case OO_ArrowStar: return PtrMemI; 844 } 845} 846 847OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) { 848 static const OverloadedOperatorKind OverOps[] = { 849 /* .* Cannot be overloaded */OO_None, OO_ArrowStar, 850 OO_Star, OO_Slash, OO_Percent, 851 OO_Plus, OO_Minus, 852 OO_LessLess, OO_GreaterGreater, 853 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, 854 OO_EqualEqual, OO_ExclaimEqual, 855 OO_Amp, 856 OO_Caret, 857 OO_Pipe, 858 OO_AmpAmp, 859 OO_PipePipe, 860 OO_Equal, OO_StarEqual, 861 OO_SlashEqual, OO_PercentEqual, 862 OO_PlusEqual, OO_MinusEqual, 863 OO_LessLessEqual, OO_GreaterGreaterEqual, 864 OO_AmpEqual, OO_CaretEqual, 865 OO_PipeEqual, 866 OO_Comma 867 }; 868 return OverOps[Opc]; 869} 870 871InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc, 872 Expr **initExprs, unsigned numInits, 873 SourceLocation rbraceloc) 874 : Expr(InitListExprClass, QualType(), false, false), 875 InitExprs(C, numInits), 876 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0), 877 UnionFieldInit(0), HadArrayRangeDesignator(false) 878{ 879 for (unsigned I = 0; I != numInits; ++I) { 880 if (initExprs[I]->isTypeDependent()) 881 TypeDependent = true; 882 if (initExprs[I]->isValueDependent()) 883 ValueDependent = true; 884 } 885 886 InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits); 887} 888 889void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) { 890 if (NumInits > InitExprs.size()) 891 InitExprs.reserve(C, NumInits); 892} 893 894void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) { 895 for (unsigned Idx = NumInits, LastIdx = InitExprs.size(); 896 Idx < LastIdx; ++Idx) 897 InitExprs[Idx]->Destroy(C); 898 InitExprs.resize(C, NumInits, 0); 899} 900 901Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) { 902 if (Init >= InitExprs.size()) { 903 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0); 904 InitExprs.back() = expr; 905 return 0; 906 } 907 908 Expr *Result = cast_or_null<Expr>(InitExprs[Init]); 909 InitExprs[Init] = expr; 910 return Result; 911} 912 913/// getFunctionType - Return the underlying function type for this block. 914/// 915const FunctionType *BlockExpr::getFunctionType() const { 916 return getType()->getAs<BlockPointerType>()-> 917 getPointeeType()->getAs<FunctionType>(); 918} 919 920SourceLocation BlockExpr::getCaretLocation() const { 921 return TheBlock->getCaretLocation(); 922} 923const Stmt *BlockExpr::getBody() const { 924 return TheBlock->getBody(); 925} 926Stmt *BlockExpr::getBody() { 927 return TheBlock->getBody(); 928} 929 930 931//===----------------------------------------------------------------------===// 932// Generic Expression Routines 933//===----------------------------------------------------------------------===// 934 935/// isUnusedResultAWarning - Return true if this immediate expression should 936/// be warned about if the result is unused. If so, fill in Loc and Ranges 937/// with location to warn on and the source range[s] to report with the 938/// warning. 939bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, 940 SourceRange &R2, ASTContext &Ctx) const { 941 // Don't warn if the expr is type dependent. The type could end up 942 // instantiating to void. 943 if (isTypeDependent()) 944 return false; 945 946 switch (getStmtClass()) { 947 default: 948 if (getType()->isVoidType()) 949 return false; 950 Loc = getExprLoc(); 951 R1 = getSourceRange(); 952 return true; 953 case ParenExprClass: 954 return cast<ParenExpr>(this)->getSubExpr()-> 955 isUnusedResultAWarning(Loc, R1, R2, Ctx); 956 case UnaryOperatorClass: { 957 const UnaryOperator *UO = cast<UnaryOperator>(this); 958 959 switch (UO->getOpcode()) { 960 default: break; 961 case UnaryOperator::PostInc: 962 case UnaryOperator::PostDec: 963 case UnaryOperator::PreInc: 964 case UnaryOperator::PreDec: // ++/-- 965 return false; // Not a warning. 966 case UnaryOperator::Deref: 967 // Dereferencing a volatile pointer is a side-effect. 968 if (Ctx.getCanonicalType(getType()).isVolatileQualified()) 969 return false; 970 break; 971 case UnaryOperator::Real: 972 case UnaryOperator::Imag: 973 // accessing a piece of a volatile complex is a side-effect. 974 if (Ctx.getCanonicalType(UO->getSubExpr()->getType()) 975 .isVolatileQualified()) 976 return false; 977 break; 978 case UnaryOperator::Extension: 979 return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx); 980 } 981 Loc = UO->getOperatorLoc(); 982 R1 = UO->getSubExpr()->getSourceRange(); 983 return true; 984 } 985 case BinaryOperatorClass: { 986 const BinaryOperator *BO = cast<BinaryOperator>(this); 987 switch (BO->getOpcode()) { 988 default: 989 break; 990 // Consider the RHS of comma for side effects. LHS was checked by 991 // Sema::CheckCommaOperands. 992 case BinaryOperator::Comma: 993 // ((foo = <blah>), 0) is an idiom for hiding the result (and 994 // lvalue-ness) of an assignment written in a macro. 995 if (IntegerLiteral *IE = 996 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens())) 997 if (IE->getValue() == 0) 998 return false; 999 return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1000 // Consider '||', '&&' to have side effects if the LHS or RHS does. 1001 case BinaryOperator::LAnd: 1002 case BinaryOperator::LOr: 1003 if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) || 1004 !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx)) 1005 return false; 1006 break; 1007 } 1008 if (BO->isAssignmentOp()) 1009 return false; 1010 Loc = BO->getOperatorLoc(); 1011 R1 = BO->getLHS()->getSourceRange(); 1012 R2 = BO->getRHS()->getSourceRange(); 1013 return true; 1014 } 1015 case CompoundAssignOperatorClass: 1016 case VAArgExprClass: 1017 return false; 1018 1019 case ConditionalOperatorClass: { 1020 // The condition must be evaluated, but if either the LHS or RHS is a 1021 // warning, warn about them. 1022 const ConditionalOperator *Exp = cast<ConditionalOperator>(this); 1023 if (Exp->getLHS() && 1024 Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx)) 1025 return true; 1026 return Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1027 } 1028 1029 case MemberExprClass: 1030 // If the base pointer or element is to a volatile pointer/field, accessing 1031 // it is a side effect. 1032 if (Ctx.getCanonicalType(getType()).isVolatileQualified()) 1033 return false; 1034 Loc = cast<MemberExpr>(this)->getMemberLoc(); 1035 R1 = SourceRange(Loc, Loc); 1036 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange(); 1037 return true; 1038 1039 case ArraySubscriptExprClass: 1040 // If the base pointer or element is to a volatile pointer/field, accessing 1041 // it is a side effect. 1042 if (Ctx.getCanonicalType(getType()).isVolatileQualified()) 1043 return false; 1044 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc(); 1045 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange(); 1046 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange(); 1047 return true; 1048 1049 case CallExprClass: 1050 case CXXOperatorCallExprClass: 1051 case CXXMemberCallExprClass: { 1052 // If this is a direct call, get the callee. 1053 const CallExpr *CE = cast<CallExpr>(this); 1054 if (const Decl *FD = CE->getCalleeDecl()) { 1055 // If the callee has attribute pure, const, or warn_unused_result, warn 1056 // about it. void foo() { strlen("bar"); } should warn. 1057 // 1058 // Note: If new cases are added here, DiagnoseUnusedExprResult should be 1059 // updated to match for QoI. 1060 if (FD->getAttr<WarnUnusedResultAttr>() || 1061 FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) { 1062 Loc = CE->getCallee()->getLocStart(); 1063 R1 = CE->getCallee()->getSourceRange(); 1064 1065 if (unsigned NumArgs = CE->getNumArgs()) 1066 R2 = SourceRange(CE->getArg(0)->getLocStart(), 1067 CE->getArg(NumArgs-1)->getLocEnd()); 1068 return true; 1069 } 1070 } 1071 return false; 1072 } 1073 1074 case CXXTemporaryObjectExprClass: 1075 case CXXConstructExprClass: 1076 return false; 1077 1078 case ObjCMessageExprClass: { 1079 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this); 1080 const ObjCMethodDecl *MD = ME->getMethodDecl(); 1081 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 1082 Loc = getExprLoc(); 1083 return true; 1084 } 1085 return false; 1086 } 1087 1088 case ObjCImplicitSetterGetterRefExprClass: { // Dot syntax for message send. 1089#if 0 1090 const ObjCImplicitSetterGetterRefExpr *Ref = 1091 cast<ObjCImplicitSetterGetterRefExpr>(this); 1092 // FIXME: We really want the location of the '.' here. 1093 Loc = Ref->getLocation(); 1094 R1 = SourceRange(Ref->getLocation(), Ref->getLocation()); 1095 if (Ref->getBase()) 1096 R2 = Ref->getBase()->getSourceRange(); 1097#else 1098 Loc = getExprLoc(); 1099 R1 = getSourceRange(); 1100#endif 1101 return true; 1102 } 1103 case StmtExprClass: { 1104 // Statement exprs don't logically have side effects themselves, but are 1105 // sometimes used in macros in ways that give them a type that is unused. 1106 // For example ({ blah; foo(); }) will end up with a type if foo has a type. 1107 // however, if the result of the stmt expr is dead, we don't want to emit a 1108 // warning. 1109 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt(); 1110 if (!CS->body_empty()) 1111 if (const Expr *E = dyn_cast<Expr>(CS->body_back())) 1112 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1113 1114 if (getType()->isVoidType()) 1115 return false; 1116 Loc = cast<StmtExpr>(this)->getLParenLoc(); 1117 R1 = getSourceRange(); 1118 return true; 1119 } 1120 case CStyleCastExprClass: 1121 // If this is an explicit cast to void, allow it. People do this when they 1122 // think they know what they're doing :). 1123 if (getType()->isVoidType()) 1124 return false; 1125 Loc = cast<CStyleCastExpr>(this)->getLParenLoc(); 1126 R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange(); 1127 return true; 1128 case CXXFunctionalCastExprClass: { 1129 if (getType()->isVoidType()) 1130 return false; 1131 const CastExpr *CE = cast<CastExpr>(this); 1132 1133 // If this is a cast to void or a constructor conversion, check the operand. 1134 // Otherwise, the result of the cast is unused. 1135 if (CE->getCastKind() == CastExpr::CK_ToVoid || 1136 CE->getCastKind() == CastExpr::CK_ConstructorConversion) 1137 return (cast<CastExpr>(this)->getSubExpr() 1138 ->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1139 Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc(); 1140 R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange(); 1141 return true; 1142 } 1143 1144 case ImplicitCastExprClass: 1145 // Check the operand, since implicit casts are inserted by Sema 1146 return (cast<ImplicitCastExpr>(this) 1147 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1148 1149 case CXXDefaultArgExprClass: 1150 return (cast<CXXDefaultArgExpr>(this) 1151 ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1152 1153 case CXXNewExprClass: 1154 // FIXME: In theory, there might be new expressions that don't have side 1155 // effects (e.g. a placement new with an uninitialized POD). 1156 case CXXDeleteExprClass: 1157 return false; 1158 case CXXBindTemporaryExprClass: 1159 return (cast<CXXBindTemporaryExpr>(this) 1160 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1161 case CXXExprWithTemporariesClass: 1162 return (cast<CXXExprWithTemporaries>(this) 1163 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1164 } 1165} 1166 1167/// isOBJCGCCandidate - Check if an expression is objc gc'able. 1168/// returns true, if it is; false otherwise. 1169bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const { 1170 switch (getStmtClass()) { 1171 default: 1172 return false; 1173 case ObjCIvarRefExprClass: 1174 return true; 1175 case Expr::UnaryOperatorClass: 1176 return cast<UnaryOperator>(this)->getSubExpr()->isOBJCGCCandidate(Ctx); 1177 case ParenExprClass: 1178 return cast<ParenExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx); 1179 case ImplicitCastExprClass: 1180 return cast<ImplicitCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx); 1181 case CStyleCastExprClass: 1182 return cast<CStyleCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx); 1183 case DeclRefExprClass: { 1184 const Decl *D = cast<DeclRefExpr>(this)->getDecl(); 1185 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1186 if (VD->hasGlobalStorage()) 1187 return true; 1188 QualType T = VD->getType(); 1189 // dereferencing to a pointer is always a gc'able candidate, 1190 // unless it is __weak. 1191 return T->isPointerType() && 1192 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak); 1193 } 1194 return false; 1195 } 1196 case MemberExprClass: { 1197 const MemberExpr *M = cast<MemberExpr>(this); 1198 return M->getBase()->isOBJCGCCandidate(Ctx); 1199 } 1200 case ArraySubscriptExprClass: 1201 return cast<ArraySubscriptExpr>(this)->getBase()->isOBJCGCCandidate(Ctx); 1202 } 1203} 1204Expr* Expr::IgnoreParens() { 1205 Expr* E = this; 1206 while (ParenExpr* P = dyn_cast<ParenExpr>(E)) 1207 E = P->getSubExpr(); 1208 1209 return E; 1210} 1211 1212/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr 1213/// or CastExprs or ImplicitCastExprs, returning their operand. 1214Expr *Expr::IgnoreParenCasts() { 1215 Expr *E = this; 1216 while (true) { 1217 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) 1218 E = P->getSubExpr(); 1219 else if (CastExpr *P = dyn_cast<CastExpr>(E)) 1220 E = P->getSubExpr(); 1221 else 1222 return E; 1223 } 1224} 1225 1226Expr *Expr::IgnoreParenImpCasts() { 1227 Expr *E = this; 1228 while (true) { 1229 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) 1230 E = P->getSubExpr(); 1231 else if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) 1232 E = P->getSubExpr(); 1233 else 1234 return E; 1235 } 1236} 1237 1238/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the 1239/// value (including ptr->int casts of the same size). Strip off any 1240/// ParenExpr or CastExprs, returning their operand. 1241Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) { 1242 Expr *E = this; 1243 while (true) { 1244 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) { 1245 E = P->getSubExpr(); 1246 continue; 1247 } 1248 1249 if (CastExpr *P = dyn_cast<CastExpr>(E)) { 1250 // We ignore integer <-> casts that are of the same width, ptr<->ptr and 1251 // ptr<->int casts of the same width. We also ignore all identity casts. 1252 Expr *SE = P->getSubExpr(); 1253 1254 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) { 1255 E = SE; 1256 continue; 1257 } 1258 1259 if ((E->getType()->isPointerType() || 1260 E->getType()->isIntegralType(Ctx)) && 1261 (SE->getType()->isPointerType() || 1262 SE->getType()->isIntegralType(Ctx)) && 1263 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) { 1264 E = SE; 1265 continue; 1266 } 1267 } 1268 1269 return E; 1270 } 1271} 1272 1273bool Expr::isDefaultArgument() const { 1274 const Expr *E = this; 1275 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 1276 E = ICE->getSubExprAsWritten(); 1277 1278 return isa<CXXDefaultArgExpr>(E); 1279} 1280 1281/// \brief Skip over any no-op casts and any temporary-binding 1282/// expressions. 1283static const Expr *skipTemporaryBindingsAndNoOpCasts(const Expr *E) { 1284 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 1285 if (ICE->getCastKind() == CastExpr::CK_NoOp) 1286 E = ICE->getSubExpr(); 1287 else 1288 break; 1289 } 1290 1291 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 1292 E = BE->getSubExpr(); 1293 1294 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 1295 if (ICE->getCastKind() == CastExpr::CK_NoOp) 1296 E = ICE->getSubExpr(); 1297 else 1298 break; 1299 } 1300 1301 return E; 1302} 1303 1304const Expr *Expr::getTemporaryObject() const { 1305 const Expr *E = skipTemporaryBindingsAndNoOpCasts(this); 1306 1307 // A cast can produce a temporary object. The object's construction 1308 // is represented as a CXXConstructExpr. 1309 if (const CastExpr *Cast = dyn_cast<CastExpr>(E)) { 1310 // Only user-defined and constructor conversions can produce 1311 // temporary objects. 1312 if (Cast->getCastKind() != CastExpr::CK_ConstructorConversion && 1313 Cast->getCastKind() != CastExpr::CK_UserDefinedConversion) 1314 return 0; 1315 1316 // Strip off temporary bindings and no-op casts. 1317 const Expr *Sub = skipTemporaryBindingsAndNoOpCasts(Cast->getSubExpr()); 1318 1319 // If this is a constructor conversion, see if we have an object 1320 // construction. 1321 if (Cast->getCastKind() == CastExpr::CK_ConstructorConversion) 1322 return dyn_cast<CXXConstructExpr>(Sub); 1323 1324 // If this is a user-defined conversion, see if we have a call to 1325 // a function that itself returns a temporary object. 1326 if (Cast->getCastKind() == CastExpr::CK_UserDefinedConversion) 1327 if (const CallExpr *CE = dyn_cast<CallExpr>(Sub)) 1328 if (CE->getCallReturnType()->isRecordType()) 1329 return CE; 1330 1331 return 0; 1332 } 1333 1334 // A call returning a class type returns a temporary. 1335 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 1336 if (CE->getCallReturnType()->isRecordType()) 1337 return CE; 1338 1339 return 0; 1340 } 1341 1342 // Explicit temporary object constructors create temporaries. 1343 return dyn_cast<CXXTemporaryObjectExpr>(E); 1344} 1345 1346/// hasAnyTypeDependentArguments - Determines if any of the expressions 1347/// in Exprs is type-dependent. 1348bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) { 1349 for (unsigned I = 0; I < NumExprs; ++I) 1350 if (Exprs[I]->isTypeDependent()) 1351 return true; 1352 1353 return false; 1354} 1355 1356/// hasAnyValueDependentArguments - Determines if any of the expressions 1357/// in Exprs is value-dependent. 1358bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) { 1359 for (unsigned I = 0; I < NumExprs; ++I) 1360 if (Exprs[I]->isValueDependent()) 1361 return true; 1362 1363 return false; 1364} 1365 1366bool Expr::isConstantInitializer(ASTContext &Ctx) const { 1367 // This function is attempting whether an expression is an initializer 1368 // which can be evaluated at compile-time. isEvaluatable handles most 1369 // of the cases, but it can't deal with some initializer-specific 1370 // expressions, and it can't deal with aggregates; we deal with those here, 1371 // and fall back to isEvaluatable for the other cases. 1372 1373 // FIXME: This function assumes the variable being assigned to 1374 // isn't a reference type! 1375 1376 switch (getStmtClass()) { 1377 default: break; 1378 case StringLiteralClass: 1379 case ObjCStringLiteralClass: 1380 case ObjCEncodeExprClass: 1381 return true; 1382 case CompoundLiteralExprClass: { 1383 // This handles gcc's extension that allows global initializers like 1384 // "struct x {int x;} x = (struct x) {};". 1385 // FIXME: This accepts other cases it shouldn't! 1386 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer(); 1387 return Exp->isConstantInitializer(Ctx); 1388 } 1389 case InitListExprClass: { 1390 // FIXME: This doesn't deal with fields with reference types correctly. 1391 // FIXME: This incorrectly allows pointers cast to integers to be assigned 1392 // to bitfields. 1393 const InitListExpr *Exp = cast<InitListExpr>(this); 1394 unsigned numInits = Exp->getNumInits(); 1395 for (unsigned i = 0; i < numInits; i++) { 1396 if (!Exp->getInit(i)->isConstantInitializer(Ctx)) 1397 return false; 1398 } 1399 return true; 1400 } 1401 case ImplicitValueInitExprClass: 1402 return true; 1403 case ParenExprClass: 1404 return cast<ParenExpr>(this)->getSubExpr()->isConstantInitializer(Ctx); 1405 case UnaryOperatorClass: { 1406 const UnaryOperator* Exp = cast<UnaryOperator>(this); 1407 if (Exp->getOpcode() == UnaryOperator::Extension) 1408 return Exp->getSubExpr()->isConstantInitializer(Ctx); 1409 break; 1410 } 1411 case BinaryOperatorClass: { 1412 // Special case &&foo - &&bar. It would be nice to generalize this somehow 1413 // but this handles the common case. 1414 const BinaryOperator *Exp = cast<BinaryOperator>(this); 1415 if (Exp->getOpcode() == BinaryOperator::Sub && 1416 isa<AddrLabelExpr>(Exp->getLHS()->IgnoreParenNoopCasts(Ctx)) && 1417 isa<AddrLabelExpr>(Exp->getRHS()->IgnoreParenNoopCasts(Ctx))) 1418 return true; 1419 break; 1420 } 1421 case ImplicitCastExprClass: 1422 case CStyleCastExprClass: 1423 // Handle casts with a destination that's a struct or union; this 1424 // deals with both the gcc no-op struct cast extension and the 1425 // cast-to-union extension. 1426 if (getType()->isRecordType()) 1427 return cast<CastExpr>(this)->getSubExpr()->isConstantInitializer(Ctx); 1428 1429 // Integer->integer casts can be handled here, which is important for 1430 // things like (int)(&&x-&&y). Scary but true. 1431 if (getType()->isIntegerType() && 1432 cast<CastExpr>(this)->getSubExpr()->getType()->isIntegerType()) 1433 return cast<CastExpr>(this)->getSubExpr()->isConstantInitializer(Ctx); 1434 1435 break; 1436 } 1437 return isEvaluatable(Ctx); 1438} 1439 1440/// isNullPointerConstant - C99 6.3.2.3p3 - Return true if this is either an 1441/// integer constant expression with the value zero, or if this is one that is 1442/// cast to void*. 1443bool Expr::isNullPointerConstant(ASTContext &Ctx, 1444 NullPointerConstantValueDependence NPC) const { 1445 if (isValueDependent()) { 1446 switch (NPC) { 1447 case NPC_NeverValueDependent: 1448 assert(false && "Unexpected value dependent expression!"); 1449 // If the unthinkable happens, fall through to the safest alternative. 1450 1451 case NPC_ValueDependentIsNull: 1452 return isTypeDependent() || getType()->isIntegralType(Ctx); 1453 1454 case NPC_ValueDependentIsNotNull: 1455 return false; 1456 } 1457 } 1458 1459 // Strip off a cast to void*, if it exists. Except in C++. 1460 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) { 1461 if (!Ctx.getLangOptions().CPlusPlus) { 1462 // Check that it is a cast to void*. 1463 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) { 1464 QualType Pointee = PT->getPointeeType(); 1465 if (!Pointee.hasQualifiers() && 1466 Pointee->isVoidType() && // to void* 1467 CE->getSubExpr()->getType()->isIntegerType()) // from int. 1468 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 1469 } 1470 } 1471 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) { 1472 // Ignore the ImplicitCastExpr type entirely. 1473 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 1474 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) { 1475 // Accept ((void*)0) as a null pointer constant, as many other 1476 // implementations do. 1477 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 1478 } else if (const CXXDefaultArgExpr *DefaultArg 1479 = dyn_cast<CXXDefaultArgExpr>(this)) { 1480 // See through default argument expressions 1481 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC); 1482 } else if (isa<GNUNullExpr>(this)) { 1483 // The GNU __null extension is always a null pointer constant. 1484 return true; 1485 } 1486 1487 // C++0x nullptr_t is always a null pointer constant. 1488 if (getType()->isNullPtrType()) 1489 return true; 1490 1491 // This expression must be an integer type. 1492 if (!getType()->isIntegerType() || 1493 (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType())) 1494 return false; 1495 1496 // If we have an integer constant expression, we need to *evaluate* it and 1497 // test for the value 0. 1498 llvm::APSInt Result; 1499 return isIntegerConstantExpr(Result, Ctx) && Result == 0; 1500} 1501 1502FieldDecl *Expr::getBitField() { 1503 Expr *E = this->IgnoreParens(); 1504 1505 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 1506 if (ICE->isLvalueCast() && ICE->getCastKind() == CastExpr::CK_NoOp) 1507 E = ICE->getSubExpr()->IgnoreParens(); 1508 else 1509 break; 1510 } 1511 1512 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E)) 1513 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) 1514 if (Field->isBitField()) 1515 return Field; 1516 1517 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) 1518 if (BinOp->isAssignmentOp() && BinOp->getLHS()) 1519 return BinOp->getLHS()->getBitField(); 1520 1521 return 0; 1522} 1523 1524bool Expr::refersToVectorElement() const { 1525 const Expr *E = this->IgnoreParens(); 1526 1527 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 1528 if (ICE->isLvalueCast() && ICE->getCastKind() == CastExpr::CK_NoOp) 1529 E = ICE->getSubExpr()->IgnoreParens(); 1530 else 1531 break; 1532 } 1533 1534 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E)) 1535 return ASE->getBase()->getType()->isVectorType(); 1536 1537 if (isa<ExtVectorElementExpr>(E)) 1538 return true; 1539 1540 return false; 1541} 1542 1543/// isArrow - Return true if the base expression is a pointer to vector, 1544/// return false if the base expression is a vector. 1545bool ExtVectorElementExpr::isArrow() const { 1546 return getBase()->getType()->isPointerType(); 1547} 1548 1549unsigned ExtVectorElementExpr::getNumElements() const { 1550 if (const VectorType *VT = getType()->getAs<VectorType>()) 1551 return VT->getNumElements(); 1552 return 1; 1553} 1554 1555/// containsDuplicateElements - Return true if any element access is repeated. 1556bool ExtVectorElementExpr::containsDuplicateElements() const { 1557 // FIXME: Refactor this code to an accessor on the AST node which returns the 1558 // "type" of component access, and share with code below and in Sema. 1559 llvm::StringRef Comp = Accessor->getName(); 1560 1561 // Halving swizzles do not contain duplicate elements. 1562 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd") 1563 return false; 1564 1565 // Advance past s-char prefix on hex swizzles. 1566 if (Comp[0] == 's' || Comp[0] == 'S') 1567 Comp = Comp.substr(1); 1568 1569 for (unsigned i = 0, e = Comp.size(); i != e; ++i) 1570 if (Comp.substr(i + 1).find(Comp[i]) != llvm::StringRef::npos) 1571 return true; 1572 1573 return false; 1574} 1575 1576/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray. 1577void ExtVectorElementExpr::getEncodedElementAccess( 1578 llvm::SmallVectorImpl<unsigned> &Elts) const { 1579 llvm::StringRef Comp = Accessor->getName(); 1580 if (Comp[0] == 's' || Comp[0] == 'S') 1581 Comp = Comp.substr(1); 1582 1583 bool isHi = Comp == "hi"; 1584 bool isLo = Comp == "lo"; 1585 bool isEven = Comp == "even"; 1586 bool isOdd = Comp == "odd"; 1587 1588 for (unsigned i = 0, e = getNumElements(); i != e; ++i) { 1589 uint64_t Index; 1590 1591 if (isHi) 1592 Index = e + i; 1593 else if (isLo) 1594 Index = i; 1595 else if (isEven) 1596 Index = 2 * i; 1597 else if (isOdd) 1598 Index = 2 * i + 1; 1599 else 1600 Index = ExtVectorType::getAccessorIdx(Comp[i]); 1601 1602 Elts.push_back(Index); 1603 } 1604} 1605 1606ObjCMessageExpr::ObjCMessageExpr(QualType T, 1607 SourceLocation LBracLoc, 1608 SourceLocation SuperLoc, 1609 bool IsInstanceSuper, 1610 QualType SuperType, 1611 Selector Sel, 1612 ObjCMethodDecl *Method, 1613 Expr **Args, unsigned NumArgs, 1614 SourceLocation RBracLoc) 1615 : Expr(ObjCMessageExprClass, T, /*TypeDependent=*/false, 1616 /*ValueDependent=*/false), 1617 NumArgs(NumArgs), Kind(IsInstanceSuper? SuperInstance : SuperClass), 1618 HasMethod(Method != 0), SuperLoc(SuperLoc), 1619 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method 1620 : Sel.getAsOpaquePtr())), 1621 LBracLoc(LBracLoc), RBracLoc(RBracLoc) 1622{ 1623 setReceiverPointer(SuperType.getAsOpaquePtr()); 1624 if (NumArgs) 1625 memcpy(getArgs(), Args, NumArgs * sizeof(Expr *)); 1626} 1627 1628ObjCMessageExpr::ObjCMessageExpr(QualType T, 1629 SourceLocation LBracLoc, 1630 TypeSourceInfo *Receiver, 1631 Selector Sel, 1632 ObjCMethodDecl *Method, 1633 Expr **Args, unsigned NumArgs, 1634 SourceLocation RBracLoc) 1635 : Expr(ObjCMessageExprClass, T, T->isDependentType(), 1636 (T->isDependentType() || 1637 hasAnyValueDependentArguments(Args, NumArgs))), 1638 NumArgs(NumArgs), Kind(Class), HasMethod(Method != 0), 1639 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method 1640 : Sel.getAsOpaquePtr())), 1641 LBracLoc(LBracLoc), RBracLoc(RBracLoc) 1642{ 1643 setReceiverPointer(Receiver); 1644 if (NumArgs) 1645 memcpy(getArgs(), Args, NumArgs * sizeof(Expr *)); 1646} 1647 1648ObjCMessageExpr::ObjCMessageExpr(QualType T, 1649 SourceLocation LBracLoc, 1650 Expr *Receiver, 1651 Selector Sel, 1652 ObjCMethodDecl *Method, 1653 Expr **Args, unsigned NumArgs, 1654 SourceLocation RBracLoc) 1655 : Expr(ObjCMessageExprClass, T, Receiver->isTypeDependent(), 1656 (Receiver->isTypeDependent() || 1657 hasAnyValueDependentArguments(Args, NumArgs))), 1658 NumArgs(NumArgs), Kind(Instance), HasMethod(Method != 0), 1659 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method 1660 : Sel.getAsOpaquePtr())), 1661 LBracLoc(LBracLoc), RBracLoc(RBracLoc) 1662{ 1663 setReceiverPointer(Receiver); 1664 if (NumArgs) 1665 memcpy(getArgs(), Args, NumArgs * sizeof(Expr *)); 1666} 1667 1668ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T, 1669 SourceLocation LBracLoc, 1670 SourceLocation SuperLoc, 1671 bool IsInstanceSuper, 1672 QualType SuperType, 1673 Selector Sel, 1674 ObjCMethodDecl *Method, 1675 Expr **Args, unsigned NumArgs, 1676 SourceLocation RBracLoc) { 1677 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) + 1678 NumArgs * sizeof(Expr *); 1679 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment); 1680 return new (Mem) ObjCMessageExpr(T, LBracLoc, SuperLoc, IsInstanceSuper, 1681 SuperType, Sel, Method, Args, NumArgs, 1682 RBracLoc); 1683} 1684 1685ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T, 1686 SourceLocation LBracLoc, 1687 TypeSourceInfo *Receiver, 1688 Selector Sel, 1689 ObjCMethodDecl *Method, 1690 Expr **Args, unsigned NumArgs, 1691 SourceLocation RBracLoc) { 1692 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) + 1693 NumArgs * sizeof(Expr *); 1694 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment); 1695 return new (Mem) ObjCMessageExpr(T, LBracLoc, Receiver, Sel, Method, Args, 1696 NumArgs, RBracLoc); 1697} 1698 1699ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T, 1700 SourceLocation LBracLoc, 1701 Expr *Receiver, 1702 Selector Sel, 1703 ObjCMethodDecl *Method, 1704 Expr **Args, unsigned NumArgs, 1705 SourceLocation RBracLoc) { 1706 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) + 1707 NumArgs * sizeof(Expr *); 1708 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment); 1709 return new (Mem) ObjCMessageExpr(T, LBracLoc, Receiver, Sel, Method, Args, 1710 NumArgs, RBracLoc); 1711} 1712 1713ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context, 1714 unsigned NumArgs) { 1715 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) + 1716 NumArgs * sizeof(Expr *); 1717 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment); 1718 return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs); 1719} 1720 1721Selector ObjCMessageExpr::getSelector() const { 1722 if (HasMethod) 1723 return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod) 1724 ->getSelector(); 1725 return Selector(SelectorOrMethod); 1726} 1727 1728ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const { 1729 switch (getReceiverKind()) { 1730 case Instance: 1731 if (const ObjCObjectPointerType *Ptr 1732 = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>()) 1733 return Ptr->getInterfaceDecl(); 1734 break; 1735 1736 case Class: 1737 if (const ObjCObjectType *Ty 1738 = getClassReceiver()->getAs<ObjCObjectType>()) 1739 return Ty->getInterface(); 1740 break; 1741 1742 case SuperInstance: 1743 if (const ObjCObjectPointerType *Ptr 1744 = getSuperType()->getAs<ObjCObjectPointerType>()) 1745 return Ptr->getInterfaceDecl(); 1746 break; 1747 1748 case SuperClass: 1749 if (const ObjCObjectPointerType *Iface 1750 = getSuperType()->getAs<ObjCObjectPointerType>()) 1751 return Iface->getInterfaceDecl(); 1752 break; 1753 } 1754 1755 return 0; 1756} 1757 1758bool ChooseExpr::isConditionTrue(ASTContext &C) const { 1759 return getCond()->EvaluateAsInt(C) != 0; 1760} 1761 1762void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs, 1763 unsigned NumExprs) { 1764 if (SubExprs) C.Deallocate(SubExprs); 1765 1766 SubExprs = new (C) Stmt* [NumExprs]; 1767 this->NumExprs = NumExprs; 1768 memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs); 1769} 1770 1771void ShuffleVectorExpr::DoDestroy(ASTContext& C) { 1772 DestroyChildren(C); 1773 if (SubExprs) C.Deallocate(SubExprs); 1774 this->~ShuffleVectorExpr(); 1775 C.Deallocate(this); 1776} 1777 1778void SizeOfAlignOfExpr::DoDestroy(ASTContext& C) { 1779 // Override default behavior of traversing children. If this has a type 1780 // operand and the type is a variable-length array, the child iteration 1781 // will iterate over the size expression. However, this expression belongs 1782 // to the type, not to this, so we don't want to delete it. 1783 // We still want to delete this expression. 1784 if (isArgumentType()) { 1785 this->~SizeOfAlignOfExpr(); 1786 C.Deallocate(this); 1787 } 1788 else 1789 Expr::DoDestroy(C); 1790} 1791 1792//===----------------------------------------------------------------------===// 1793// DesignatedInitExpr 1794//===----------------------------------------------------------------------===// 1795 1796IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() { 1797 assert(Kind == FieldDesignator && "Only valid on a field designator"); 1798 if (Field.NameOrField & 0x01) 1799 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01); 1800 else 1801 return getField()->getIdentifier(); 1802} 1803 1804DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty, 1805 unsigned NumDesignators, 1806 const Designator *Designators, 1807 SourceLocation EqualOrColonLoc, 1808 bool GNUSyntax, 1809 Expr **IndexExprs, 1810 unsigned NumIndexExprs, 1811 Expr *Init) 1812 : Expr(DesignatedInitExprClass, Ty, 1813 Init->isTypeDependent(), Init->isValueDependent()), 1814 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax), 1815 NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) { 1816 this->Designators = new (C) Designator[NumDesignators]; 1817 1818 // Record the initializer itself. 1819 child_iterator Child = child_begin(); 1820 *Child++ = Init; 1821 1822 // Copy the designators and their subexpressions, computing 1823 // value-dependence along the way. 1824 unsigned IndexIdx = 0; 1825 for (unsigned I = 0; I != NumDesignators; ++I) { 1826 this->Designators[I] = Designators[I]; 1827 1828 if (this->Designators[I].isArrayDesignator()) { 1829 // Compute type- and value-dependence. 1830 Expr *Index = IndexExprs[IndexIdx]; 1831 ValueDependent = ValueDependent || 1832 Index->isTypeDependent() || Index->isValueDependent(); 1833 1834 // Copy the index expressions into permanent storage. 1835 *Child++ = IndexExprs[IndexIdx++]; 1836 } else if (this->Designators[I].isArrayRangeDesignator()) { 1837 // Compute type- and value-dependence. 1838 Expr *Start = IndexExprs[IndexIdx]; 1839 Expr *End = IndexExprs[IndexIdx + 1]; 1840 ValueDependent = ValueDependent || 1841 Start->isTypeDependent() || Start->isValueDependent() || 1842 End->isTypeDependent() || End->isValueDependent(); 1843 1844 // Copy the start/end expressions into permanent storage. 1845 *Child++ = IndexExprs[IndexIdx++]; 1846 *Child++ = IndexExprs[IndexIdx++]; 1847 } 1848 } 1849 1850 assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions"); 1851} 1852 1853DesignatedInitExpr * 1854DesignatedInitExpr::Create(ASTContext &C, Designator *Designators, 1855 unsigned NumDesignators, 1856 Expr **IndexExprs, unsigned NumIndexExprs, 1857 SourceLocation ColonOrEqualLoc, 1858 bool UsesColonSyntax, Expr *Init) { 1859 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) + 1860 sizeof(Stmt *) * (NumIndexExprs + 1), 8); 1861 return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators, 1862 ColonOrEqualLoc, UsesColonSyntax, 1863 IndexExprs, NumIndexExprs, Init); 1864} 1865 1866DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C, 1867 unsigned NumIndexExprs) { 1868 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) + 1869 sizeof(Stmt *) * (NumIndexExprs + 1), 8); 1870 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1); 1871} 1872 1873void DesignatedInitExpr::setDesignators(ASTContext &C, 1874 const Designator *Desigs, 1875 unsigned NumDesigs) { 1876 DestroyDesignators(C); 1877 1878 Designators = new (C) Designator[NumDesigs]; 1879 NumDesignators = NumDesigs; 1880 for (unsigned I = 0; I != NumDesigs; ++I) 1881 Designators[I] = Desigs[I]; 1882} 1883 1884SourceRange DesignatedInitExpr::getSourceRange() const { 1885 SourceLocation StartLoc; 1886 Designator &First = 1887 *const_cast<DesignatedInitExpr*>(this)->designators_begin(); 1888 if (First.isFieldDesignator()) { 1889 if (GNUSyntax) 1890 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc); 1891 else 1892 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc); 1893 } else 1894 StartLoc = 1895 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc); 1896 return SourceRange(StartLoc, getInit()->getSourceRange().getEnd()); 1897} 1898 1899Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) { 1900 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator"); 1901 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 1902 Ptr += sizeof(DesignatedInitExpr); 1903 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 1904 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1)); 1905} 1906 1907Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) { 1908 assert(D.Kind == Designator::ArrayRangeDesignator && 1909 "Requires array range designator"); 1910 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 1911 Ptr += sizeof(DesignatedInitExpr); 1912 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 1913 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1)); 1914} 1915 1916Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) { 1917 assert(D.Kind == Designator::ArrayRangeDesignator && 1918 "Requires array range designator"); 1919 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 1920 Ptr += sizeof(DesignatedInitExpr); 1921 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 1922 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2)); 1923} 1924 1925/// \brief Replaces the designator at index @p Idx with the series 1926/// of designators in [First, Last). 1927void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx, 1928 const Designator *First, 1929 const Designator *Last) { 1930 unsigned NumNewDesignators = Last - First; 1931 if (NumNewDesignators == 0) { 1932 std::copy_backward(Designators + Idx + 1, 1933 Designators + NumDesignators, 1934 Designators + Idx); 1935 --NumNewDesignators; 1936 return; 1937 } else if (NumNewDesignators == 1) { 1938 Designators[Idx] = *First; 1939 return; 1940 } 1941 1942 Designator *NewDesignators 1943 = new (C) Designator[NumDesignators - 1 + NumNewDesignators]; 1944 std::copy(Designators, Designators + Idx, NewDesignators); 1945 std::copy(First, Last, NewDesignators + Idx); 1946 std::copy(Designators + Idx + 1, Designators + NumDesignators, 1947 NewDesignators + Idx + NumNewDesignators); 1948 DestroyDesignators(C); 1949 Designators = NewDesignators; 1950 NumDesignators = NumDesignators - 1 + NumNewDesignators; 1951} 1952 1953void DesignatedInitExpr::DoDestroy(ASTContext &C) { 1954 DestroyDesignators(C); 1955 Expr::DoDestroy(C); 1956} 1957 1958void DesignatedInitExpr::DestroyDesignators(ASTContext &C) { 1959 for (unsigned I = 0; I != NumDesignators; ++I) 1960 Designators[I].~Designator(); 1961 C.Deallocate(Designators); 1962 Designators = 0; 1963} 1964 1965ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc, 1966 Expr **exprs, unsigned nexprs, 1967 SourceLocation rparenloc) 1968: Expr(ParenListExprClass, QualType(), 1969 hasAnyTypeDependentArguments(exprs, nexprs), 1970 hasAnyValueDependentArguments(exprs, nexprs)), 1971 NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) { 1972 1973 Exprs = new (C) Stmt*[nexprs]; 1974 for (unsigned i = 0; i != nexprs; ++i) 1975 Exprs[i] = exprs[i]; 1976} 1977 1978void ParenListExpr::DoDestroy(ASTContext& C) { 1979 DestroyChildren(C); 1980 if (Exprs) C.Deallocate(Exprs); 1981 this->~ParenListExpr(); 1982 C.Deallocate(this); 1983} 1984 1985//===----------------------------------------------------------------------===// 1986// ExprIterator. 1987//===----------------------------------------------------------------------===// 1988 1989Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); } 1990Expr* ExprIterator::operator*() const { return cast<Expr>(*I); } 1991Expr* ExprIterator::operator->() const { return cast<Expr>(*I); } 1992const Expr* ConstExprIterator::operator[](size_t idx) const { 1993 return cast<Expr>(I[idx]); 1994} 1995const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); } 1996const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); } 1997 1998//===----------------------------------------------------------------------===// 1999// Child Iterators for iterating over subexpressions/substatements 2000//===----------------------------------------------------------------------===// 2001 2002// DeclRefExpr 2003Stmt::child_iterator DeclRefExpr::child_begin() { return child_iterator(); } 2004Stmt::child_iterator DeclRefExpr::child_end() { return child_iterator(); } 2005 2006// ObjCIvarRefExpr 2007Stmt::child_iterator ObjCIvarRefExpr::child_begin() { return &Base; } 2008Stmt::child_iterator ObjCIvarRefExpr::child_end() { return &Base+1; } 2009 2010// ObjCPropertyRefExpr 2011Stmt::child_iterator ObjCPropertyRefExpr::child_begin() { return &Base; } 2012Stmt::child_iterator ObjCPropertyRefExpr::child_end() { return &Base+1; } 2013 2014// ObjCImplicitSetterGetterRefExpr 2015Stmt::child_iterator ObjCImplicitSetterGetterRefExpr::child_begin() { 2016 // If this is accessing a class member, skip that entry. 2017 if (Base) return &Base; 2018 return &Base+1; 2019} 2020Stmt::child_iterator ObjCImplicitSetterGetterRefExpr::child_end() { 2021 return &Base+1; 2022} 2023 2024// ObjCSuperExpr 2025Stmt::child_iterator ObjCSuperExpr::child_begin() { return child_iterator(); } 2026Stmt::child_iterator ObjCSuperExpr::child_end() { return child_iterator(); } 2027 2028// ObjCIsaExpr 2029Stmt::child_iterator ObjCIsaExpr::child_begin() { return &Base; } 2030Stmt::child_iterator ObjCIsaExpr::child_end() { return &Base+1; } 2031 2032// PredefinedExpr 2033Stmt::child_iterator PredefinedExpr::child_begin() { return child_iterator(); } 2034Stmt::child_iterator PredefinedExpr::child_end() { return child_iterator(); } 2035 2036// IntegerLiteral 2037Stmt::child_iterator IntegerLiteral::child_begin() { return child_iterator(); } 2038Stmt::child_iterator IntegerLiteral::child_end() { return child_iterator(); } 2039 2040// CharacterLiteral 2041Stmt::child_iterator CharacterLiteral::child_begin() { return child_iterator();} 2042Stmt::child_iterator CharacterLiteral::child_end() { return child_iterator(); } 2043 2044// FloatingLiteral 2045Stmt::child_iterator FloatingLiteral::child_begin() { return child_iterator(); } 2046Stmt::child_iterator FloatingLiteral::child_end() { return child_iterator(); } 2047 2048// ImaginaryLiteral 2049Stmt::child_iterator ImaginaryLiteral::child_begin() { return &Val; } 2050Stmt::child_iterator ImaginaryLiteral::child_end() { return &Val+1; } 2051 2052// StringLiteral 2053Stmt::child_iterator StringLiteral::child_begin() { return child_iterator(); } 2054Stmt::child_iterator StringLiteral::child_end() { return child_iterator(); } 2055 2056// ParenExpr 2057Stmt::child_iterator ParenExpr::child_begin() { return &Val; } 2058Stmt::child_iterator ParenExpr::child_end() { return &Val+1; } 2059 2060// UnaryOperator 2061Stmt::child_iterator UnaryOperator::child_begin() { return &Val; } 2062Stmt::child_iterator UnaryOperator::child_end() { return &Val+1; } 2063 2064// OffsetOfExpr 2065Stmt::child_iterator OffsetOfExpr::child_begin() { 2066 return reinterpret_cast<Stmt **> (reinterpret_cast<OffsetOfNode *> (this + 1) 2067 + NumComps); 2068} 2069Stmt::child_iterator OffsetOfExpr::child_end() { 2070 return child_iterator(&*child_begin() + NumExprs); 2071} 2072 2073// SizeOfAlignOfExpr 2074Stmt::child_iterator SizeOfAlignOfExpr::child_begin() { 2075 // If this is of a type and the type is a VLA type (and not a typedef), the 2076 // size expression of the VLA needs to be treated as an executable expression. 2077 // Why isn't this weirdness documented better in StmtIterator? 2078 if (isArgumentType()) { 2079 if (VariableArrayType* T = dyn_cast<VariableArrayType>( 2080 getArgumentType().getTypePtr())) 2081 return child_iterator(T); 2082 return child_iterator(); 2083 } 2084 return child_iterator(&Argument.Ex); 2085} 2086Stmt::child_iterator SizeOfAlignOfExpr::child_end() { 2087 if (isArgumentType()) 2088 return child_iterator(); 2089 return child_iterator(&Argument.Ex + 1); 2090} 2091 2092// ArraySubscriptExpr 2093Stmt::child_iterator ArraySubscriptExpr::child_begin() { 2094 return &SubExprs[0]; 2095} 2096Stmt::child_iterator ArraySubscriptExpr::child_end() { 2097 return &SubExprs[0]+END_EXPR; 2098} 2099 2100// CallExpr 2101Stmt::child_iterator CallExpr::child_begin() { 2102 return &SubExprs[0]; 2103} 2104Stmt::child_iterator CallExpr::child_end() { 2105 return &SubExprs[0]+NumArgs+ARGS_START; 2106} 2107 2108// MemberExpr 2109Stmt::child_iterator MemberExpr::child_begin() { return &Base; } 2110Stmt::child_iterator MemberExpr::child_end() { return &Base+1; } 2111 2112// ExtVectorElementExpr 2113Stmt::child_iterator ExtVectorElementExpr::child_begin() { return &Base; } 2114Stmt::child_iterator ExtVectorElementExpr::child_end() { return &Base+1; } 2115 2116// CompoundLiteralExpr 2117Stmt::child_iterator CompoundLiteralExpr::child_begin() { return &Init; } 2118Stmt::child_iterator CompoundLiteralExpr::child_end() { return &Init+1; } 2119 2120// CastExpr 2121Stmt::child_iterator CastExpr::child_begin() { return &Op; } 2122Stmt::child_iterator CastExpr::child_end() { return &Op+1; } 2123 2124// BinaryOperator 2125Stmt::child_iterator BinaryOperator::child_begin() { 2126 return &SubExprs[0]; 2127} 2128Stmt::child_iterator BinaryOperator::child_end() { 2129 return &SubExprs[0]+END_EXPR; 2130} 2131 2132// ConditionalOperator 2133Stmt::child_iterator ConditionalOperator::child_begin() { 2134 return &SubExprs[0]; 2135} 2136Stmt::child_iterator ConditionalOperator::child_end() { 2137 return &SubExprs[0]+END_EXPR; 2138} 2139 2140// AddrLabelExpr 2141Stmt::child_iterator AddrLabelExpr::child_begin() { return child_iterator(); } 2142Stmt::child_iterator AddrLabelExpr::child_end() { return child_iterator(); } 2143 2144// StmtExpr 2145Stmt::child_iterator StmtExpr::child_begin() { return &SubStmt; } 2146Stmt::child_iterator StmtExpr::child_end() { return &SubStmt+1; } 2147 2148// TypesCompatibleExpr 2149Stmt::child_iterator TypesCompatibleExpr::child_begin() { 2150 return child_iterator(); 2151} 2152 2153Stmt::child_iterator TypesCompatibleExpr::child_end() { 2154 return child_iterator(); 2155} 2156 2157// ChooseExpr 2158Stmt::child_iterator ChooseExpr::child_begin() { return &SubExprs[0]; } 2159Stmt::child_iterator ChooseExpr::child_end() { return &SubExprs[0]+END_EXPR; } 2160 2161// GNUNullExpr 2162Stmt::child_iterator GNUNullExpr::child_begin() { return child_iterator(); } 2163Stmt::child_iterator GNUNullExpr::child_end() { return child_iterator(); } 2164 2165// ShuffleVectorExpr 2166Stmt::child_iterator ShuffleVectorExpr::child_begin() { 2167 return &SubExprs[0]; 2168} 2169Stmt::child_iterator ShuffleVectorExpr::child_end() { 2170 return &SubExprs[0]+NumExprs; 2171} 2172 2173// VAArgExpr 2174Stmt::child_iterator VAArgExpr::child_begin() { return &Val; } 2175Stmt::child_iterator VAArgExpr::child_end() { return &Val+1; } 2176 2177// InitListExpr 2178Stmt::child_iterator InitListExpr::child_begin() { 2179 return InitExprs.size() ? &InitExprs[0] : 0; 2180} 2181Stmt::child_iterator InitListExpr::child_end() { 2182 return InitExprs.size() ? &InitExprs[0] + InitExprs.size() : 0; 2183} 2184 2185// DesignatedInitExpr 2186Stmt::child_iterator DesignatedInitExpr::child_begin() { 2187 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 2188 Ptr += sizeof(DesignatedInitExpr); 2189 return reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 2190} 2191Stmt::child_iterator DesignatedInitExpr::child_end() { 2192 return child_iterator(&*child_begin() + NumSubExprs); 2193} 2194 2195// ImplicitValueInitExpr 2196Stmt::child_iterator ImplicitValueInitExpr::child_begin() { 2197 return child_iterator(); 2198} 2199 2200Stmt::child_iterator ImplicitValueInitExpr::child_end() { 2201 return child_iterator(); 2202} 2203 2204// ParenListExpr 2205Stmt::child_iterator ParenListExpr::child_begin() { 2206 return &Exprs[0]; 2207} 2208Stmt::child_iterator ParenListExpr::child_end() { 2209 return &Exprs[0]+NumExprs; 2210} 2211 2212// ObjCStringLiteral 2213Stmt::child_iterator ObjCStringLiteral::child_begin() { 2214 return &String; 2215} 2216Stmt::child_iterator ObjCStringLiteral::child_end() { 2217 return &String+1; 2218} 2219 2220// ObjCEncodeExpr 2221Stmt::child_iterator ObjCEncodeExpr::child_begin() { return child_iterator(); } 2222Stmt::child_iterator ObjCEncodeExpr::child_end() { return child_iterator(); } 2223 2224// ObjCSelectorExpr 2225Stmt::child_iterator ObjCSelectorExpr::child_begin() { 2226 return child_iterator(); 2227} 2228Stmt::child_iterator ObjCSelectorExpr::child_end() { 2229 return child_iterator(); 2230} 2231 2232// ObjCProtocolExpr 2233Stmt::child_iterator ObjCProtocolExpr::child_begin() { 2234 return child_iterator(); 2235} 2236Stmt::child_iterator ObjCProtocolExpr::child_end() { 2237 return child_iterator(); 2238} 2239 2240// ObjCMessageExpr 2241Stmt::child_iterator ObjCMessageExpr::child_begin() { 2242 if (getReceiverKind() == Instance) 2243 return reinterpret_cast<Stmt **>(this + 1); 2244 return getArgs(); 2245} 2246Stmt::child_iterator ObjCMessageExpr::child_end() { 2247 return getArgs() + getNumArgs(); 2248} 2249 2250// Blocks 2251Stmt::child_iterator BlockExpr::child_begin() { return child_iterator(); } 2252Stmt::child_iterator BlockExpr::child_end() { return child_iterator(); } 2253 2254Stmt::child_iterator BlockDeclRefExpr::child_begin() { return child_iterator();} 2255Stmt::child_iterator BlockDeclRefExpr::child_end() { return child_iterator(); } 2256