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> 33 using 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. 39 bool 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(). 96 namespace { 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 116 SourceLocation Expr::getExprLoc() const { 117 switch (getStmtClass()) { 118 case Stmt::NoStmtClass: llvm_unreachable("statement without class"); 119 #define ABSTRACT_STMT(type) 120 #define STMT(type, base) \ 121 case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break; 122 #define EXPR(type, base) \ 123 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc); 124 #include "clang/AST/StmtNodes.inc" 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. 136 static 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 226 void 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 260 DeclRefExpr::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 294 DeclRefExpr *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 308 DeclRefExpr *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 336 DeclRefExpr *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 353 SourceRange 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. 364 std::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 452 void 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 468 IntegerLiteral * 469 IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V, 470 QualType type, SourceLocation l) { 471 return new (C) IntegerLiteral(C, V, type, l); 472 } 473 474 IntegerLiteral * 475 IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) { 476 return new (C) IntegerLiteral(Empty); 477 } 478 479 FloatingLiteral * 480 FloatingLiteral::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 485 FloatingLiteral * 486 FloatingLiteral::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. 493 double 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 501 int 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 524 StringLiteral *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 546 StringLiteral *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 557 void 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 /// 600 SourceLocation StringLiteral:: 601 getLocationOfByte(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]++". 661 const 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 680 UnaryOperatorKind 681 UnaryOperator::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 695 OverloadedOperatorKind 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 714 CallExpr::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 743 CallExpr::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 771 CallExpr::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 778 CallExpr::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 786 Decl *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 810 FunctionDecl *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. 817 void 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. 845 unsigned 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 867 QualType 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 881 SourceRange 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 894 OffsetOfExpr *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 908 OffsetOfExpr *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 916 OffsetOfExpr::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 943 IdentifierInfo *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 951 MemberExpr *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 1015 SourceRange 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 1036 void 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_ReinterpretMemberPointer: 1057 assert(getType()->isMemberPointerType()); 1058 assert(getSubExpr()->getType()->isMemberPointerType()); 1059 goto CheckNoBasePath; 1060 1061 case CK_BitCast: 1062 // Arbitrary casts to C pointer types count as bitcasts. 1063 // Otherwise, we should only have block and ObjC pointer casts 1064 // here if they stay within the type kind. 1065 if (!getType()->isPointerType()) { 1066 assert(getType()->isObjCObjectPointerType() == 1067 getSubExpr()->getType()->isObjCObjectPointerType()); 1068 assert(getType()->isBlockPointerType() == 1069 getSubExpr()->getType()->isBlockPointerType()); 1070 } 1071 goto CheckNoBasePath; 1072 1073 case CK_AnyPointerToBlockPointerCast: 1074 assert(getType()->isBlockPointerType()); 1075 assert(getSubExpr()->getType()->isAnyPointerType() && 1076 !getSubExpr()->getType()->isBlockPointerType()); 1077 goto CheckNoBasePath; 1078 1079 case CK_CopyAndAutoreleaseBlockObject: 1080 assert(getType()->isBlockPointerType()); 1081 assert(getSubExpr()->getType()->isBlockPointerType()); 1082 goto CheckNoBasePath; 1083 1084 // These should not have an inheritance path. 1085 case CK_Dynamic: 1086 case CK_ToUnion: 1087 case CK_ArrayToPointerDecay: 1088 case CK_FunctionToPointerDecay: 1089 case CK_NullToMemberPointer: 1090 case CK_NullToPointer: 1091 case CK_ConstructorConversion: 1092 case CK_IntegralToPointer: 1093 case CK_PointerToIntegral: 1094 case CK_ToVoid: 1095 case CK_VectorSplat: 1096 case CK_IntegralCast: 1097 case CK_IntegralToFloating: 1098 case CK_FloatingToIntegral: 1099 case CK_FloatingCast: 1100 case CK_ObjCObjectLValueCast: 1101 case CK_FloatingRealToComplex: 1102 case CK_FloatingComplexToReal: 1103 case CK_FloatingComplexCast: 1104 case CK_FloatingComplexToIntegralComplex: 1105 case CK_IntegralRealToComplex: 1106 case CK_IntegralComplexToReal: 1107 case CK_IntegralComplexCast: 1108 case CK_IntegralComplexToFloatingComplex: 1109 case CK_ARCProduceObject: 1110 case CK_ARCConsumeObject: 1111 case CK_ARCReclaimReturnedObject: 1112 case CK_ARCExtendBlockObject: 1113 assert(!getType()->isBooleanType() && "unheralded conversion to bool"); 1114 goto CheckNoBasePath; 1115 1116 case CK_Dependent: 1117 case CK_LValueToRValue: 1118 case CK_NoOp: 1119 case CK_AtomicToNonAtomic: 1120 case CK_NonAtomicToAtomic: 1121 case CK_PointerToBoolean: 1122 case CK_IntegralToBoolean: 1123 case CK_FloatingToBoolean: 1124 case CK_MemberPointerToBoolean: 1125 case CK_FloatingComplexToBoolean: 1126 case CK_IntegralComplexToBoolean: 1127 case CK_LValueBitCast: // -> bool& 1128 case CK_UserDefinedConversion: // operator bool() 1129 CheckNoBasePath: 1130 assert(path_empty() && "Cast kind should not have a base path!"); 1131 break; 1132 } 1133 } 1134 1135 const char *CastExpr::getCastKindName() const { 1136 switch (getCastKind()) { 1137 case CK_Dependent: 1138 return "Dependent"; 1139 case CK_BitCast: 1140 return "BitCast"; 1141 case CK_LValueBitCast: 1142 return "LValueBitCast"; 1143 case CK_LValueToRValue: 1144 return "LValueToRValue"; 1145 case CK_NoOp: 1146 return "NoOp"; 1147 case CK_BaseToDerived: 1148 return "BaseToDerived"; 1149 case CK_DerivedToBase: 1150 return "DerivedToBase"; 1151 case CK_UncheckedDerivedToBase: 1152 return "UncheckedDerivedToBase"; 1153 case CK_Dynamic: 1154 return "Dynamic"; 1155 case CK_ToUnion: 1156 return "ToUnion"; 1157 case CK_ArrayToPointerDecay: 1158 return "ArrayToPointerDecay"; 1159 case CK_FunctionToPointerDecay: 1160 return "FunctionToPointerDecay"; 1161 case CK_NullToMemberPointer: 1162 return "NullToMemberPointer"; 1163 case CK_NullToPointer: 1164 return "NullToPointer"; 1165 case CK_BaseToDerivedMemberPointer: 1166 return "BaseToDerivedMemberPointer"; 1167 case CK_DerivedToBaseMemberPointer: 1168 return "DerivedToBaseMemberPointer"; 1169 case CK_ReinterpretMemberPointer: 1170 return "ReinterpretMemberPointer"; 1171 case CK_UserDefinedConversion: 1172 return "UserDefinedConversion"; 1173 case CK_ConstructorConversion: 1174 return "ConstructorConversion"; 1175 case CK_IntegralToPointer: 1176 return "IntegralToPointer"; 1177 case CK_PointerToIntegral: 1178 return "PointerToIntegral"; 1179 case CK_PointerToBoolean: 1180 return "PointerToBoolean"; 1181 case CK_ToVoid: 1182 return "ToVoid"; 1183 case CK_VectorSplat: 1184 return "VectorSplat"; 1185 case CK_IntegralCast: 1186 return "IntegralCast"; 1187 case CK_IntegralToBoolean: 1188 return "IntegralToBoolean"; 1189 case CK_IntegralToFloating: 1190 return "IntegralToFloating"; 1191 case CK_FloatingToIntegral: 1192 return "FloatingToIntegral"; 1193 case CK_FloatingCast: 1194 return "FloatingCast"; 1195 case CK_FloatingToBoolean: 1196 return "FloatingToBoolean"; 1197 case CK_MemberPointerToBoolean: 1198 return "MemberPointerToBoolean"; 1199 case CK_CPointerToObjCPointerCast: 1200 return "CPointerToObjCPointerCast"; 1201 case CK_BlockPointerToObjCPointerCast: 1202 return "BlockPointerToObjCPointerCast"; 1203 case CK_AnyPointerToBlockPointerCast: 1204 return "AnyPointerToBlockPointerCast"; 1205 case CK_ObjCObjectLValueCast: 1206 return "ObjCObjectLValueCast"; 1207 case CK_FloatingRealToComplex: 1208 return "FloatingRealToComplex"; 1209 case CK_FloatingComplexToReal: 1210 return "FloatingComplexToReal"; 1211 case CK_FloatingComplexToBoolean: 1212 return "FloatingComplexToBoolean"; 1213 case CK_FloatingComplexCast: 1214 return "FloatingComplexCast"; 1215 case CK_FloatingComplexToIntegralComplex: 1216 return "FloatingComplexToIntegralComplex"; 1217 case CK_IntegralRealToComplex: 1218 return "IntegralRealToComplex"; 1219 case CK_IntegralComplexToReal: 1220 return "IntegralComplexToReal"; 1221 case CK_IntegralComplexToBoolean: 1222 return "IntegralComplexToBoolean"; 1223 case CK_IntegralComplexCast: 1224 return "IntegralComplexCast"; 1225 case CK_IntegralComplexToFloatingComplex: 1226 return "IntegralComplexToFloatingComplex"; 1227 case CK_ARCConsumeObject: 1228 return "ARCConsumeObject"; 1229 case CK_ARCProduceObject: 1230 return "ARCProduceObject"; 1231 case CK_ARCReclaimReturnedObject: 1232 return "ARCReclaimReturnedObject"; 1233 case CK_ARCExtendBlockObject: 1234 return "ARCCExtendBlockObject"; 1235 case CK_AtomicToNonAtomic: 1236 return "AtomicToNonAtomic"; 1237 case CK_NonAtomicToAtomic: 1238 return "NonAtomicToAtomic"; 1239 case CK_CopyAndAutoreleaseBlockObject: 1240 return "CopyAndAutoreleaseBlockObject"; 1241 } 1242 1243 llvm_unreachable("Unhandled cast kind!"); 1244 } 1245 1246 Expr *CastExpr::getSubExprAsWritten() { 1247 Expr *SubExpr = 0; 1248 CastExpr *E = this; 1249 do { 1250 SubExpr = E->getSubExpr(); 1251 1252 // Skip through reference binding to temporary. 1253 if (MaterializeTemporaryExpr *Materialize 1254 = dyn_cast<MaterializeTemporaryExpr>(SubExpr)) 1255 SubExpr = Materialize->GetTemporaryExpr(); 1256 1257 // Skip any temporary bindings; they're implicit. 1258 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) 1259 SubExpr = Binder->getSubExpr(); 1260 1261 // Conversions by constructor and conversion functions have a 1262 // subexpression describing the call; strip it off. 1263 if (E->getCastKind() == CK_ConstructorConversion) 1264 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0); 1265 else if (E->getCastKind() == CK_UserDefinedConversion) 1266 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument(); 1267 1268 // If the subexpression we're left with is an implicit cast, look 1269 // through that, too. 1270 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr))); 1271 1272 return SubExpr; 1273 } 1274 1275 CXXBaseSpecifier **CastExpr::path_buffer() { 1276 switch (getStmtClass()) { 1277 #define ABSTRACT_STMT(x) 1278 #define CASTEXPR(Type, Base) \ 1279 case Stmt::Type##Class: \ 1280 return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1); 1281 #define STMT(Type, Base) 1282 #include "clang/AST/StmtNodes.inc" 1283 default: 1284 llvm_unreachable("non-cast expressions not possible here"); 1285 } 1286 } 1287 1288 void CastExpr::setCastPath(const CXXCastPath &Path) { 1289 assert(Path.size() == path_size()); 1290 memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*)); 1291 } 1292 1293 ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T, 1294 CastKind Kind, Expr *Operand, 1295 const CXXCastPath *BasePath, 1296 ExprValueKind VK) { 1297 unsigned PathSize = (BasePath ? BasePath->size() : 0); 1298 void *Buffer = 1299 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*)); 1300 ImplicitCastExpr *E = 1301 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK); 1302 if (PathSize) E->setCastPath(*BasePath); 1303 return E; 1304 } 1305 1306 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C, 1307 unsigned PathSize) { 1308 void *Buffer = 1309 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*)); 1310 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize); 1311 } 1312 1313 1314 CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T, 1315 ExprValueKind VK, CastKind K, Expr *Op, 1316 const CXXCastPath *BasePath, 1317 TypeSourceInfo *WrittenTy, 1318 SourceLocation L, SourceLocation R) { 1319 unsigned PathSize = (BasePath ? BasePath->size() : 0); 1320 void *Buffer = 1321 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*)); 1322 CStyleCastExpr *E = 1323 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R); 1324 if (PathSize) E->setCastPath(*BasePath); 1325 return E; 1326 } 1327 1328 CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) { 1329 void *Buffer = 1330 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*)); 1331 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize); 1332 } 1333 1334 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it 1335 /// corresponds to, e.g. "<<=". 1336 const char *BinaryOperator::getOpcodeStr(Opcode Op) { 1337 switch (Op) { 1338 case BO_PtrMemD: return ".*"; 1339 case BO_PtrMemI: return "->*"; 1340 case BO_Mul: return "*"; 1341 case BO_Div: return "/"; 1342 case BO_Rem: return "%"; 1343 case BO_Add: return "+"; 1344 case BO_Sub: return "-"; 1345 case BO_Shl: return "<<"; 1346 case BO_Shr: return ">>"; 1347 case BO_LT: return "<"; 1348 case BO_GT: return ">"; 1349 case BO_LE: return "<="; 1350 case BO_GE: return ">="; 1351 case BO_EQ: return "=="; 1352 case BO_NE: return "!="; 1353 case BO_And: return "&"; 1354 case BO_Xor: return "^"; 1355 case BO_Or: return "|"; 1356 case BO_LAnd: return "&&"; 1357 case BO_LOr: return "||"; 1358 case BO_Assign: return "="; 1359 case BO_MulAssign: return "*="; 1360 case BO_DivAssign: return "/="; 1361 case BO_RemAssign: return "%="; 1362 case BO_AddAssign: return "+="; 1363 case BO_SubAssign: return "-="; 1364 case BO_ShlAssign: return "<<="; 1365 case BO_ShrAssign: return ">>="; 1366 case BO_AndAssign: return "&="; 1367 case BO_XorAssign: return "^="; 1368 case BO_OrAssign: return "|="; 1369 case BO_Comma: return ","; 1370 } 1371 1372 llvm_unreachable("Invalid OpCode!"); 1373 } 1374 1375 BinaryOperatorKind 1376 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) { 1377 switch (OO) { 1378 default: llvm_unreachable("Not an overloadable binary operator"); 1379 case OO_Plus: return BO_Add; 1380 case OO_Minus: return BO_Sub; 1381 case OO_Star: return BO_Mul; 1382 case OO_Slash: return BO_Div; 1383 case OO_Percent: return BO_Rem; 1384 case OO_Caret: return BO_Xor; 1385 case OO_Amp: return BO_And; 1386 case OO_Pipe: return BO_Or; 1387 case OO_Equal: return BO_Assign; 1388 case OO_Less: return BO_LT; 1389 case OO_Greater: return BO_GT; 1390 case OO_PlusEqual: return BO_AddAssign; 1391 case OO_MinusEqual: return BO_SubAssign; 1392 case OO_StarEqual: return BO_MulAssign; 1393 case OO_SlashEqual: return BO_DivAssign; 1394 case OO_PercentEqual: return BO_RemAssign; 1395 case OO_CaretEqual: return BO_XorAssign; 1396 case OO_AmpEqual: return BO_AndAssign; 1397 case OO_PipeEqual: return BO_OrAssign; 1398 case OO_LessLess: return BO_Shl; 1399 case OO_GreaterGreater: return BO_Shr; 1400 case OO_LessLessEqual: return BO_ShlAssign; 1401 case OO_GreaterGreaterEqual: return BO_ShrAssign; 1402 case OO_EqualEqual: return BO_EQ; 1403 case OO_ExclaimEqual: return BO_NE; 1404 case OO_LessEqual: return BO_LE; 1405 case OO_GreaterEqual: return BO_GE; 1406 case OO_AmpAmp: return BO_LAnd; 1407 case OO_PipePipe: return BO_LOr; 1408 case OO_Comma: return BO_Comma; 1409 case OO_ArrowStar: return BO_PtrMemI; 1410 } 1411 } 1412 1413 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) { 1414 static const OverloadedOperatorKind OverOps[] = { 1415 /* .* Cannot be overloaded */OO_None, OO_ArrowStar, 1416 OO_Star, OO_Slash, OO_Percent, 1417 OO_Plus, OO_Minus, 1418 OO_LessLess, OO_GreaterGreater, 1419 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, 1420 OO_EqualEqual, OO_ExclaimEqual, 1421 OO_Amp, 1422 OO_Caret, 1423 OO_Pipe, 1424 OO_AmpAmp, 1425 OO_PipePipe, 1426 OO_Equal, OO_StarEqual, 1427 OO_SlashEqual, OO_PercentEqual, 1428 OO_PlusEqual, OO_MinusEqual, 1429 OO_LessLessEqual, OO_GreaterGreaterEqual, 1430 OO_AmpEqual, OO_CaretEqual, 1431 OO_PipeEqual, 1432 OO_Comma 1433 }; 1434 return OverOps[Opc]; 1435 } 1436 1437 InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc, 1438 Expr **initExprs, unsigned numInits, 1439 SourceLocation rbraceloc) 1440 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false, 1441 false, false), 1442 InitExprs(C, numInits), 1443 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0) 1444 { 1445 sawArrayRangeDesignator(false); 1446 setInitializesStdInitializerList(false); 1447 for (unsigned I = 0; I != numInits; ++I) { 1448 if (initExprs[I]->isTypeDependent()) 1449 ExprBits.TypeDependent = true; 1450 if (initExprs[I]->isValueDependent()) 1451 ExprBits.ValueDependent = true; 1452 if (initExprs[I]->isInstantiationDependent()) 1453 ExprBits.InstantiationDependent = true; 1454 if (initExprs[I]->containsUnexpandedParameterPack()) 1455 ExprBits.ContainsUnexpandedParameterPack = true; 1456 } 1457 1458 InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits); 1459 } 1460 1461 void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) { 1462 if (NumInits > InitExprs.size()) 1463 InitExprs.reserve(C, NumInits); 1464 } 1465 1466 void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) { 1467 InitExprs.resize(C, NumInits, 0); 1468 } 1469 1470 Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) { 1471 if (Init >= InitExprs.size()) { 1472 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0); 1473 InitExprs.back() = expr; 1474 return 0; 1475 } 1476 1477 Expr *Result = cast_or_null<Expr>(InitExprs[Init]); 1478 InitExprs[Init] = expr; 1479 return Result; 1480 } 1481 1482 void InitListExpr::setArrayFiller(Expr *filler) { 1483 assert(!hasArrayFiller() && "Filler already set!"); 1484 ArrayFillerOrUnionFieldInit = filler; 1485 // Fill out any "holes" in the array due to designated initializers. 1486 Expr **inits = getInits(); 1487 for (unsigned i = 0, e = getNumInits(); i != e; ++i) 1488 if (inits[i] == 0) 1489 inits[i] = filler; 1490 } 1491 1492 SourceRange InitListExpr::getSourceRange() const { 1493 if (SyntacticForm) 1494 return SyntacticForm->getSourceRange(); 1495 SourceLocation Beg = LBraceLoc, End = RBraceLoc; 1496 if (Beg.isInvalid()) { 1497 // Find the first non-null initializer. 1498 for (InitExprsTy::const_iterator I = InitExprs.begin(), 1499 E = InitExprs.end(); 1500 I != E; ++I) { 1501 if (Stmt *S = *I) { 1502 Beg = S->getLocStart(); 1503 break; 1504 } 1505 } 1506 } 1507 if (End.isInvalid()) { 1508 // Find the first non-null initializer from the end. 1509 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(), 1510 E = InitExprs.rend(); 1511 I != E; ++I) { 1512 if (Stmt *S = *I) { 1513 End = S->getSourceRange().getEnd(); 1514 break; 1515 } 1516 } 1517 } 1518 return SourceRange(Beg, End); 1519 } 1520 1521 /// getFunctionType - Return the underlying function type for this block. 1522 /// 1523 const FunctionProtoType *BlockExpr::getFunctionType() const { 1524 // The block pointer is never sugared, but the function type might be. 1525 return cast<BlockPointerType>(getType()) 1526 ->getPointeeType()->castAs<FunctionProtoType>(); 1527 } 1528 1529 SourceLocation BlockExpr::getCaretLocation() const { 1530 return TheBlock->getCaretLocation(); 1531 } 1532 const Stmt *BlockExpr::getBody() const { 1533 return TheBlock->getBody(); 1534 } 1535 Stmt *BlockExpr::getBody() { 1536 return TheBlock->getBody(); 1537 } 1538 1539 1540 //===----------------------------------------------------------------------===// 1541 // Generic Expression Routines 1542 //===----------------------------------------------------------------------===// 1543 1544 /// isUnusedResultAWarning - Return true if this immediate expression should 1545 /// be warned about if the result is unused. If so, fill in Loc and Ranges 1546 /// with location to warn on and the source range[s] to report with the 1547 /// warning. 1548 bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1, 1549 SourceRange &R2, ASTContext &Ctx) const { 1550 // Don't warn if the expr is type dependent. The type could end up 1551 // instantiating to void. 1552 if (isTypeDependent()) 1553 return false; 1554 1555 switch (getStmtClass()) { 1556 default: 1557 if (getType()->isVoidType()) 1558 return false; 1559 Loc = getExprLoc(); 1560 R1 = getSourceRange(); 1561 return true; 1562 case ParenExprClass: 1563 return cast<ParenExpr>(this)->getSubExpr()-> 1564 isUnusedResultAWarning(Loc, R1, R2, Ctx); 1565 case GenericSelectionExprClass: 1566 return cast<GenericSelectionExpr>(this)->getResultExpr()-> 1567 isUnusedResultAWarning(Loc, R1, R2, Ctx); 1568 case UnaryOperatorClass: { 1569 const UnaryOperator *UO = cast<UnaryOperator>(this); 1570 1571 switch (UO->getOpcode()) { 1572 default: break; 1573 case UO_PostInc: 1574 case UO_PostDec: 1575 case UO_PreInc: 1576 case UO_PreDec: // ++/-- 1577 return false; // Not a warning. 1578 case UO_Deref: 1579 // Dereferencing a volatile pointer is a side-effect. 1580 if (Ctx.getCanonicalType(getType()).isVolatileQualified()) 1581 return false; 1582 break; 1583 case UO_Real: 1584 case UO_Imag: 1585 // accessing a piece of a volatile complex is a side-effect. 1586 if (Ctx.getCanonicalType(UO->getSubExpr()->getType()) 1587 .isVolatileQualified()) 1588 return false; 1589 break; 1590 case UO_Extension: 1591 return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1592 } 1593 Loc = UO->getOperatorLoc(); 1594 R1 = UO->getSubExpr()->getSourceRange(); 1595 return true; 1596 } 1597 case BinaryOperatorClass: { 1598 const BinaryOperator *BO = cast<BinaryOperator>(this); 1599 switch (BO->getOpcode()) { 1600 default: 1601 break; 1602 // Consider the RHS of comma for side effects. LHS was checked by 1603 // Sema::CheckCommaOperands. 1604 case BO_Comma: 1605 // ((foo = <blah>), 0) is an idiom for hiding the result (and 1606 // lvalue-ness) of an assignment written in a macro. 1607 if (IntegerLiteral *IE = 1608 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens())) 1609 if (IE->getValue() == 0) 1610 return false; 1611 return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1612 // Consider '||', '&&' to have side effects if the LHS or RHS does. 1613 case BO_LAnd: 1614 case BO_LOr: 1615 if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) || 1616 !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx)) 1617 return false; 1618 break; 1619 } 1620 if (BO->isAssignmentOp()) 1621 return false; 1622 Loc = BO->getOperatorLoc(); 1623 R1 = BO->getLHS()->getSourceRange(); 1624 R2 = BO->getRHS()->getSourceRange(); 1625 return true; 1626 } 1627 case CompoundAssignOperatorClass: 1628 case VAArgExprClass: 1629 case AtomicExprClass: 1630 return false; 1631 1632 case ConditionalOperatorClass: { 1633 // If only one of the LHS or RHS is a warning, the operator might 1634 // be being used for control flow. Only warn if both the LHS and 1635 // RHS are warnings. 1636 const ConditionalOperator *Exp = cast<ConditionalOperator>(this); 1637 if (!Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx)) 1638 return false; 1639 if (!Exp->getLHS()) 1640 return true; 1641 return Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1642 } 1643 1644 case MemberExprClass: 1645 // If the base pointer or element is to a volatile pointer/field, accessing 1646 // it is a side effect. 1647 if (Ctx.getCanonicalType(getType()).isVolatileQualified()) 1648 return false; 1649 Loc = cast<MemberExpr>(this)->getMemberLoc(); 1650 R1 = SourceRange(Loc, Loc); 1651 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange(); 1652 return true; 1653 1654 case ArraySubscriptExprClass: 1655 // If the base pointer or element is to a volatile pointer/field, accessing 1656 // it is a side effect. 1657 if (Ctx.getCanonicalType(getType()).isVolatileQualified()) 1658 return false; 1659 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc(); 1660 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange(); 1661 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange(); 1662 return true; 1663 1664 case CXXOperatorCallExprClass: { 1665 // We warn about operator== and operator!= even when user-defined operator 1666 // overloads as there is no reasonable way to define these such that they 1667 // have non-trivial, desirable side-effects. See the -Wunused-comparison 1668 // warning: these operators are commonly typo'ed, and so warning on them 1669 // provides additional value as well. If this list is updated, 1670 // DiagnoseUnusedComparison should be as well. 1671 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this); 1672 if (Op->getOperator() == OO_EqualEqual || 1673 Op->getOperator() == OO_ExclaimEqual) { 1674 Loc = Op->getOperatorLoc(); 1675 R1 = Op->getSourceRange(); 1676 return true; 1677 } 1678 1679 // Fallthrough for generic call handling. 1680 } 1681 case CallExprClass: 1682 case CXXMemberCallExprClass: { 1683 // If this is a direct call, get the callee. 1684 const CallExpr *CE = cast<CallExpr>(this); 1685 if (const Decl *FD = CE->getCalleeDecl()) { 1686 // If the callee has attribute pure, const, or warn_unused_result, warn 1687 // about it. void foo() { strlen("bar"); } should warn. 1688 // 1689 // Note: If new cases are added here, DiagnoseUnusedExprResult should be 1690 // updated to match for QoI. 1691 if (FD->getAttr<WarnUnusedResultAttr>() || 1692 FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) { 1693 Loc = CE->getCallee()->getLocStart(); 1694 R1 = CE->getCallee()->getSourceRange(); 1695 1696 if (unsigned NumArgs = CE->getNumArgs()) 1697 R2 = SourceRange(CE->getArg(0)->getLocStart(), 1698 CE->getArg(NumArgs-1)->getLocEnd()); 1699 return true; 1700 } 1701 } 1702 return false; 1703 } 1704 1705 case CXXTemporaryObjectExprClass: 1706 case CXXConstructExprClass: 1707 return false; 1708 1709 case ObjCMessageExprClass: { 1710 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this); 1711 if (Ctx.getLangOptions().ObjCAutoRefCount && 1712 ME->isInstanceMessage() && 1713 !ME->getType()->isVoidType() && 1714 ME->getSelector().getIdentifierInfoForSlot(0) && 1715 ME->getSelector().getIdentifierInfoForSlot(0) 1716 ->getName().startswith("init")) { 1717 Loc = getExprLoc(); 1718 R1 = ME->getSourceRange(); 1719 return true; 1720 } 1721 1722 const ObjCMethodDecl *MD = ME->getMethodDecl(); 1723 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 1724 Loc = getExprLoc(); 1725 return true; 1726 } 1727 return false; 1728 } 1729 1730 case ObjCPropertyRefExprClass: 1731 Loc = getExprLoc(); 1732 R1 = getSourceRange(); 1733 return true; 1734 1735 case PseudoObjectExprClass: { 1736 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this); 1737 1738 // Only complain about things that have the form of a getter. 1739 if (isa<UnaryOperator>(PO->getSyntacticForm()) || 1740 isa<BinaryOperator>(PO->getSyntacticForm())) 1741 return false; 1742 1743 Loc = getExprLoc(); 1744 R1 = getSourceRange(); 1745 return true; 1746 } 1747 1748 case StmtExprClass: { 1749 // Statement exprs don't logically have side effects themselves, but are 1750 // sometimes used in macros in ways that give them a type that is unused. 1751 // For example ({ blah; foo(); }) will end up with a type if foo has a type. 1752 // however, if the result of the stmt expr is dead, we don't want to emit a 1753 // warning. 1754 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt(); 1755 if (!CS->body_empty()) { 1756 if (const Expr *E = dyn_cast<Expr>(CS->body_back())) 1757 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1758 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back())) 1759 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt())) 1760 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx); 1761 } 1762 1763 if (getType()->isVoidType()) 1764 return false; 1765 Loc = cast<StmtExpr>(this)->getLParenLoc(); 1766 R1 = getSourceRange(); 1767 return true; 1768 } 1769 case CStyleCastExprClass: 1770 // If this is an explicit cast to void, allow it. People do this when they 1771 // think they know what they're doing :). 1772 if (getType()->isVoidType()) 1773 return false; 1774 Loc = cast<CStyleCastExpr>(this)->getLParenLoc(); 1775 R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange(); 1776 return true; 1777 case CXXFunctionalCastExprClass: { 1778 if (getType()->isVoidType()) 1779 return false; 1780 const CastExpr *CE = cast<CastExpr>(this); 1781 1782 // If this is a cast to void or a constructor conversion, check the operand. 1783 // Otherwise, the result of the cast is unused. 1784 if (CE->getCastKind() == CK_ToVoid || 1785 CE->getCastKind() == CK_ConstructorConversion) 1786 return (cast<CastExpr>(this)->getSubExpr() 1787 ->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1788 Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc(); 1789 R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange(); 1790 return true; 1791 } 1792 1793 case ImplicitCastExprClass: 1794 // Check the operand, since implicit casts are inserted by Sema 1795 return (cast<ImplicitCastExpr>(this) 1796 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1797 1798 case CXXDefaultArgExprClass: 1799 return (cast<CXXDefaultArgExpr>(this) 1800 ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1801 1802 case CXXNewExprClass: 1803 // FIXME: In theory, there might be new expressions that don't have side 1804 // effects (e.g. a placement new with an uninitialized POD). 1805 case CXXDeleteExprClass: 1806 return false; 1807 case CXXBindTemporaryExprClass: 1808 return (cast<CXXBindTemporaryExpr>(this) 1809 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1810 case ExprWithCleanupsClass: 1811 return (cast<ExprWithCleanups>(this) 1812 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx)); 1813 } 1814 } 1815 1816 /// isOBJCGCCandidate - Check if an expression is objc gc'able. 1817 /// returns true, if it is; false otherwise. 1818 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const { 1819 const Expr *E = IgnoreParens(); 1820 switch (E->getStmtClass()) { 1821 default: 1822 return false; 1823 case ObjCIvarRefExprClass: 1824 return true; 1825 case Expr::UnaryOperatorClass: 1826 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); 1827 case ImplicitCastExprClass: 1828 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); 1829 case MaterializeTemporaryExprClass: 1830 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr() 1831 ->isOBJCGCCandidate(Ctx); 1832 case CStyleCastExprClass: 1833 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); 1834 case BlockDeclRefExprClass: 1835 case DeclRefExprClass: { 1836 1837 const Decl *D; 1838 if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) 1839 D = BDRE->getDecl(); 1840 else 1841 D = cast<DeclRefExpr>(E)->getDecl(); 1842 1843 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1844 if (VD->hasGlobalStorage()) 1845 return true; 1846 QualType T = VD->getType(); 1847 // dereferencing to a pointer is always a gc'able candidate, 1848 // unless it is __weak. 1849 return T->isPointerType() && 1850 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak); 1851 } 1852 return false; 1853 } 1854 case MemberExprClass: { 1855 const MemberExpr *M = cast<MemberExpr>(E); 1856 return M->getBase()->isOBJCGCCandidate(Ctx); 1857 } 1858 case ArraySubscriptExprClass: 1859 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx); 1860 } 1861 } 1862 1863 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const { 1864 if (isTypeDependent()) 1865 return false; 1866 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction; 1867 } 1868 1869 QualType Expr::findBoundMemberType(const Expr *expr) { 1870 assert(expr->hasPlaceholderType(BuiltinType::BoundMember)); 1871 1872 // Bound member expressions are always one of these possibilities: 1873 // x->m x.m x->*y x.*y 1874 // (possibly parenthesized) 1875 1876 expr = expr->IgnoreParens(); 1877 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) { 1878 assert(isa<CXXMethodDecl>(mem->getMemberDecl())); 1879 return mem->getMemberDecl()->getType(); 1880 } 1881 1882 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) { 1883 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>() 1884 ->getPointeeType(); 1885 assert(type->isFunctionType()); 1886 return type; 1887 } 1888 1889 assert(isa<UnresolvedMemberExpr>(expr)); 1890 return QualType(); 1891 } 1892 1893 static Expr::CanThrowResult MergeCanThrow(Expr::CanThrowResult CT1, 1894 Expr::CanThrowResult CT2) { 1895 // CanThrowResult constants are ordered so that the maximum is the correct 1896 // merge result. 1897 return CT1 > CT2 ? CT1 : CT2; 1898 } 1899 1900 static Expr::CanThrowResult CanSubExprsThrow(ASTContext &C, const Expr *CE) { 1901 Expr *E = const_cast<Expr*>(CE); 1902 Expr::CanThrowResult R = Expr::CT_Cannot; 1903 for (Expr::child_range I = E->children(); I && R != Expr::CT_Can; ++I) { 1904 R = MergeCanThrow(R, cast<Expr>(*I)->CanThrow(C)); 1905 } 1906 return R; 1907 } 1908 1909 static Expr::CanThrowResult CanCalleeThrow(ASTContext &Ctx, const Expr *E, 1910 const Decl *D, 1911 bool NullThrows = true) { 1912 if (!D) 1913 return NullThrows ? Expr::CT_Can : Expr::CT_Cannot; 1914 1915 // See if we can get a function type from the decl somehow. 1916 const ValueDecl *VD = dyn_cast<ValueDecl>(D); 1917 if (!VD) // If we have no clue what we're calling, assume the worst. 1918 return Expr::CT_Can; 1919 1920 // As an extension, we assume that __attribute__((nothrow)) functions don't 1921 // throw. 1922 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>()) 1923 return Expr::CT_Cannot; 1924 1925 QualType T = VD->getType(); 1926 const FunctionProtoType *FT; 1927 if ((FT = T->getAs<FunctionProtoType>())) { 1928 } else if (const PointerType *PT = T->getAs<PointerType>()) 1929 FT = PT->getPointeeType()->getAs<FunctionProtoType>(); 1930 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 1931 FT = RT->getPointeeType()->getAs<FunctionProtoType>(); 1932 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>()) 1933 FT = MT->getPointeeType()->getAs<FunctionProtoType>(); 1934 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) 1935 FT = BT->getPointeeType()->getAs<FunctionProtoType>(); 1936 1937 if (!FT) 1938 return Expr::CT_Can; 1939 1940 if (FT->getExceptionSpecType() == EST_Delayed) { 1941 assert(isa<CXXConstructorDecl>(D) && 1942 "only constructor exception specs can be unknown"); 1943 Ctx.getDiagnostics().Report(E->getLocStart(), 1944 diag::err_exception_spec_unknown) 1945 << E->getSourceRange(); 1946 return Expr::CT_Can; 1947 } 1948 1949 return FT->isNothrow(Ctx) ? Expr::CT_Cannot : Expr::CT_Can; 1950 } 1951 1952 static Expr::CanThrowResult CanDynamicCastThrow(const CXXDynamicCastExpr *DC) { 1953 if (DC->isTypeDependent()) 1954 return Expr::CT_Dependent; 1955 1956 if (!DC->getTypeAsWritten()->isReferenceType()) 1957 return Expr::CT_Cannot; 1958 1959 if (DC->getSubExpr()->isTypeDependent()) 1960 return Expr::CT_Dependent; 1961 1962 return DC->getCastKind() == clang::CK_Dynamic? Expr::CT_Can : Expr::CT_Cannot; 1963 } 1964 1965 static Expr::CanThrowResult CanTypeidThrow(ASTContext &C, 1966 const CXXTypeidExpr *DC) { 1967 if (DC->isTypeOperand()) 1968 return Expr::CT_Cannot; 1969 1970 Expr *Op = DC->getExprOperand(); 1971 if (Op->isTypeDependent()) 1972 return Expr::CT_Dependent; 1973 1974 const RecordType *RT = Op->getType()->getAs<RecordType>(); 1975 if (!RT) 1976 return Expr::CT_Cannot; 1977 1978 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic()) 1979 return Expr::CT_Cannot; 1980 1981 if (Op->Classify(C).isPRValue()) 1982 return Expr::CT_Cannot; 1983 1984 return Expr::CT_Can; 1985 } 1986 1987 Expr::CanThrowResult Expr::CanThrow(ASTContext &C) const { 1988 // C++ [expr.unary.noexcept]p3: 1989 // [Can throw] if in a potentially-evaluated context the expression would 1990 // contain: 1991 switch (getStmtClass()) { 1992 case CXXThrowExprClass: 1993 // - a potentially evaluated throw-expression 1994 return CT_Can; 1995 1996 case CXXDynamicCastExprClass: { 1997 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v), 1998 // where T is a reference type, that requires a run-time check 1999 CanThrowResult CT = CanDynamicCastThrow(cast<CXXDynamicCastExpr>(this)); 2000 if (CT == CT_Can) 2001 return CT; 2002 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 2003 } 2004 2005 case CXXTypeidExprClass: 2006 // - a potentially evaluated typeid expression applied to a glvalue 2007 // expression whose type is a polymorphic class type 2008 return CanTypeidThrow(C, cast<CXXTypeidExpr>(this)); 2009 2010 // - a potentially evaluated call to a function, member function, function 2011 // pointer, or member function pointer that does not have a non-throwing 2012 // exception-specification 2013 case CallExprClass: 2014 case CXXMemberCallExprClass: 2015 case CXXOperatorCallExprClass: { 2016 const CallExpr *CE = cast<CallExpr>(this); 2017 CanThrowResult CT; 2018 if (isTypeDependent()) 2019 CT = CT_Dependent; 2020 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) 2021 CT = CT_Cannot; 2022 else 2023 CT = CanCalleeThrow(C, this, CE->getCalleeDecl()); 2024 if (CT == CT_Can) 2025 return CT; 2026 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 2027 } 2028 2029 case CXXConstructExprClass: 2030 case CXXTemporaryObjectExprClass: { 2031 CanThrowResult CT = CanCalleeThrow(C, this, 2032 cast<CXXConstructExpr>(this)->getConstructor()); 2033 if (CT == CT_Can) 2034 return CT; 2035 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 2036 } 2037 2038 case LambdaExprClass: { 2039 const LambdaExpr *Lambda = cast<LambdaExpr>(this); 2040 CanThrowResult CT = Expr::CT_Cannot; 2041 for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(), 2042 CapEnd = Lambda->capture_init_end(); 2043 Cap != CapEnd; ++Cap) 2044 CT = MergeCanThrow(CT, (*Cap)->CanThrow(C)); 2045 return CT; 2046 } 2047 2048 case CXXNewExprClass: { 2049 CanThrowResult CT; 2050 if (isTypeDependent()) 2051 CT = CT_Dependent; 2052 else 2053 CT = CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getOperatorNew()); 2054 if (CT == CT_Can) 2055 return CT; 2056 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 2057 } 2058 2059 case CXXDeleteExprClass: { 2060 CanThrowResult CT; 2061 QualType DTy = cast<CXXDeleteExpr>(this)->getDestroyedType(); 2062 if (DTy.isNull() || DTy->isDependentType()) { 2063 CT = CT_Dependent; 2064 } else { 2065 CT = CanCalleeThrow(C, this, 2066 cast<CXXDeleteExpr>(this)->getOperatorDelete()); 2067 if (const RecordType *RT = DTy->getAs<RecordType>()) { 2068 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2069 CT = MergeCanThrow(CT, CanCalleeThrow(C, this, RD->getDestructor())); 2070 } 2071 if (CT == CT_Can) 2072 return CT; 2073 } 2074 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 2075 } 2076 2077 case CXXBindTemporaryExprClass: { 2078 // The bound temporary has to be destroyed again, which might throw. 2079 CanThrowResult CT = CanCalleeThrow(C, this, 2080 cast<CXXBindTemporaryExpr>(this)->getTemporary()->getDestructor()); 2081 if (CT == CT_Can) 2082 return CT; 2083 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 2084 } 2085 2086 // ObjC message sends are like function calls, but never have exception 2087 // specs. 2088 case ObjCMessageExprClass: 2089 case ObjCPropertyRefExprClass: 2090 return CT_Can; 2091 2092 // Many other things have subexpressions, so we have to test those. 2093 // Some are simple: 2094 case ConditionalOperatorClass: 2095 case CompoundLiteralExprClass: 2096 case CXXConstCastExprClass: 2097 case CXXDefaultArgExprClass: 2098 case CXXReinterpretCastExprClass: 2099 case DesignatedInitExprClass: 2100 case ExprWithCleanupsClass: 2101 case ExtVectorElementExprClass: 2102 case InitListExprClass: 2103 case MemberExprClass: 2104 case ObjCIsaExprClass: 2105 case ObjCIvarRefExprClass: 2106 case ParenExprClass: 2107 case ParenListExprClass: 2108 case ShuffleVectorExprClass: 2109 case VAArgExprClass: 2110 return CanSubExprsThrow(C, this); 2111 2112 // Some might be dependent for other reasons. 2113 case ArraySubscriptExprClass: 2114 case BinaryOperatorClass: 2115 case CompoundAssignOperatorClass: 2116 case CStyleCastExprClass: 2117 case CXXStaticCastExprClass: 2118 case CXXFunctionalCastExprClass: 2119 case ImplicitCastExprClass: 2120 case MaterializeTemporaryExprClass: 2121 case UnaryOperatorClass: { 2122 CanThrowResult CT = isTypeDependent() ? CT_Dependent : CT_Cannot; 2123 return MergeCanThrow(CT, CanSubExprsThrow(C, this)); 2124 } 2125 2126 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms. 2127 case StmtExprClass: 2128 return CT_Can; 2129 2130 case ChooseExprClass: 2131 if (isTypeDependent() || isValueDependent()) 2132 return CT_Dependent; 2133 return cast<ChooseExpr>(this)->getChosenSubExpr(C)->CanThrow(C); 2134 2135 case GenericSelectionExprClass: 2136 if (cast<GenericSelectionExpr>(this)->isResultDependent()) 2137 return CT_Dependent; 2138 return cast<GenericSelectionExpr>(this)->getResultExpr()->CanThrow(C); 2139 2140 // Some expressions are always dependent. 2141 case CXXDependentScopeMemberExprClass: 2142 case CXXUnresolvedConstructExprClass: 2143 case DependentScopeDeclRefExprClass: 2144 return CT_Dependent; 2145 2146 case AtomicExprClass: 2147 case AsTypeExprClass: 2148 case BinaryConditionalOperatorClass: 2149 case BlockExprClass: 2150 case BlockDeclRefExprClass: 2151 case CUDAKernelCallExprClass: 2152 case DeclRefExprClass: 2153 case ObjCBridgedCastExprClass: 2154 case ObjCIndirectCopyRestoreExprClass: 2155 case ObjCProtocolExprClass: 2156 case ObjCSelectorExprClass: 2157 case OffsetOfExprClass: 2158 case PackExpansionExprClass: 2159 case PseudoObjectExprClass: 2160 case SubstNonTypeTemplateParmExprClass: 2161 case SubstNonTypeTemplateParmPackExprClass: 2162 case UnaryExprOrTypeTraitExprClass: 2163 case UnresolvedLookupExprClass: 2164 case UnresolvedMemberExprClass: 2165 // FIXME: Can any of the above throw? If so, when? 2166 return CT_Cannot; 2167 2168 case AddrLabelExprClass: 2169 case ArrayTypeTraitExprClass: 2170 case BinaryTypeTraitExprClass: 2171 case CXXBoolLiteralExprClass: 2172 case CXXNoexceptExprClass: 2173 case CXXNullPtrLiteralExprClass: 2174 case CXXPseudoDestructorExprClass: 2175 case CXXScalarValueInitExprClass: 2176 case CXXThisExprClass: 2177 case CXXUuidofExprClass: 2178 case CharacterLiteralClass: 2179 case ExpressionTraitExprClass: 2180 case FloatingLiteralClass: 2181 case GNUNullExprClass: 2182 case ImaginaryLiteralClass: 2183 case ImplicitValueInitExprClass: 2184 case IntegerLiteralClass: 2185 case ObjCEncodeExprClass: 2186 case ObjCStringLiteralClass: 2187 case OpaqueValueExprClass: 2188 case PredefinedExprClass: 2189 case SizeOfPackExprClass: 2190 case StringLiteralClass: 2191 case UnaryTypeTraitExprClass: 2192 // These expressions can never throw. 2193 return CT_Cannot; 2194 2195 #define STMT(CLASS, PARENT) case CLASS##Class: 2196 #define STMT_RANGE(Base, First, Last) 2197 #define LAST_STMT_RANGE(BASE, FIRST, LAST) 2198 #define EXPR(CLASS, PARENT) 2199 #define ABSTRACT_STMT(STMT) 2200 #include "clang/AST/StmtNodes.inc" 2201 case NoStmtClass: 2202 llvm_unreachable("Invalid class for expression"); 2203 } 2204 llvm_unreachable("Bogus StmtClass"); 2205 } 2206 2207 Expr* Expr::IgnoreParens() { 2208 Expr* E = this; 2209 while (true) { 2210 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) { 2211 E = P->getSubExpr(); 2212 continue; 2213 } 2214 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) { 2215 if (P->getOpcode() == UO_Extension) { 2216 E = P->getSubExpr(); 2217 continue; 2218 } 2219 } 2220 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) { 2221 if (!P->isResultDependent()) { 2222 E = P->getResultExpr(); 2223 continue; 2224 } 2225 } 2226 return E; 2227 } 2228 } 2229 2230 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr 2231 /// or CastExprs or ImplicitCastExprs, returning their operand. 2232 Expr *Expr::IgnoreParenCasts() { 2233 Expr *E = this; 2234 while (true) { 2235 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) { 2236 E = P->getSubExpr(); 2237 continue; 2238 } 2239 if (CastExpr *P = dyn_cast<CastExpr>(E)) { 2240 E = P->getSubExpr(); 2241 continue; 2242 } 2243 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) { 2244 if (P->getOpcode() == UO_Extension) { 2245 E = P->getSubExpr(); 2246 continue; 2247 } 2248 } 2249 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) { 2250 if (!P->isResultDependent()) { 2251 E = P->getResultExpr(); 2252 continue; 2253 } 2254 } 2255 if (MaterializeTemporaryExpr *Materialize 2256 = dyn_cast<MaterializeTemporaryExpr>(E)) { 2257 E = Materialize->GetTemporaryExpr(); 2258 continue; 2259 } 2260 if (SubstNonTypeTemplateParmExpr *NTTP 2261 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 2262 E = NTTP->getReplacement(); 2263 continue; 2264 } 2265 return E; 2266 } 2267 } 2268 2269 /// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue 2270 /// casts. This is intended purely as a temporary workaround for code 2271 /// that hasn't yet been rewritten to do the right thing about those 2272 /// casts, and may disappear along with the last internal use. 2273 Expr *Expr::IgnoreParenLValueCasts() { 2274 Expr *E = this; 2275 while (true) { 2276 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) { 2277 E = P->getSubExpr(); 2278 continue; 2279 } else if (CastExpr *P = dyn_cast<CastExpr>(E)) { 2280 if (P->getCastKind() == CK_LValueToRValue) { 2281 E = P->getSubExpr(); 2282 continue; 2283 } 2284 } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) { 2285 if (P->getOpcode() == UO_Extension) { 2286 E = P->getSubExpr(); 2287 continue; 2288 } 2289 } else if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) { 2290 if (!P->isResultDependent()) { 2291 E = P->getResultExpr(); 2292 continue; 2293 } 2294 } else if (MaterializeTemporaryExpr *Materialize 2295 = dyn_cast<MaterializeTemporaryExpr>(E)) { 2296 E = Materialize->GetTemporaryExpr(); 2297 continue; 2298 } else if (SubstNonTypeTemplateParmExpr *NTTP 2299 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 2300 E = NTTP->getReplacement(); 2301 continue; 2302 } 2303 break; 2304 } 2305 return E; 2306 } 2307 2308 Expr *Expr::IgnoreParenImpCasts() { 2309 Expr *E = this; 2310 while (true) { 2311 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) { 2312 E = P->getSubExpr(); 2313 continue; 2314 } 2315 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) { 2316 E = P->getSubExpr(); 2317 continue; 2318 } 2319 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) { 2320 if (P->getOpcode() == UO_Extension) { 2321 E = P->getSubExpr(); 2322 continue; 2323 } 2324 } 2325 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) { 2326 if (!P->isResultDependent()) { 2327 E = P->getResultExpr(); 2328 continue; 2329 } 2330 } 2331 if (MaterializeTemporaryExpr *Materialize 2332 = dyn_cast<MaterializeTemporaryExpr>(E)) { 2333 E = Materialize->GetTemporaryExpr(); 2334 continue; 2335 } 2336 if (SubstNonTypeTemplateParmExpr *NTTP 2337 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 2338 E = NTTP->getReplacement(); 2339 continue; 2340 } 2341 return E; 2342 } 2343 } 2344 2345 Expr *Expr::IgnoreConversionOperator() { 2346 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) { 2347 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl())) 2348 return MCE->getImplicitObjectArgument(); 2349 } 2350 return this; 2351 } 2352 2353 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the 2354 /// value (including ptr->int casts of the same size). Strip off any 2355 /// ParenExpr or CastExprs, returning their operand. 2356 Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) { 2357 Expr *E = this; 2358 while (true) { 2359 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) { 2360 E = P->getSubExpr(); 2361 continue; 2362 } 2363 2364 if (CastExpr *P = dyn_cast<CastExpr>(E)) { 2365 // We ignore integer <-> casts that are of the same width, ptr<->ptr and 2366 // ptr<->int casts of the same width. We also ignore all identity casts. 2367 Expr *SE = P->getSubExpr(); 2368 2369 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) { 2370 E = SE; 2371 continue; 2372 } 2373 2374 if ((E->getType()->isPointerType() || 2375 E->getType()->isIntegralType(Ctx)) && 2376 (SE->getType()->isPointerType() || 2377 SE->getType()->isIntegralType(Ctx)) && 2378 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) { 2379 E = SE; 2380 continue; 2381 } 2382 } 2383 2384 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) { 2385 if (P->getOpcode() == UO_Extension) { 2386 E = P->getSubExpr(); 2387 continue; 2388 } 2389 } 2390 2391 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) { 2392 if (!P->isResultDependent()) { 2393 E = P->getResultExpr(); 2394 continue; 2395 } 2396 } 2397 2398 if (SubstNonTypeTemplateParmExpr *NTTP 2399 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 2400 E = NTTP->getReplacement(); 2401 continue; 2402 } 2403 2404 return E; 2405 } 2406 } 2407 2408 bool Expr::isDefaultArgument() const { 2409 const Expr *E = this; 2410 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E)) 2411 E = M->GetTemporaryExpr(); 2412 2413 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 2414 E = ICE->getSubExprAsWritten(); 2415 2416 return isa<CXXDefaultArgExpr>(E); 2417 } 2418 2419 /// \brief Skip over any no-op casts and any temporary-binding 2420 /// expressions. 2421 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) { 2422 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E)) 2423 E = M->GetTemporaryExpr(); 2424 2425 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2426 if (ICE->getCastKind() == CK_NoOp) 2427 E = ICE->getSubExpr(); 2428 else 2429 break; 2430 } 2431 2432 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 2433 E = BE->getSubExpr(); 2434 2435 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2436 if (ICE->getCastKind() == CK_NoOp) 2437 E = ICE->getSubExpr(); 2438 else 2439 break; 2440 } 2441 2442 return E->IgnoreParens(); 2443 } 2444 2445 /// isTemporaryObject - Determines if this expression produces a 2446 /// temporary of the given class type. 2447 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const { 2448 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy))) 2449 return false; 2450 2451 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this); 2452 2453 // Temporaries are by definition pr-values of class type. 2454 if (!E->Classify(C).isPRValue()) { 2455 // In this context, property reference is a message call and is pr-value. 2456 if (!isa<ObjCPropertyRefExpr>(E)) 2457 return false; 2458 } 2459 2460 // Black-list a few cases which yield pr-values of class type that don't 2461 // refer to temporaries of that type: 2462 2463 // - implicit derived-to-base conversions 2464 if (isa<ImplicitCastExpr>(E)) { 2465 switch (cast<ImplicitCastExpr>(E)->getCastKind()) { 2466 case CK_DerivedToBase: 2467 case CK_UncheckedDerivedToBase: 2468 return false; 2469 default: 2470 break; 2471 } 2472 } 2473 2474 // - member expressions (all) 2475 if (isa<MemberExpr>(E)) 2476 return false; 2477 2478 // - opaque values (all) 2479 if (isa<OpaqueValueExpr>(E)) 2480 return false; 2481 2482 return true; 2483 } 2484 2485 bool Expr::isImplicitCXXThis() const { 2486 const Expr *E = this; 2487 2488 // Strip away parentheses and casts we don't care about. 2489 while (true) { 2490 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) { 2491 E = Paren->getSubExpr(); 2492 continue; 2493 } 2494 2495 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2496 if (ICE->getCastKind() == CK_NoOp || 2497 ICE->getCastKind() == CK_LValueToRValue || 2498 ICE->getCastKind() == CK_DerivedToBase || 2499 ICE->getCastKind() == CK_UncheckedDerivedToBase) { 2500 E = ICE->getSubExpr(); 2501 continue; 2502 } 2503 } 2504 2505 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) { 2506 if (UnOp->getOpcode() == UO_Extension) { 2507 E = UnOp->getSubExpr(); 2508 continue; 2509 } 2510 } 2511 2512 if (const MaterializeTemporaryExpr *M 2513 = dyn_cast<MaterializeTemporaryExpr>(E)) { 2514 E = M->GetTemporaryExpr(); 2515 continue; 2516 } 2517 2518 break; 2519 } 2520 2521 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E)) 2522 return This->isImplicit(); 2523 2524 return false; 2525 } 2526 2527 /// hasAnyTypeDependentArguments - Determines if any of the expressions 2528 /// in Exprs is type-dependent. 2529 bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) { 2530 for (unsigned I = 0; I < NumExprs; ++I) 2531 if (Exprs[I]->isTypeDependent()) 2532 return true; 2533 2534 return false; 2535 } 2536 2537 /// hasAnyValueDependentArguments - Determines if any of the expressions 2538 /// in Exprs is value-dependent. 2539 bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) { 2540 for (unsigned I = 0; I < NumExprs; ++I) 2541 if (Exprs[I]->isValueDependent()) 2542 return true; 2543 2544 return false; 2545 } 2546 2547 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const { 2548 // This function is attempting whether an expression is an initializer 2549 // which can be evaluated at compile-time. isEvaluatable handles most 2550 // of the cases, but it can't deal with some initializer-specific 2551 // expressions, and it can't deal with aggregates; we deal with those here, 2552 // and fall back to isEvaluatable for the other cases. 2553 2554 // If we ever capture reference-binding directly in the AST, we can 2555 // kill the second parameter. 2556 2557 if (IsForRef) { 2558 EvalResult Result; 2559 return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects; 2560 } 2561 2562 switch (getStmtClass()) { 2563 default: break; 2564 case IntegerLiteralClass: 2565 case FloatingLiteralClass: 2566 case StringLiteralClass: 2567 case ObjCStringLiteralClass: 2568 case ObjCEncodeExprClass: 2569 return true; 2570 case CXXTemporaryObjectExprClass: 2571 case CXXConstructExprClass: { 2572 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this); 2573 2574 // Only if it's 2575 if (CE->getConstructor()->isTrivial()) { 2576 // 1) an application of the trivial default constructor or 2577 if (!CE->getNumArgs()) return true; 2578 2579 // 2) an elidable trivial copy construction of an operand which is 2580 // itself a constant initializer. Note that we consider the 2581 // operand on its own, *not* as a reference binding. 2582 if (CE->isElidable() && 2583 CE->getArg(0)->isConstantInitializer(Ctx, false)) 2584 return true; 2585 } 2586 2587 // 3) a foldable constexpr constructor. 2588 break; 2589 } 2590 case CompoundLiteralExprClass: { 2591 // This handles gcc's extension that allows global initializers like 2592 // "struct x {int x;} x = (struct x) {};". 2593 // FIXME: This accepts other cases it shouldn't! 2594 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer(); 2595 return Exp->isConstantInitializer(Ctx, false); 2596 } 2597 case InitListExprClass: { 2598 // FIXME: This doesn't deal with fields with reference types correctly. 2599 // FIXME: This incorrectly allows pointers cast to integers to be assigned 2600 // to bitfields. 2601 const InitListExpr *Exp = cast<InitListExpr>(this); 2602 unsigned numInits = Exp->getNumInits(); 2603 for (unsigned i = 0; i < numInits; i++) { 2604 if (!Exp->getInit(i)->isConstantInitializer(Ctx, false)) 2605 return false; 2606 } 2607 return true; 2608 } 2609 case ImplicitValueInitExprClass: 2610 return true; 2611 case ParenExprClass: 2612 return cast<ParenExpr>(this)->getSubExpr() 2613 ->isConstantInitializer(Ctx, IsForRef); 2614 case GenericSelectionExprClass: 2615 if (cast<GenericSelectionExpr>(this)->isResultDependent()) 2616 return false; 2617 return cast<GenericSelectionExpr>(this)->getResultExpr() 2618 ->isConstantInitializer(Ctx, IsForRef); 2619 case ChooseExprClass: 2620 return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx) 2621 ->isConstantInitializer(Ctx, IsForRef); 2622 case UnaryOperatorClass: { 2623 const UnaryOperator* Exp = cast<UnaryOperator>(this); 2624 if (Exp->getOpcode() == UO_Extension) 2625 return Exp->getSubExpr()->isConstantInitializer(Ctx, false); 2626 break; 2627 } 2628 case CXXFunctionalCastExprClass: 2629 case CXXStaticCastExprClass: 2630 case ImplicitCastExprClass: 2631 case CStyleCastExprClass: { 2632 const CastExpr *CE = cast<CastExpr>(this); 2633 2634 // If we're promoting an integer to an _Atomic type then this is constant 2635 // if the integer is constant. We also need to check the converse in case 2636 // someone does something like: 2637 // 2638 // int a = (_Atomic(int))42; 2639 // 2640 // I doubt anyone would write code like this directly, but it's quite 2641 // possible as the result of macro expansions. 2642 if (CE->getCastKind() == CK_NonAtomicToAtomic || 2643 CE->getCastKind() == CK_AtomicToNonAtomic) 2644 return CE->getSubExpr()->isConstantInitializer(Ctx, false); 2645 2646 // Handle bitcasts of vector constants. 2647 if (getType()->isVectorType() && CE->getCastKind() == CK_BitCast) 2648 return CE->getSubExpr()->isConstantInitializer(Ctx, false); 2649 2650 // Handle misc casts we want to ignore. 2651 // FIXME: Is it really safe to ignore all these? 2652 if (CE->getCastKind() == CK_NoOp || 2653 CE->getCastKind() == CK_LValueToRValue || 2654 CE->getCastKind() == CK_ToUnion || 2655 CE->getCastKind() == CK_ConstructorConversion) 2656 return CE->getSubExpr()->isConstantInitializer(Ctx, false); 2657 2658 break; 2659 } 2660 case MaterializeTemporaryExprClass: 2661 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr() 2662 ->isConstantInitializer(Ctx, false); 2663 } 2664 return isEvaluatable(Ctx); 2665 } 2666 2667 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null 2668 /// pointer constant or not, as well as the specific kind of constant detected. 2669 /// Null pointer constants can be integer constant expressions with the 2670 /// value zero, casts of zero to void*, nullptr (C++0X), or __null 2671 /// (a GNU extension). 2672 Expr::NullPointerConstantKind 2673 Expr::isNullPointerConstant(ASTContext &Ctx, 2674 NullPointerConstantValueDependence NPC) const { 2675 if (isValueDependent()) { 2676 switch (NPC) { 2677 case NPC_NeverValueDependent: 2678 llvm_unreachable("Unexpected value dependent expression!"); 2679 case NPC_ValueDependentIsNull: 2680 if (isTypeDependent() || getType()->isIntegralType(Ctx)) 2681 return NPCK_ZeroInteger; 2682 else 2683 return NPCK_NotNull; 2684 2685 case NPC_ValueDependentIsNotNull: 2686 return NPCK_NotNull; 2687 } 2688 } 2689 2690 // Strip off a cast to void*, if it exists. Except in C++. 2691 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) { 2692 if (!Ctx.getLangOptions().CPlusPlus) { 2693 // Check that it is a cast to void*. 2694 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) { 2695 QualType Pointee = PT->getPointeeType(); 2696 if (!Pointee.hasQualifiers() && 2697 Pointee->isVoidType() && // to void* 2698 CE->getSubExpr()->getType()->isIntegerType()) // from int. 2699 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 2700 } 2701 } 2702 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) { 2703 // Ignore the ImplicitCastExpr type entirely. 2704 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 2705 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) { 2706 // Accept ((void*)0) as a null pointer constant, as many other 2707 // implementations do. 2708 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC); 2709 } else if (const GenericSelectionExpr *GE = 2710 dyn_cast<GenericSelectionExpr>(this)) { 2711 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC); 2712 } else if (const CXXDefaultArgExpr *DefaultArg 2713 = dyn_cast<CXXDefaultArgExpr>(this)) { 2714 // See through default argument expressions 2715 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC); 2716 } else if (isa<GNUNullExpr>(this)) { 2717 // The GNU __null extension is always a null pointer constant. 2718 return NPCK_GNUNull; 2719 } else if (const MaterializeTemporaryExpr *M 2720 = dyn_cast<MaterializeTemporaryExpr>(this)) { 2721 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC); 2722 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) { 2723 if (const Expr *Source = OVE->getSourceExpr()) 2724 return Source->isNullPointerConstant(Ctx, NPC); 2725 } 2726 2727 // C++0x nullptr_t is always a null pointer constant. 2728 if (getType()->isNullPtrType()) 2729 return NPCK_CXX0X_nullptr; 2730 2731 if (const RecordType *UT = getType()->getAsUnionType()) 2732 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2733 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){ 2734 const Expr *InitExpr = CLE->getInitializer(); 2735 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr)) 2736 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC); 2737 } 2738 // This expression must be an integer type. 2739 if (!getType()->isIntegerType() || 2740 (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType())) 2741 return NPCK_NotNull; 2742 2743 // If we have an integer constant expression, we need to *evaluate* it and 2744 // test for the value 0. Don't use the C++11 constant expression semantics 2745 // for this, for now; once the dust settles on core issue 903, we might only 2746 // allow a literal 0 here in C++11 mode. 2747 if (Ctx.getLangOptions().CPlusPlus0x) { 2748 if (!isCXX98IntegralConstantExpr(Ctx)) 2749 return NPCK_NotNull; 2750 } else { 2751 if (!isIntegerConstantExpr(Ctx)) 2752 return NPCK_NotNull; 2753 } 2754 2755 return (EvaluateKnownConstInt(Ctx) == 0) ? NPCK_ZeroInteger : NPCK_NotNull; 2756 } 2757 2758 /// \brief If this expression is an l-value for an Objective C 2759 /// property, find the underlying property reference expression. 2760 const ObjCPropertyRefExpr *Expr::getObjCProperty() const { 2761 const Expr *E = this; 2762 while (true) { 2763 assert((E->getValueKind() == VK_LValue && 2764 E->getObjectKind() == OK_ObjCProperty) && 2765 "expression is not a property reference"); 2766 E = E->IgnoreParenCasts(); 2767 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2768 if (BO->getOpcode() == BO_Comma) { 2769 E = BO->getRHS(); 2770 continue; 2771 } 2772 } 2773 2774 break; 2775 } 2776 2777 return cast<ObjCPropertyRefExpr>(E); 2778 } 2779 2780 FieldDecl *Expr::getBitField() { 2781 Expr *E = this->IgnoreParens(); 2782 2783 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2784 if (ICE->getCastKind() == CK_LValueToRValue || 2785 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp)) 2786 E = ICE->getSubExpr()->IgnoreParens(); 2787 else 2788 break; 2789 } 2790 2791 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E)) 2792 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) 2793 if (Field->isBitField()) 2794 return Field; 2795 2796 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) 2797 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl())) 2798 if (Field->isBitField()) 2799 return Field; 2800 2801 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) { 2802 if (BinOp->isAssignmentOp() && BinOp->getLHS()) 2803 return BinOp->getLHS()->getBitField(); 2804 2805 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS()) 2806 return BinOp->getRHS()->getBitField(); 2807 } 2808 2809 return 0; 2810 } 2811 2812 bool Expr::refersToVectorElement() const { 2813 const Expr *E = this->IgnoreParens(); 2814 2815 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2816 if (ICE->getValueKind() != VK_RValue && 2817 ICE->getCastKind() == CK_NoOp) 2818 E = ICE->getSubExpr()->IgnoreParens(); 2819 else 2820 break; 2821 } 2822 2823 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E)) 2824 return ASE->getBase()->getType()->isVectorType(); 2825 2826 if (isa<ExtVectorElementExpr>(E)) 2827 return true; 2828 2829 return false; 2830 } 2831 2832 /// isArrow - Return true if the base expression is a pointer to vector, 2833 /// return false if the base expression is a vector. 2834 bool ExtVectorElementExpr::isArrow() const { 2835 return getBase()->getType()->isPointerType(); 2836 } 2837 2838 unsigned ExtVectorElementExpr::getNumElements() const { 2839 if (const VectorType *VT = getType()->getAs<VectorType>()) 2840 return VT->getNumElements(); 2841 return 1; 2842 } 2843 2844 /// containsDuplicateElements - Return true if any element access is repeated. 2845 bool ExtVectorElementExpr::containsDuplicateElements() const { 2846 // FIXME: Refactor this code to an accessor on the AST node which returns the 2847 // "type" of component access, and share with code below and in Sema. 2848 StringRef Comp = Accessor->getName(); 2849 2850 // Halving swizzles do not contain duplicate elements. 2851 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd") 2852 return false; 2853 2854 // Advance past s-char prefix on hex swizzles. 2855 if (Comp[0] == 's' || Comp[0] == 'S') 2856 Comp = Comp.substr(1); 2857 2858 for (unsigned i = 0, e = Comp.size(); i != e; ++i) 2859 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos) 2860 return true; 2861 2862 return false; 2863 } 2864 2865 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray. 2866 void ExtVectorElementExpr::getEncodedElementAccess( 2867 SmallVectorImpl<unsigned> &Elts) const { 2868 StringRef Comp = Accessor->getName(); 2869 if (Comp[0] == 's' || Comp[0] == 'S') 2870 Comp = Comp.substr(1); 2871 2872 bool isHi = Comp == "hi"; 2873 bool isLo = Comp == "lo"; 2874 bool isEven = Comp == "even"; 2875 bool isOdd = Comp == "odd"; 2876 2877 for (unsigned i = 0, e = getNumElements(); i != e; ++i) { 2878 uint64_t Index; 2879 2880 if (isHi) 2881 Index = e + i; 2882 else if (isLo) 2883 Index = i; 2884 else if (isEven) 2885 Index = 2 * i; 2886 else if (isOdd) 2887 Index = 2 * i + 1; 2888 else 2889 Index = ExtVectorType::getAccessorIdx(Comp[i]); 2890 2891 Elts.push_back(Index); 2892 } 2893 } 2894 2895 ObjCMessageExpr::ObjCMessageExpr(QualType T, 2896 ExprValueKind VK, 2897 SourceLocation LBracLoc, 2898 SourceLocation SuperLoc, 2899 bool IsInstanceSuper, 2900 QualType SuperType, 2901 Selector Sel, 2902 ArrayRef<SourceLocation> SelLocs, 2903 SelectorLocationsKind SelLocsK, 2904 ObjCMethodDecl *Method, 2905 ArrayRef<Expr *> Args, 2906 SourceLocation RBracLoc, 2907 bool isImplicit) 2908 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, 2909 /*TypeDependent=*/false, /*ValueDependent=*/false, 2910 /*InstantiationDependent=*/false, 2911 /*ContainsUnexpandedParameterPack=*/false), 2912 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method 2913 : Sel.getAsOpaquePtr())), 2914 Kind(IsInstanceSuper? SuperInstance : SuperClass), 2915 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit), 2916 SuperLoc(SuperLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc) 2917 { 2918 initArgsAndSelLocs(Args, SelLocs, SelLocsK); 2919 setReceiverPointer(SuperType.getAsOpaquePtr()); 2920 } 2921 2922 ObjCMessageExpr::ObjCMessageExpr(QualType T, 2923 ExprValueKind VK, 2924 SourceLocation LBracLoc, 2925 TypeSourceInfo *Receiver, 2926 Selector Sel, 2927 ArrayRef<SourceLocation> SelLocs, 2928 SelectorLocationsKind SelLocsK, 2929 ObjCMethodDecl *Method, 2930 ArrayRef<Expr *> Args, 2931 SourceLocation RBracLoc, 2932 bool isImplicit) 2933 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(), 2934 T->isDependentType(), T->isInstantiationDependentType(), 2935 T->containsUnexpandedParameterPack()), 2936 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method 2937 : Sel.getAsOpaquePtr())), 2938 Kind(Class), 2939 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit), 2940 LBracLoc(LBracLoc), RBracLoc(RBracLoc) 2941 { 2942 initArgsAndSelLocs(Args, SelLocs, SelLocsK); 2943 setReceiverPointer(Receiver); 2944 } 2945 2946 ObjCMessageExpr::ObjCMessageExpr(QualType T, 2947 ExprValueKind VK, 2948 SourceLocation LBracLoc, 2949 Expr *Receiver, 2950 Selector Sel, 2951 ArrayRef<SourceLocation> SelLocs, 2952 SelectorLocationsKind SelLocsK, 2953 ObjCMethodDecl *Method, 2954 ArrayRef<Expr *> Args, 2955 SourceLocation RBracLoc, 2956 bool isImplicit) 2957 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(), 2958 Receiver->isTypeDependent(), 2959 Receiver->isInstantiationDependent(), 2960 Receiver->containsUnexpandedParameterPack()), 2961 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method 2962 : Sel.getAsOpaquePtr())), 2963 Kind(Instance), 2964 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit), 2965 LBracLoc(LBracLoc), RBracLoc(RBracLoc) 2966 { 2967 initArgsAndSelLocs(Args, SelLocs, SelLocsK); 2968 setReceiverPointer(Receiver); 2969 } 2970 2971 void ObjCMessageExpr::initArgsAndSelLocs(ArrayRef<Expr *> Args, 2972 ArrayRef<SourceLocation> SelLocs, 2973 SelectorLocationsKind SelLocsK) { 2974 setNumArgs(Args.size()); 2975 Expr **MyArgs = getArgs(); 2976 for (unsigned I = 0; I != Args.size(); ++I) { 2977 if (Args[I]->isTypeDependent()) 2978 ExprBits.TypeDependent = true; 2979 if (Args[I]->isValueDependent()) 2980 ExprBits.ValueDependent = true; 2981 if (Args[I]->isInstantiationDependent()) 2982 ExprBits.InstantiationDependent = true; 2983 if (Args[I]->containsUnexpandedParameterPack()) 2984 ExprBits.ContainsUnexpandedParameterPack = true; 2985 2986 MyArgs[I] = Args[I]; 2987 } 2988 2989 SelLocsKind = SelLocsK; 2990 if (!isImplicit()) { 2991 if (SelLocsK == SelLoc_NonStandard) 2992 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs()); 2993 } 2994 } 2995 2996 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T, 2997 ExprValueKind VK, 2998 SourceLocation LBracLoc, 2999 SourceLocation SuperLoc, 3000 bool IsInstanceSuper, 3001 QualType SuperType, 3002 Selector Sel, 3003 ArrayRef<SourceLocation> SelLocs, 3004 ObjCMethodDecl *Method, 3005 ArrayRef<Expr *> Args, 3006 SourceLocation RBracLoc, 3007 bool isImplicit) { 3008 assert((!SelLocs.empty() || isImplicit) && 3009 "No selector locs for non-implicit message"); 3010 ObjCMessageExpr *Mem; 3011 SelectorLocationsKind SelLocsK = SelectorLocationsKind(); 3012 if (isImplicit) 3013 Mem = alloc(Context, Args.size(), 0); 3014 else 3015 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK); 3016 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper, 3017 SuperType, Sel, SelLocs, SelLocsK, 3018 Method, Args, RBracLoc, isImplicit); 3019 } 3020 3021 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T, 3022 ExprValueKind VK, 3023 SourceLocation LBracLoc, 3024 TypeSourceInfo *Receiver, 3025 Selector Sel, 3026 ArrayRef<SourceLocation> SelLocs, 3027 ObjCMethodDecl *Method, 3028 ArrayRef<Expr *> Args, 3029 SourceLocation RBracLoc, 3030 bool isImplicit) { 3031 assert((!SelLocs.empty() || isImplicit) && 3032 "No selector locs for non-implicit message"); 3033 ObjCMessageExpr *Mem; 3034 SelectorLocationsKind SelLocsK = SelectorLocationsKind(); 3035 if (isImplicit) 3036 Mem = alloc(Context, Args.size(), 0); 3037 else 3038 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK); 3039 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, 3040 SelLocs, SelLocsK, Method, Args, RBracLoc, 3041 isImplicit); 3042 } 3043 3044 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T, 3045 ExprValueKind VK, 3046 SourceLocation LBracLoc, 3047 Expr *Receiver, 3048 Selector Sel, 3049 ArrayRef<SourceLocation> SelLocs, 3050 ObjCMethodDecl *Method, 3051 ArrayRef<Expr *> Args, 3052 SourceLocation RBracLoc, 3053 bool isImplicit) { 3054 assert((!SelLocs.empty() || isImplicit) && 3055 "No selector locs for non-implicit message"); 3056 ObjCMessageExpr *Mem; 3057 SelectorLocationsKind SelLocsK = SelectorLocationsKind(); 3058 if (isImplicit) 3059 Mem = alloc(Context, Args.size(), 0); 3060 else 3061 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK); 3062 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, 3063 SelLocs, SelLocsK, Method, Args, RBracLoc, 3064 isImplicit); 3065 } 3066 3067 ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context, 3068 unsigned NumArgs, 3069 unsigned NumStoredSelLocs) { 3070 ObjCMessageExpr *Mem = alloc(Context, NumArgs, NumStoredSelLocs); 3071 return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs); 3072 } 3073 3074 ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C, 3075 ArrayRef<Expr *> Args, 3076 SourceLocation RBraceLoc, 3077 ArrayRef<SourceLocation> SelLocs, 3078 Selector Sel, 3079 SelectorLocationsKind &SelLocsK) { 3080 SelLocsK = hasStandardSelectorLocs(Sel, SelLocs, Args, RBraceLoc); 3081 unsigned NumStoredSelLocs = (SelLocsK == SelLoc_NonStandard) ? SelLocs.size() 3082 : 0; 3083 return alloc(C, Args.size(), NumStoredSelLocs); 3084 } 3085 3086 ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C, 3087 unsigned NumArgs, 3088 unsigned NumStoredSelLocs) { 3089 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) + 3090 NumArgs * sizeof(Expr *) + NumStoredSelLocs * sizeof(SourceLocation); 3091 return (ObjCMessageExpr *)C.Allocate(Size, 3092 llvm::AlignOf<ObjCMessageExpr>::Alignment); 3093 } 3094 3095 void ObjCMessageExpr::getSelectorLocs( 3096 SmallVectorImpl<SourceLocation> &SelLocs) const { 3097 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i) 3098 SelLocs.push_back(getSelectorLoc(i)); 3099 } 3100 3101 SourceRange ObjCMessageExpr::getReceiverRange() const { 3102 switch (getReceiverKind()) { 3103 case Instance: 3104 return getInstanceReceiver()->getSourceRange(); 3105 3106 case Class: 3107 return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange(); 3108 3109 case SuperInstance: 3110 case SuperClass: 3111 return getSuperLoc(); 3112 } 3113 3114 llvm_unreachable("Invalid ReceiverKind!"); 3115 } 3116 3117 Selector ObjCMessageExpr::getSelector() const { 3118 if (HasMethod) 3119 return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod) 3120 ->getSelector(); 3121 return Selector(SelectorOrMethod); 3122 } 3123 3124 ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const { 3125 switch (getReceiverKind()) { 3126 case Instance: 3127 if (const ObjCObjectPointerType *Ptr 3128 = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>()) 3129 return Ptr->getInterfaceDecl(); 3130 break; 3131 3132 case Class: 3133 if (const ObjCObjectType *Ty 3134 = getClassReceiver()->getAs<ObjCObjectType>()) 3135 return Ty->getInterface(); 3136 break; 3137 3138 case SuperInstance: 3139 if (const ObjCObjectPointerType *Ptr 3140 = getSuperType()->getAs<ObjCObjectPointerType>()) 3141 return Ptr->getInterfaceDecl(); 3142 break; 3143 3144 case SuperClass: 3145 if (const ObjCObjectType *Iface 3146 = getSuperType()->getAs<ObjCObjectType>()) 3147 return Iface->getInterface(); 3148 break; 3149 } 3150 3151 return 0; 3152 } 3153 3154 StringRef ObjCBridgedCastExpr::getBridgeKindName() const { 3155 switch (getBridgeKind()) { 3156 case OBC_Bridge: 3157 return "__bridge"; 3158 case OBC_BridgeTransfer: 3159 return "__bridge_transfer"; 3160 case OBC_BridgeRetained: 3161 return "__bridge_retained"; 3162 } 3163 3164 llvm_unreachable("Invalid BridgeKind!"); 3165 } 3166 3167 bool ChooseExpr::isConditionTrue(const ASTContext &C) const { 3168 return getCond()->EvaluateKnownConstInt(C) != 0; 3169 } 3170 3171 ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr, 3172 QualType Type, SourceLocation BLoc, 3173 SourceLocation RP) 3174 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary, 3175 Type->isDependentType(), Type->isDependentType(), 3176 Type->isInstantiationDependentType(), 3177 Type->containsUnexpandedParameterPack()), 3178 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr) 3179 { 3180 SubExprs = new (C) Stmt*[nexpr]; 3181 for (unsigned i = 0; i < nexpr; i++) { 3182 if (args[i]->isTypeDependent()) 3183 ExprBits.TypeDependent = true; 3184 if (args[i]->isValueDependent()) 3185 ExprBits.ValueDependent = true; 3186 if (args[i]->isInstantiationDependent()) 3187 ExprBits.InstantiationDependent = true; 3188 if (args[i]->containsUnexpandedParameterPack()) 3189 ExprBits.ContainsUnexpandedParameterPack = true; 3190 3191 SubExprs[i] = args[i]; 3192 } 3193 } 3194 3195 void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs, 3196 unsigned NumExprs) { 3197 if (SubExprs) C.Deallocate(SubExprs); 3198 3199 SubExprs = new (C) Stmt* [NumExprs]; 3200 this->NumExprs = NumExprs; 3201 memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs); 3202 } 3203 3204 GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context, 3205 SourceLocation GenericLoc, Expr *ControllingExpr, 3206 TypeSourceInfo **AssocTypes, Expr **AssocExprs, 3207 unsigned NumAssocs, SourceLocation DefaultLoc, 3208 SourceLocation RParenLoc, 3209 bool ContainsUnexpandedParameterPack, 3210 unsigned ResultIndex) 3211 : Expr(GenericSelectionExprClass, 3212 AssocExprs[ResultIndex]->getType(), 3213 AssocExprs[ResultIndex]->getValueKind(), 3214 AssocExprs[ResultIndex]->getObjectKind(), 3215 AssocExprs[ResultIndex]->isTypeDependent(), 3216 AssocExprs[ResultIndex]->isValueDependent(), 3217 AssocExprs[ResultIndex]->isInstantiationDependent(), 3218 ContainsUnexpandedParameterPack), 3219 AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]), 3220 SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs), 3221 ResultIndex(ResultIndex), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), 3222 RParenLoc(RParenLoc) { 3223 SubExprs[CONTROLLING] = ControllingExpr; 3224 std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes); 3225 std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR); 3226 } 3227 3228 GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context, 3229 SourceLocation GenericLoc, Expr *ControllingExpr, 3230 TypeSourceInfo **AssocTypes, Expr **AssocExprs, 3231 unsigned NumAssocs, SourceLocation DefaultLoc, 3232 SourceLocation RParenLoc, 3233 bool ContainsUnexpandedParameterPack) 3234 : Expr(GenericSelectionExprClass, 3235 Context.DependentTy, 3236 VK_RValue, 3237 OK_Ordinary, 3238 /*isTypeDependent=*/true, 3239 /*isValueDependent=*/true, 3240 /*isInstantiationDependent=*/true, 3241 ContainsUnexpandedParameterPack), 3242 AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]), 3243 SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs), 3244 ResultIndex(-1U), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), 3245 RParenLoc(RParenLoc) { 3246 SubExprs[CONTROLLING] = ControllingExpr; 3247 std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes); 3248 std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR); 3249 } 3250 3251 //===----------------------------------------------------------------------===// 3252 // DesignatedInitExpr 3253 //===----------------------------------------------------------------------===// 3254 3255 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const { 3256 assert(Kind == FieldDesignator && "Only valid on a field designator"); 3257 if (Field.NameOrField & 0x01) 3258 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01); 3259 else 3260 return getField()->getIdentifier(); 3261 } 3262 3263 DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty, 3264 unsigned NumDesignators, 3265 const Designator *Designators, 3266 SourceLocation EqualOrColonLoc, 3267 bool GNUSyntax, 3268 Expr **IndexExprs, 3269 unsigned NumIndexExprs, 3270 Expr *Init) 3271 : Expr(DesignatedInitExprClass, Ty, 3272 Init->getValueKind(), Init->getObjectKind(), 3273 Init->isTypeDependent(), Init->isValueDependent(), 3274 Init->isInstantiationDependent(), 3275 Init->containsUnexpandedParameterPack()), 3276 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax), 3277 NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) { 3278 this->Designators = new (C) Designator[NumDesignators]; 3279 3280 // Record the initializer itself. 3281 child_range Child = children(); 3282 *Child++ = Init; 3283 3284 // Copy the designators and their subexpressions, computing 3285 // value-dependence along the way. 3286 unsigned IndexIdx = 0; 3287 for (unsigned I = 0; I != NumDesignators; ++I) { 3288 this->Designators[I] = Designators[I]; 3289 3290 if (this->Designators[I].isArrayDesignator()) { 3291 // Compute type- and value-dependence. 3292 Expr *Index = IndexExprs[IndexIdx]; 3293 if (Index->isTypeDependent() || Index->isValueDependent()) 3294 ExprBits.ValueDependent = true; 3295 if (Index->isInstantiationDependent()) 3296 ExprBits.InstantiationDependent = true; 3297 // Propagate unexpanded parameter packs. 3298 if (Index->containsUnexpandedParameterPack()) 3299 ExprBits.ContainsUnexpandedParameterPack = true; 3300 3301 // Copy the index expressions into permanent storage. 3302 *Child++ = IndexExprs[IndexIdx++]; 3303 } else if (this->Designators[I].isArrayRangeDesignator()) { 3304 // Compute type- and value-dependence. 3305 Expr *Start = IndexExprs[IndexIdx]; 3306 Expr *End = IndexExprs[IndexIdx + 1]; 3307 if (Start->isTypeDependent() || Start->isValueDependent() || 3308 End->isTypeDependent() || End->isValueDependent()) { 3309 ExprBits.ValueDependent = true; 3310 ExprBits.InstantiationDependent = true; 3311 } else if (Start->isInstantiationDependent() || 3312 End->isInstantiationDependent()) { 3313 ExprBits.InstantiationDependent = true; 3314 } 3315 3316 // Propagate unexpanded parameter packs. 3317 if (Start->containsUnexpandedParameterPack() || 3318 End->containsUnexpandedParameterPack()) 3319 ExprBits.ContainsUnexpandedParameterPack = true; 3320 3321 // Copy the start/end expressions into permanent storage. 3322 *Child++ = IndexExprs[IndexIdx++]; 3323 *Child++ = IndexExprs[IndexIdx++]; 3324 } 3325 } 3326 3327 assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions"); 3328 } 3329 3330 DesignatedInitExpr * 3331 DesignatedInitExpr::Create(ASTContext &C, Designator *Designators, 3332 unsigned NumDesignators, 3333 Expr **IndexExprs, unsigned NumIndexExprs, 3334 SourceLocation ColonOrEqualLoc, 3335 bool UsesColonSyntax, Expr *Init) { 3336 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) + 3337 sizeof(Stmt *) * (NumIndexExprs + 1), 8); 3338 return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators, 3339 ColonOrEqualLoc, UsesColonSyntax, 3340 IndexExprs, NumIndexExprs, Init); 3341 } 3342 3343 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C, 3344 unsigned NumIndexExprs) { 3345 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) + 3346 sizeof(Stmt *) * (NumIndexExprs + 1), 8); 3347 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1); 3348 } 3349 3350 void DesignatedInitExpr::setDesignators(ASTContext &C, 3351 const Designator *Desigs, 3352 unsigned NumDesigs) { 3353 Designators = new (C) Designator[NumDesigs]; 3354 NumDesignators = NumDesigs; 3355 for (unsigned I = 0; I != NumDesigs; ++I) 3356 Designators[I] = Desigs[I]; 3357 } 3358 3359 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const { 3360 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this); 3361 if (size() == 1) 3362 return DIE->getDesignator(0)->getSourceRange(); 3363 return SourceRange(DIE->getDesignator(0)->getStartLocation(), 3364 DIE->getDesignator(size()-1)->getEndLocation()); 3365 } 3366 3367 SourceRange DesignatedInitExpr::getSourceRange() const { 3368 SourceLocation StartLoc; 3369 Designator &First = 3370 *const_cast<DesignatedInitExpr*>(this)->designators_begin(); 3371 if (First.isFieldDesignator()) { 3372 if (GNUSyntax) 3373 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc); 3374 else 3375 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc); 3376 } else 3377 StartLoc = 3378 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc); 3379 return SourceRange(StartLoc, getInit()->getSourceRange().getEnd()); 3380 } 3381 3382 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) { 3383 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator"); 3384 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 3385 Ptr += sizeof(DesignatedInitExpr); 3386 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 3387 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1)); 3388 } 3389 3390 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) { 3391 assert(D.Kind == Designator::ArrayRangeDesignator && 3392 "Requires array range designator"); 3393 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 3394 Ptr += sizeof(DesignatedInitExpr); 3395 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 3396 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1)); 3397 } 3398 3399 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) { 3400 assert(D.Kind == Designator::ArrayRangeDesignator && 3401 "Requires array range designator"); 3402 char* Ptr = static_cast<char*>(static_cast<void *>(this)); 3403 Ptr += sizeof(DesignatedInitExpr); 3404 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr)); 3405 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2)); 3406 } 3407 3408 /// \brief Replaces the designator at index @p Idx with the series 3409 /// of designators in [First, Last). 3410 void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx, 3411 const Designator *First, 3412 const Designator *Last) { 3413 unsigned NumNewDesignators = Last - First; 3414 if (NumNewDesignators == 0) { 3415 std::copy_backward(Designators + Idx + 1, 3416 Designators + NumDesignators, 3417 Designators + Idx); 3418 --NumNewDesignators; 3419 return; 3420 } else if (NumNewDesignators == 1) { 3421 Designators[Idx] = *First; 3422 return; 3423 } 3424 3425 Designator *NewDesignators 3426 = new (C) Designator[NumDesignators - 1 + NumNewDesignators]; 3427 std::copy(Designators, Designators + Idx, NewDesignators); 3428 std::copy(First, Last, NewDesignators + Idx); 3429 std::copy(Designators + Idx + 1, Designators + NumDesignators, 3430 NewDesignators + Idx + NumNewDesignators); 3431 Designators = NewDesignators; 3432 NumDesignators = NumDesignators - 1 + NumNewDesignators; 3433 } 3434 3435 ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc, 3436 Expr **exprs, unsigned nexprs, 3437 SourceLocation rparenloc) 3438 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, 3439 false, false, false, false), 3440 NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) { 3441 Exprs = new (C) Stmt*[nexprs]; 3442 for (unsigned i = 0; i != nexprs; ++i) { 3443 if (exprs[i]->isTypeDependent()) 3444 ExprBits.TypeDependent = true; 3445 if (exprs[i]->isValueDependent()) 3446 ExprBits.ValueDependent = true; 3447 if (exprs[i]->isInstantiationDependent()) 3448 ExprBits.InstantiationDependent = true; 3449 if (exprs[i]->containsUnexpandedParameterPack()) 3450 ExprBits.ContainsUnexpandedParameterPack = true; 3451 3452 Exprs[i] = exprs[i]; 3453 } 3454 } 3455 3456 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) { 3457 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e)) 3458 e = ewc->getSubExpr(); 3459 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e)) 3460 e = m->GetTemporaryExpr(); 3461 e = cast<CXXConstructExpr>(e)->getArg(0); 3462 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) 3463 e = ice->getSubExpr(); 3464 return cast<OpaqueValueExpr>(e); 3465 } 3466 3467 PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &Context, EmptyShell sh, 3468 unsigned numSemanticExprs) { 3469 void *buffer = Context.Allocate(sizeof(PseudoObjectExpr) + 3470 (1 + numSemanticExprs) * sizeof(Expr*), 3471 llvm::alignOf<PseudoObjectExpr>()); 3472 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs); 3473 } 3474 3475 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs) 3476 : Expr(PseudoObjectExprClass, shell) { 3477 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1; 3478 } 3479 3480 PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &C, Expr *syntax, 3481 ArrayRef<Expr*> semantics, 3482 unsigned resultIndex) { 3483 assert(syntax && "no syntactic expression!"); 3484 assert(semantics.size() && "no semantic expressions!"); 3485 3486 QualType type; 3487 ExprValueKind VK; 3488 if (resultIndex == NoResult) { 3489 type = C.VoidTy; 3490 VK = VK_RValue; 3491 } else { 3492 assert(resultIndex < semantics.size()); 3493 type = semantics[resultIndex]->getType(); 3494 VK = semantics[resultIndex]->getValueKind(); 3495 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary); 3496 } 3497 3498 void *buffer = C.Allocate(sizeof(PseudoObjectExpr) + 3499 (1 + semantics.size()) * sizeof(Expr*), 3500 llvm::alignOf<PseudoObjectExpr>()); 3501 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics, 3502 resultIndex); 3503 } 3504 3505 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK, 3506 Expr *syntax, ArrayRef<Expr*> semantics, 3507 unsigned resultIndex) 3508 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary, 3509 /*filled in at end of ctor*/ false, false, false, false) { 3510 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1; 3511 PseudoObjectExprBits.ResultIndex = resultIndex + 1; 3512 3513 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) { 3514 Expr *E = (i == 0 ? syntax : semantics[i-1]); 3515 getSubExprsBuffer()[i] = E; 3516 3517 if (E->isTypeDependent()) 3518 ExprBits.TypeDependent = true; 3519 if (E->isValueDependent()) 3520 ExprBits.ValueDependent = true; 3521 if (E->isInstantiationDependent()) 3522 ExprBits.InstantiationDependent = true; 3523 if (E->containsUnexpandedParameterPack()) 3524 ExprBits.ContainsUnexpandedParameterPack = true; 3525 3526 if (isa<OpaqueValueExpr>(E)) 3527 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != 0 && 3528 "opaque-value semantic expressions for pseudo-object " 3529 "operations must have sources"); 3530 } 3531 } 3532 3533 //===----------------------------------------------------------------------===// 3534 // ExprIterator. 3535 //===----------------------------------------------------------------------===// 3536 3537 Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); } 3538 Expr* ExprIterator::operator*() const { return cast<Expr>(*I); } 3539 Expr* ExprIterator::operator->() const { return cast<Expr>(*I); } 3540 const Expr* ConstExprIterator::operator[](size_t idx) const { 3541 return cast<Expr>(I[idx]); 3542 } 3543 const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); } 3544 const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); } 3545 3546 //===----------------------------------------------------------------------===// 3547 // Child Iterators for iterating over subexpressions/substatements 3548 //===----------------------------------------------------------------------===// 3549 3550 // UnaryExprOrTypeTraitExpr 3551 Stmt::child_range UnaryExprOrTypeTraitExpr::children() { 3552 // If this is of a type and the type is a VLA type (and not a typedef), the 3553 // size expression of the VLA needs to be treated as an executable expression. 3554 // Why isn't this weirdness documented better in StmtIterator? 3555 if (isArgumentType()) { 3556 if (const VariableArrayType* T = dyn_cast<VariableArrayType>( 3557 getArgumentType().getTypePtr())) 3558 return child_range(child_iterator(T), child_iterator()); 3559 return child_range(); 3560 } 3561 return child_range(&Argument.Ex, &Argument.Ex + 1); 3562 } 3563 3564 // ObjCMessageExpr 3565 Stmt::child_range ObjCMessageExpr::children() { 3566 Stmt **begin; 3567 if (getReceiverKind() == Instance) 3568 begin = reinterpret_cast<Stmt **>(this + 1); 3569 else 3570 begin = reinterpret_cast<Stmt **>(getArgs()); 3571 return child_range(begin, 3572 reinterpret_cast<Stmt **>(getArgs() + getNumArgs())); 3573 } 3574 3575 // Blocks 3576 BlockDeclRefExpr::BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK, 3577 SourceLocation l, bool ByRef, 3578 bool constAdded) 3579 : Expr(BlockDeclRefExprClass, t, VK, OK_Ordinary, false, false, false, 3580 d->isParameterPack()), 3581 D(d), Loc(l), IsByRef(ByRef), ConstQualAdded(constAdded) 3582 { 3583 bool TypeDependent = false; 3584 bool ValueDependent = false; 3585 bool InstantiationDependent = false; 3586 computeDeclRefDependence(D, getType(), TypeDependent, ValueDependent, 3587 InstantiationDependent); 3588 ExprBits.TypeDependent = TypeDependent; 3589 ExprBits.ValueDependent = ValueDependent; 3590 ExprBits.InstantiationDependent = InstantiationDependent; 3591 } 3592 3593 3594 AtomicExpr::AtomicExpr(SourceLocation BLoc, Expr **args, unsigned nexpr, 3595 QualType t, AtomicOp op, SourceLocation RP) 3596 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary, 3597 false, false, false, false), 3598 NumSubExprs(nexpr), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) 3599 { 3600 for (unsigned i = 0; i < nexpr; i++) { 3601 if (args[i]->isTypeDependent()) 3602 ExprBits.TypeDependent = true; 3603 if (args[i]->isValueDependent()) 3604 ExprBits.ValueDependent = true; 3605 if (args[i]->isInstantiationDependent()) 3606 ExprBits.InstantiationDependent = true; 3607 if (args[i]->containsUnexpandedParameterPack()) 3608 ExprBits.ContainsUnexpandedParameterPack = true; 3609 3610 SubExprs[i] = args[i]; 3611 } 3612 } 3613