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