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