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