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