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