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