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