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