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