1 //===- Stmt.cpp - Statement 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 Stmt class and statement subclasses. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/Stmt.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTDiagnostic.h" 16 #include "clang/AST/Decl.h" 17 #include "clang/AST/DeclGroup.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/ExprOpenMP.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/AST/StmtObjC.h" 24 #include "clang/AST/StmtOpenMP.h" 25 #include "clang/AST/Type.h" 26 #include "clang/Basic/CharInfo.h" 27 #include "clang/Basic/LLVM.h" 28 #include "clang/Basic/SourceLocation.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/Token.h" 31 #include "llvm/ADT/SmallVector.h" 32 #include "llvm/ADT/StringExtras.h" 33 #include "llvm/ADT/StringRef.h" 34 #include "llvm/Support/Casting.h" 35 #include "llvm/Support/Compiler.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/MathExtras.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include <algorithm> 40 #include <cassert> 41 #include <cstring> 42 #include <string> 43 #include <utility> 44 45 using namespace clang; 46 47 static struct StmtClassNameTable { 48 const char *Name; 49 unsigned Counter; 50 unsigned Size; 51 } StmtClassInfo[Stmt::lastStmtConstant+1]; 52 53 static StmtClassNameTable &getStmtInfoTableEntry(Stmt::StmtClass E) { 54 static bool Initialized = false; 55 if (Initialized) 56 return StmtClassInfo[E]; 57 58 // Initialize the table on the first use. 59 Initialized = true; 60 #define ABSTRACT_STMT(STMT) 61 #define STMT(CLASS, PARENT) \ 62 StmtClassInfo[(unsigned)Stmt::CLASS##Class].Name = #CLASS; \ 63 StmtClassInfo[(unsigned)Stmt::CLASS##Class].Size = sizeof(CLASS); 64 #include "clang/AST/StmtNodes.inc" 65 66 return StmtClassInfo[E]; 67 } 68 69 void *Stmt::operator new(size_t bytes, const ASTContext& C, 70 unsigned alignment) { 71 return ::operator new(bytes, C, alignment); 72 } 73 74 const char *Stmt::getStmtClassName() const { 75 return getStmtInfoTableEntry((StmtClass) StmtBits.sClass).Name; 76 } 77 78 // Check that no statement / expression class is polymorphic. LLVM style RTTI 79 // should be used instead. If absolutely needed an exception can still be added 80 // here by defining the appropriate macro (but please don't do this). 81 #define STMT(CLASS, PARENT) \ 82 static_assert(!std::is_polymorphic<CLASS>::value, \ 83 #CLASS " should not be polymorphic!"); 84 #include "clang/AST/StmtNodes.inc" 85 86 void Stmt::PrintStats() { 87 // Ensure the table is primed. 88 getStmtInfoTableEntry(Stmt::NullStmtClass); 89 90 unsigned sum = 0; 91 llvm::errs() << "\n*** Stmt/Expr Stats:\n"; 92 for (int i = 0; i != Stmt::lastStmtConstant+1; i++) { 93 if (StmtClassInfo[i].Name == nullptr) continue; 94 sum += StmtClassInfo[i].Counter; 95 } 96 llvm::errs() << " " << sum << " stmts/exprs total.\n"; 97 sum = 0; 98 for (int i = 0; i != Stmt::lastStmtConstant+1; i++) { 99 if (StmtClassInfo[i].Name == nullptr) continue; 100 if (StmtClassInfo[i].Counter == 0) continue; 101 llvm::errs() << " " << StmtClassInfo[i].Counter << " " 102 << StmtClassInfo[i].Name << ", " << StmtClassInfo[i].Size 103 << " each (" << StmtClassInfo[i].Counter*StmtClassInfo[i].Size 104 << " bytes)\n"; 105 sum += StmtClassInfo[i].Counter*StmtClassInfo[i].Size; 106 } 107 108 llvm::errs() << "Total bytes = " << sum << "\n"; 109 } 110 111 void Stmt::addStmtClass(StmtClass s) { 112 ++getStmtInfoTableEntry(s).Counter; 113 } 114 115 bool Stmt::StatisticsEnabled = false; 116 void Stmt::EnableStatistics() { 117 StatisticsEnabled = true; 118 } 119 120 /// Skip no-op (attributed, compound) container stmts and skip captured 121 /// stmt at the top, if \a IgnoreCaptured is true. 122 Stmt *Stmt::IgnoreContainers(bool IgnoreCaptured) { 123 Stmt *S = this; 124 if (IgnoreCaptured) 125 if (auto CapS = dyn_cast_or_null<CapturedStmt>(S)) 126 S = CapS->getCapturedStmt(); 127 while (true) { 128 if (auto AS = dyn_cast_or_null<AttributedStmt>(S)) 129 S = AS->getSubStmt(); 130 else if (auto CS = dyn_cast_or_null<CompoundStmt>(S)) { 131 if (CS->size() != 1) 132 break; 133 S = CS->body_back(); 134 } else 135 break; 136 } 137 return S; 138 } 139 140 /// Strip off all label-like statements. 141 /// 142 /// This will strip off label statements, case statements, attributed 143 /// statements and default statements recursively. 144 const Stmt *Stmt::stripLabelLikeStatements() const { 145 const Stmt *S = this; 146 while (true) { 147 if (const auto *LS = dyn_cast<LabelStmt>(S)) 148 S = LS->getSubStmt(); 149 else if (const auto *SC = dyn_cast<SwitchCase>(S)) 150 S = SC->getSubStmt(); 151 else if (const auto *AS = dyn_cast<AttributedStmt>(S)) 152 S = AS->getSubStmt(); 153 else 154 return S; 155 } 156 } 157 158 namespace { 159 160 struct good {}; 161 struct bad {}; 162 163 // These silly little functions have to be static inline to suppress 164 // unused warnings, and they have to be defined to suppress other 165 // warnings. 166 static good is_good(good) { return good(); } 167 168 typedef Stmt::child_range children_t(); 169 template <class T> good implements_children(children_t T::*) { 170 return good(); 171 } 172 LLVM_ATTRIBUTE_UNUSED 173 static bad implements_children(children_t Stmt::*) { 174 return bad(); 175 } 176 177 typedef SourceLocation getBeginLoc_t() const; 178 template <class T> good implements_getBeginLoc(getBeginLoc_t T::*) { 179 return good(); 180 } 181 LLVM_ATTRIBUTE_UNUSED 182 static bad implements_getBeginLoc(getBeginLoc_t Stmt::*) { return bad(); } 183 184 typedef SourceLocation getLocEnd_t() const; 185 template <class T> good implements_getEndLoc(getLocEnd_t T::*) { 186 return good(); 187 } 188 LLVM_ATTRIBUTE_UNUSED 189 static bad implements_getEndLoc(getLocEnd_t Stmt::*) { return bad(); } 190 191 #define ASSERT_IMPLEMENTS_children(type) \ 192 (void) is_good(implements_children(&type::children)) 193 #define ASSERT_IMPLEMENTS_getBeginLoc(type) \ 194 (void)is_good(implements_getBeginLoc(&type::getBeginLoc)) 195 #define ASSERT_IMPLEMENTS_getEndLoc(type) \ 196 (void)is_good(implements_getEndLoc(&type::getEndLoc)) 197 198 } // namespace 199 200 /// Check whether the various Stmt classes implement their member 201 /// functions. 202 LLVM_ATTRIBUTE_UNUSED 203 static inline void check_implementations() { 204 #define ABSTRACT_STMT(type) 205 #define STMT(type, base) \ 206 ASSERT_IMPLEMENTS_children(type); \ 207 ASSERT_IMPLEMENTS_getBeginLoc(type); \ 208 ASSERT_IMPLEMENTS_getEndLoc(type); 209 #include "clang/AST/StmtNodes.inc" 210 } 211 212 Stmt::child_range Stmt::children() { 213 switch (getStmtClass()) { 214 case Stmt::NoStmtClass: llvm_unreachable("statement without class"); 215 #define ABSTRACT_STMT(type) 216 #define STMT(type, base) \ 217 case Stmt::type##Class: \ 218 return static_cast<type*>(this)->children(); 219 #include "clang/AST/StmtNodes.inc" 220 } 221 llvm_unreachable("unknown statement kind!"); 222 } 223 224 // Amusing macro metaprogramming hack: check whether a class provides 225 // a more specific implementation of getSourceRange. 226 // 227 // See also Expr.cpp:getExprLoc(). 228 namespace { 229 230 /// This implementation is used when a class provides a custom 231 /// implementation of getSourceRange. 232 template <class S, class T> 233 SourceRange getSourceRangeImpl(const Stmt *stmt, 234 SourceRange (T::*v)() const) { 235 return static_cast<const S*>(stmt)->getSourceRange(); 236 } 237 238 /// This implementation is used when a class doesn't provide a custom 239 /// implementation of getSourceRange. Overload resolution should pick it over 240 /// the implementation above because it's more specialized according to 241 /// function template partial ordering. 242 template <class S> 243 SourceRange getSourceRangeImpl(const Stmt *stmt, 244 SourceRange (Stmt::*v)() const) { 245 return SourceRange(static_cast<const S *>(stmt)->getBeginLoc(), 246 static_cast<const S *>(stmt)->getEndLoc()); 247 } 248 249 } // namespace 250 251 SourceRange Stmt::getSourceRange() const { 252 switch (getStmtClass()) { 253 case Stmt::NoStmtClass: llvm_unreachable("statement without class"); 254 #define ABSTRACT_STMT(type) 255 #define STMT(type, base) \ 256 case Stmt::type##Class: \ 257 return getSourceRangeImpl<type>(this, &type::getSourceRange); 258 #include "clang/AST/StmtNodes.inc" 259 } 260 llvm_unreachable("unknown statement kind!"); 261 } 262 263 SourceLocation Stmt::getBeginLoc() const { 264 // llvm::errs() << "getBeginLoc() for " << getStmtClassName() << "\n"; 265 switch (getStmtClass()) { 266 case Stmt::NoStmtClass: llvm_unreachable("statement without class"); 267 #define ABSTRACT_STMT(type) 268 #define STMT(type, base) \ 269 case Stmt::type##Class: \ 270 return static_cast<const type *>(this)->getBeginLoc(); 271 #include "clang/AST/StmtNodes.inc" 272 } 273 llvm_unreachable("unknown statement kind"); 274 } 275 276 SourceLocation Stmt::getEndLoc() const { 277 switch (getStmtClass()) { 278 case Stmt::NoStmtClass: llvm_unreachable("statement without class"); 279 #define ABSTRACT_STMT(type) 280 #define STMT(type, base) \ 281 case Stmt::type##Class: \ 282 return static_cast<const type *>(this)->getEndLoc(); 283 #include "clang/AST/StmtNodes.inc" 284 } 285 llvm_unreachable("unknown statement kind"); 286 } 287 288 int64_t Stmt::getID(const ASTContext &Context) const { 289 return Context.getAllocator().identifyKnownAlignedObject<Stmt>(this); 290 } 291 292 CompoundStmt::CompoundStmt(ArrayRef<Stmt *> Stmts, SourceLocation LB, 293 SourceLocation RB) 294 : Stmt(CompoundStmtClass), RBraceLoc(RB) { 295 CompoundStmtBits.NumStmts = Stmts.size(); 296 setStmts(Stmts); 297 CompoundStmtBits.LBraceLoc = LB; 298 } 299 300 void CompoundStmt::setStmts(ArrayRef<Stmt *> Stmts) { 301 assert(CompoundStmtBits.NumStmts == Stmts.size() && 302 "NumStmts doesn't fit in bits of CompoundStmtBits.NumStmts!"); 303 304 std::copy(Stmts.begin(), Stmts.end(), body_begin()); 305 } 306 307 CompoundStmt *CompoundStmt::Create(const ASTContext &C, ArrayRef<Stmt *> Stmts, 308 SourceLocation LB, SourceLocation RB) { 309 void *Mem = 310 C.Allocate(totalSizeToAlloc<Stmt *>(Stmts.size()), alignof(CompoundStmt)); 311 return new (Mem) CompoundStmt(Stmts, LB, RB); 312 } 313 314 CompoundStmt *CompoundStmt::CreateEmpty(const ASTContext &C, 315 unsigned NumStmts) { 316 void *Mem = 317 C.Allocate(totalSizeToAlloc<Stmt *>(NumStmts), alignof(CompoundStmt)); 318 CompoundStmt *New = new (Mem) CompoundStmt(EmptyShell()); 319 New->CompoundStmtBits.NumStmts = NumStmts; 320 return New; 321 } 322 323 const char *LabelStmt::getName() const { 324 return getDecl()->getIdentifier()->getNameStart(); 325 } 326 327 AttributedStmt *AttributedStmt::Create(const ASTContext &C, SourceLocation Loc, 328 ArrayRef<const Attr*> Attrs, 329 Stmt *SubStmt) { 330 assert(!Attrs.empty() && "Attrs should not be empty"); 331 void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(Attrs.size()), 332 alignof(AttributedStmt)); 333 return new (Mem) AttributedStmt(Loc, Attrs, SubStmt); 334 } 335 336 AttributedStmt *AttributedStmt::CreateEmpty(const ASTContext &C, 337 unsigned NumAttrs) { 338 assert(NumAttrs > 0 && "NumAttrs should be greater than zero"); 339 void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(NumAttrs), 340 alignof(AttributedStmt)); 341 return new (Mem) AttributedStmt(EmptyShell(), NumAttrs); 342 } 343 344 std::string AsmStmt::generateAsmString(const ASTContext &C) const { 345 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this)) 346 return gccAsmStmt->generateAsmString(C); 347 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this)) 348 return msAsmStmt->generateAsmString(C); 349 llvm_unreachable("unknown asm statement kind!"); 350 } 351 352 StringRef AsmStmt::getOutputConstraint(unsigned i) const { 353 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this)) 354 return gccAsmStmt->getOutputConstraint(i); 355 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this)) 356 return msAsmStmt->getOutputConstraint(i); 357 llvm_unreachable("unknown asm statement kind!"); 358 } 359 360 const Expr *AsmStmt::getOutputExpr(unsigned i) const { 361 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this)) 362 return gccAsmStmt->getOutputExpr(i); 363 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this)) 364 return msAsmStmt->getOutputExpr(i); 365 llvm_unreachable("unknown asm statement kind!"); 366 } 367 368 StringRef AsmStmt::getInputConstraint(unsigned i) const { 369 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this)) 370 return gccAsmStmt->getInputConstraint(i); 371 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this)) 372 return msAsmStmt->getInputConstraint(i); 373 llvm_unreachable("unknown asm statement kind!"); 374 } 375 376 const Expr *AsmStmt::getInputExpr(unsigned i) const { 377 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this)) 378 return gccAsmStmt->getInputExpr(i); 379 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this)) 380 return msAsmStmt->getInputExpr(i); 381 llvm_unreachable("unknown asm statement kind!"); 382 } 383 384 StringRef AsmStmt::getClobber(unsigned i) const { 385 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this)) 386 return gccAsmStmt->getClobber(i); 387 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this)) 388 return msAsmStmt->getClobber(i); 389 llvm_unreachable("unknown asm statement kind!"); 390 } 391 392 /// getNumPlusOperands - Return the number of output operands that have a "+" 393 /// constraint. 394 unsigned AsmStmt::getNumPlusOperands() const { 395 unsigned Res = 0; 396 for (unsigned i = 0, e = getNumOutputs(); i != e; ++i) 397 if (isOutputPlusConstraint(i)) 398 ++Res; 399 return Res; 400 } 401 402 char GCCAsmStmt::AsmStringPiece::getModifier() const { 403 assert(isOperand() && "Only Operands can have modifiers."); 404 return isLetter(Str[0]) ? Str[0] : '\0'; 405 } 406 407 StringRef GCCAsmStmt::getClobber(unsigned i) const { 408 return getClobberStringLiteral(i)->getString(); 409 } 410 411 Expr *GCCAsmStmt::getOutputExpr(unsigned i) { 412 return cast<Expr>(Exprs[i]); 413 } 414 415 /// getOutputConstraint - Return the constraint string for the specified 416 /// output operand. All output constraints are known to be non-empty (either 417 /// '=' or '+'). 418 StringRef GCCAsmStmt::getOutputConstraint(unsigned i) const { 419 return getOutputConstraintLiteral(i)->getString(); 420 } 421 422 Expr *GCCAsmStmt::getInputExpr(unsigned i) { 423 return cast<Expr>(Exprs[i + NumOutputs]); 424 } 425 426 void GCCAsmStmt::setInputExpr(unsigned i, Expr *E) { 427 Exprs[i + NumOutputs] = E; 428 } 429 430 /// getInputConstraint - Return the specified input constraint. Unlike output 431 /// constraints, these can be empty. 432 StringRef GCCAsmStmt::getInputConstraint(unsigned i) const { 433 return getInputConstraintLiteral(i)->getString(); 434 } 435 436 void GCCAsmStmt::setOutputsAndInputsAndClobbers(const ASTContext &C, 437 IdentifierInfo **Names, 438 StringLiteral **Constraints, 439 Stmt **Exprs, 440 unsigned NumOutputs, 441 unsigned NumInputs, 442 StringLiteral **Clobbers, 443 unsigned NumClobbers) { 444 this->NumOutputs = NumOutputs; 445 this->NumInputs = NumInputs; 446 this->NumClobbers = NumClobbers; 447 448 unsigned NumExprs = NumOutputs + NumInputs; 449 450 C.Deallocate(this->Names); 451 this->Names = new (C) IdentifierInfo*[NumExprs]; 452 std::copy(Names, Names + NumExprs, this->Names); 453 454 C.Deallocate(this->Exprs); 455 this->Exprs = new (C) Stmt*[NumExprs]; 456 std::copy(Exprs, Exprs + NumExprs, this->Exprs); 457 458 C.Deallocate(this->Constraints); 459 this->Constraints = new (C) StringLiteral*[NumExprs]; 460 std::copy(Constraints, Constraints + NumExprs, this->Constraints); 461 462 C.Deallocate(this->Clobbers); 463 this->Clobbers = new (C) StringLiteral*[NumClobbers]; 464 std::copy(Clobbers, Clobbers + NumClobbers, this->Clobbers); 465 } 466 467 /// getNamedOperand - Given a symbolic operand reference like %[foo], 468 /// translate this into a numeric value needed to reference the same operand. 469 /// This returns -1 if the operand name is invalid. 470 int GCCAsmStmt::getNamedOperand(StringRef SymbolicName) const { 471 unsigned NumPlusOperands = 0; 472 473 // Check if this is an output operand. 474 for (unsigned i = 0, e = getNumOutputs(); i != e; ++i) { 475 if (getOutputName(i) == SymbolicName) 476 return i; 477 } 478 479 for (unsigned i = 0, e = getNumInputs(); i != e; ++i) 480 if (getInputName(i) == SymbolicName) 481 return getNumOutputs() + NumPlusOperands + i; 482 483 // Not found. 484 return -1; 485 } 486 487 /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing 488 /// it into pieces. If the asm string is erroneous, emit errors and return 489 /// true, otherwise return false. 490 unsigned GCCAsmStmt::AnalyzeAsmString(SmallVectorImpl<AsmStringPiece>&Pieces, 491 const ASTContext &C, unsigned &DiagOffs) const { 492 StringRef Str = getAsmString()->getString(); 493 const char *StrStart = Str.begin(); 494 const char *StrEnd = Str.end(); 495 const char *CurPtr = StrStart; 496 497 // "Simple" inline asms have no constraints or operands, just convert the asm 498 // string to escape $'s. 499 if (isSimple()) { 500 std::string Result; 501 for (; CurPtr != StrEnd; ++CurPtr) { 502 switch (*CurPtr) { 503 case '$': 504 Result += "$$"; 505 break; 506 default: 507 Result += *CurPtr; 508 break; 509 } 510 } 511 Pieces.push_back(AsmStringPiece(Result)); 512 return 0; 513 } 514 515 // CurStringPiece - The current string that we are building up as we scan the 516 // asm string. 517 std::string CurStringPiece; 518 519 bool HasVariants = !C.getTargetInfo().hasNoAsmVariants(); 520 521 unsigned LastAsmStringToken = 0; 522 unsigned LastAsmStringOffset = 0; 523 524 while (true) { 525 // Done with the string? 526 if (CurPtr == StrEnd) { 527 if (!CurStringPiece.empty()) 528 Pieces.push_back(AsmStringPiece(CurStringPiece)); 529 return 0; 530 } 531 532 char CurChar = *CurPtr++; 533 switch (CurChar) { 534 case '$': CurStringPiece += "$$"; continue; 535 case '{': CurStringPiece += (HasVariants ? "$(" : "{"); continue; 536 case '|': CurStringPiece += (HasVariants ? "$|" : "|"); continue; 537 case '}': CurStringPiece += (HasVariants ? "$)" : "}"); continue; 538 case '%': 539 break; 540 default: 541 CurStringPiece += CurChar; 542 continue; 543 } 544 545 // Escaped "%" character in asm string. 546 if (CurPtr == StrEnd) { 547 // % at end of string is invalid (no escape). 548 DiagOffs = CurPtr-StrStart-1; 549 return diag::err_asm_invalid_escape; 550 } 551 // Handle escaped char and continue looping over the asm string. 552 char EscapedChar = *CurPtr++; 553 switch (EscapedChar) { 554 default: 555 break; 556 case '%': // %% -> % 557 case '{': // %{ -> { 558 case '}': // %} -> } 559 CurStringPiece += EscapedChar; 560 continue; 561 case '=': // %= -> Generate a unique ID. 562 CurStringPiece += "${:uid}"; 563 continue; 564 } 565 566 // Otherwise, we have an operand. If we have accumulated a string so far, 567 // add it to the Pieces list. 568 if (!CurStringPiece.empty()) { 569 Pieces.push_back(AsmStringPiece(CurStringPiece)); 570 CurStringPiece.clear(); 571 } 572 573 // Handle operands that have asmSymbolicName (e.g., %x[foo]) and those that 574 // don't (e.g., %x4). 'x' following the '%' is the constraint modifier. 575 576 const char *Begin = CurPtr - 1; // Points to the character following '%'. 577 const char *Percent = Begin - 1; // Points to '%'. 578 579 if (isLetter(EscapedChar)) { 580 if (CurPtr == StrEnd) { // Premature end. 581 DiagOffs = CurPtr-StrStart-1; 582 return diag::err_asm_invalid_escape; 583 } 584 EscapedChar = *CurPtr++; 585 } 586 587 const TargetInfo &TI = C.getTargetInfo(); 588 const SourceManager &SM = C.getSourceManager(); 589 const LangOptions &LO = C.getLangOpts(); 590 591 // Handle operands that don't have asmSymbolicName (e.g., %x4). 592 if (isDigit(EscapedChar)) { 593 // %n - Assembler operand n 594 unsigned N = 0; 595 596 --CurPtr; 597 while (CurPtr != StrEnd && isDigit(*CurPtr)) 598 N = N*10 + ((*CurPtr++)-'0'); 599 600 unsigned NumOperands = 601 getNumOutputs() + getNumPlusOperands() + getNumInputs(); 602 if (N >= NumOperands) { 603 DiagOffs = CurPtr-StrStart-1; 604 return diag::err_asm_invalid_operand_number; 605 } 606 607 // Str contains "x4" (Operand without the leading %). 608 std::string Str(Begin, CurPtr - Begin); 609 610 // (BeginLoc, EndLoc) represents the range of the operand we are currently 611 // processing. Unlike Str, the range includes the leading '%'. 612 SourceLocation BeginLoc = getAsmString()->getLocationOfByte( 613 Percent - StrStart, SM, LO, TI, &LastAsmStringToken, 614 &LastAsmStringOffset); 615 SourceLocation EndLoc = getAsmString()->getLocationOfByte( 616 CurPtr - StrStart, SM, LO, TI, &LastAsmStringToken, 617 &LastAsmStringOffset); 618 619 Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc); 620 continue; 621 } 622 623 // Handle operands that have asmSymbolicName (e.g., %x[foo]). 624 if (EscapedChar == '[') { 625 DiagOffs = CurPtr-StrStart-1; 626 627 // Find the ']'. 628 const char *NameEnd = (const char*)memchr(CurPtr, ']', StrEnd-CurPtr); 629 if (NameEnd == nullptr) 630 return diag::err_asm_unterminated_symbolic_operand_name; 631 if (NameEnd == CurPtr) 632 return diag::err_asm_empty_symbolic_operand_name; 633 634 StringRef SymbolicName(CurPtr, NameEnd - CurPtr); 635 636 int N = getNamedOperand(SymbolicName); 637 if (N == -1) { 638 // Verify that an operand with that name exists. 639 DiagOffs = CurPtr-StrStart; 640 return diag::err_asm_unknown_symbolic_operand_name; 641 } 642 643 // Str contains "x[foo]" (Operand without the leading %). 644 std::string Str(Begin, NameEnd + 1 - Begin); 645 646 // (BeginLoc, EndLoc) represents the range of the operand we are currently 647 // processing. Unlike Str, the range includes the leading '%'. 648 SourceLocation BeginLoc = getAsmString()->getLocationOfByte( 649 Percent - StrStart, SM, LO, TI, &LastAsmStringToken, 650 &LastAsmStringOffset); 651 SourceLocation EndLoc = getAsmString()->getLocationOfByte( 652 NameEnd + 1 - StrStart, SM, LO, TI, &LastAsmStringToken, 653 &LastAsmStringOffset); 654 655 Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc); 656 657 CurPtr = NameEnd+1; 658 continue; 659 } 660 661 DiagOffs = CurPtr-StrStart-1; 662 return diag::err_asm_invalid_escape; 663 } 664 } 665 666 /// Assemble final IR asm string (GCC-style). 667 std::string GCCAsmStmt::generateAsmString(const ASTContext &C) const { 668 // Analyze the asm string to decompose it into its pieces. We know that Sema 669 // has already done this, so it is guaranteed to be successful. 670 SmallVector<GCCAsmStmt::AsmStringPiece, 4> Pieces; 671 unsigned DiagOffs; 672 AnalyzeAsmString(Pieces, C, DiagOffs); 673 674 std::string AsmString; 675 for (const auto &Piece : Pieces) { 676 if (Piece.isString()) 677 AsmString += Piece.getString(); 678 else if (Piece.getModifier() == '\0') 679 AsmString += '$' + llvm::utostr(Piece.getOperandNo()); 680 else 681 AsmString += "${" + llvm::utostr(Piece.getOperandNo()) + ':' + 682 Piece.getModifier() + '}'; 683 } 684 return AsmString; 685 } 686 687 /// Assemble final IR asm string (MS-style). 688 std::string MSAsmStmt::generateAsmString(const ASTContext &C) const { 689 // FIXME: This needs to be translated into the IR string representation. 690 return AsmStr; 691 } 692 693 Expr *MSAsmStmt::getOutputExpr(unsigned i) { 694 return cast<Expr>(Exprs[i]); 695 } 696 697 Expr *MSAsmStmt::getInputExpr(unsigned i) { 698 return cast<Expr>(Exprs[i + NumOutputs]); 699 } 700 701 void MSAsmStmt::setInputExpr(unsigned i, Expr *E) { 702 Exprs[i + NumOutputs] = E; 703 } 704 705 //===----------------------------------------------------------------------===// 706 // Constructors 707 //===----------------------------------------------------------------------===// 708 709 GCCAsmStmt::GCCAsmStmt(const ASTContext &C, SourceLocation asmloc, 710 bool issimple, bool isvolatile, unsigned numoutputs, 711 unsigned numinputs, IdentifierInfo **names, 712 StringLiteral **constraints, Expr **exprs, 713 StringLiteral *asmstr, unsigned numclobbers, 714 StringLiteral **clobbers, SourceLocation rparenloc) 715 : AsmStmt(GCCAsmStmtClass, asmloc, issimple, isvolatile, numoutputs, 716 numinputs, numclobbers), RParenLoc(rparenloc), AsmStr(asmstr) { 717 unsigned NumExprs = NumOutputs + NumInputs; 718 719 Names = new (C) IdentifierInfo*[NumExprs]; 720 std::copy(names, names + NumExprs, Names); 721 722 Exprs = new (C) Stmt*[NumExprs]; 723 std::copy(exprs, exprs + NumExprs, Exprs); 724 725 Constraints = new (C) StringLiteral*[NumExprs]; 726 std::copy(constraints, constraints + NumExprs, Constraints); 727 728 Clobbers = new (C) StringLiteral*[NumClobbers]; 729 std::copy(clobbers, clobbers + NumClobbers, Clobbers); 730 } 731 732 MSAsmStmt::MSAsmStmt(const ASTContext &C, SourceLocation asmloc, 733 SourceLocation lbraceloc, bool issimple, bool isvolatile, 734 ArrayRef<Token> asmtoks, unsigned numoutputs, 735 unsigned numinputs, 736 ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs, 737 StringRef asmstr, ArrayRef<StringRef> clobbers, 738 SourceLocation endloc) 739 : AsmStmt(MSAsmStmtClass, asmloc, issimple, isvolatile, numoutputs, 740 numinputs, clobbers.size()), LBraceLoc(lbraceloc), 741 EndLoc(endloc), NumAsmToks(asmtoks.size()) { 742 initialize(C, asmstr, asmtoks, constraints, exprs, clobbers); 743 } 744 745 static StringRef copyIntoContext(const ASTContext &C, StringRef str) { 746 return str.copy(C); 747 } 748 749 void MSAsmStmt::initialize(const ASTContext &C, StringRef asmstr, 750 ArrayRef<Token> asmtoks, 751 ArrayRef<StringRef> constraints, 752 ArrayRef<Expr*> exprs, 753 ArrayRef<StringRef> clobbers) { 754 assert(NumAsmToks == asmtoks.size()); 755 assert(NumClobbers == clobbers.size()); 756 757 assert(exprs.size() == NumOutputs + NumInputs); 758 assert(exprs.size() == constraints.size()); 759 760 AsmStr = copyIntoContext(C, asmstr); 761 762 Exprs = new (C) Stmt*[exprs.size()]; 763 std::copy(exprs.begin(), exprs.end(), Exprs); 764 765 AsmToks = new (C) Token[asmtoks.size()]; 766 std::copy(asmtoks.begin(), asmtoks.end(), AsmToks); 767 768 Constraints = new (C) StringRef[exprs.size()]; 769 std::transform(constraints.begin(), constraints.end(), Constraints, 770 [&](StringRef Constraint) { 771 return copyIntoContext(C, Constraint); 772 }); 773 774 Clobbers = new (C) StringRef[NumClobbers]; 775 // FIXME: Avoid the allocation/copy if at all possible. 776 std::transform(clobbers.begin(), clobbers.end(), Clobbers, 777 [&](StringRef Clobber) { 778 return copyIntoContext(C, Clobber); 779 }); 780 } 781 782 IfStmt::IfStmt(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr, 783 Stmt *Init, VarDecl *Var, Expr *Cond, Stmt *Then, 784 SourceLocation EL, Stmt *Else) 785 : Stmt(IfStmtClass) { 786 bool HasElse = Else != nullptr; 787 bool HasVar = Var != nullptr; 788 bool HasInit = Init != nullptr; 789 IfStmtBits.HasElse = HasElse; 790 IfStmtBits.HasVar = HasVar; 791 IfStmtBits.HasInit = HasInit; 792 793 setConstexpr(IsConstexpr); 794 795 setCond(Cond); 796 setThen(Then); 797 if (HasElse) 798 setElse(Else); 799 if (HasVar) 800 setConditionVariable(Ctx, Var); 801 if (HasInit) 802 setInit(Init); 803 804 setIfLoc(IL); 805 if (HasElse) 806 setElseLoc(EL); 807 } 808 809 IfStmt::IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit) 810 : Stmt(IfStmtClass, Empty) { 811 IfStmtBits.HasElse = HasElse; 812 IfStmtBits.HasVar = HasVar; 813 IfStmtBits.HasInit = HasInit; 814 } 815 816 IfStmt *IfStmt::Create(const ASTContext &Ctx, SourceLocation IL, 817 bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond, 818 Stmt *Then, SourceLocation EL, Stmt *Else) { 819 bool HasElse = Else != nullptr; 820 bool HasVar = Var != nullptr; 821 bool HasInit = Init != nullptr; 822 void *Mem = Ctx.Allocate( 823 totalSizeToAlloc<Stmt *, SourceLocation>( 824 NumMandatoryStmtPtr + HasElse + HasVar + HasInit, HasElse), 825 alignof(IfStmt)); 826 return new (Mem) 827 IfStmt(Ctx, IL, IsConstexpr, Init, Var, Cond, Then, EL, Else); 828 } 829 830 IfStmt *IfStmt::CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar, 831 bool HasInit) { 832 void *Mem = Ctx.Allocate( 833 totalSizeToAlloc<Stmt *, SourceLocation>( 834 NumMandatoryStmtPtr + HasElse + HasVar + HasInit, HasElse), 835 alignof(IfStmt)); 836 return new (Mem) IfStmt(EmptyShell(), HasElse, HasVar, HasInit); 837 } 838 839 VarDecl *IfStmt::getConditionVariable() { 840 auto *DS = getConditionVariableDeclStmt(); 841 if (!DS) 842 return nullptr; 843 return cast<VarDecl>(DS->getSingleDecl()); 844 } 845 846 void IfStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) { 847 assert(hasVarStorage() && 848 "This if statement has no storage for a condition variable!"); 849 850 if (!V) { 851 getTrailingObjects<Stmt *>()[varOffset()] = nullptr; 852 return; 853 } 854 855 SourceRange VarRange = V->getSourceRange(); 856 getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx) 857 DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd()); 858 } 859 860 bool IfStmt::isObjCAvailabilityCheck() const { 861 return isa<ObjCAvailabilityCheckExpr>(getCond()); 862 } 863 864 ForStmt::ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar, 865 Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP, 866 SourceLocation RP) 867 : Stmt(ForStmtClass), LParenLoc(LP), RParenLoc(RP) 868 { 869 SubExprs[INIT] = Init; 870 setConditionVariable(C, condVar); 871 SubExprs[COND] = Cond; 872 SubExprs[INC] = Inc; 873 SubExprs[BODY] = Body; 874 ForStmtBits.ForLoc = FL; 875 } 876 877 VarDecl *ForStmt::getConditionVariable() const { 878 if (!SubExprs[CONDVAR]) 879 return nullptr; 880 881 auto *DS = cast<DeclStmt>(SubExprs[CONDVAR]); 882 return cast<VarDecl>(DS->getSingleDecl()); 883 } 884 885 void ForStmt::setConditionVariable(const ASTContext &C, VarDecl *V) { 886 if (!V) { 887 SubExprs[CONDVAR] = nullptr; 888 return; 889 } 890 891 SourceRange VarRange = V->getSourceRange(); 892 SubExprs[CONDVAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(), 893 VarRange.getEnd()); 894 } 895 896 SwitchStmt::SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, 897 Expr *Cond) 898 : Stmt(SwitchStmtClass), FirstCase(nullptr) { 899 bool HasInit = Init != nullptr; 900 bool HasVar = Var != nullptr; 901 SwitchStmtBits.HasInit = HasInit; 902 SwitchStmtBits.HasVar = HasVar; 903 SwitchStmtBits.AllEnumCasesCovered = false; 904 905 setCond(Cond); 906 setBody(nullptr); 907 if (HasInit) 908 setInit(Init); 909 if (HasVar) 910 setConditionVariable(Ctx, Var); 911 912 setSwitchLoc(SourceLocation{}); 913 } 914 915 SwitchStmt::SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar) 916 : Stmt(SwitchStmtClass, Empty) { 917 SwitchStmtBits.HasInit = HasInit; 918 SwitchStmtBits.HasVar = HasVar; 919 SwitchStmtBits.AllEnumCasesCovered = false; 920 } 921 922 SwitchStmt *SwitchStmt::Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, 923 Expr *Cond) { 924 bool HasInit = Init != nullptr; 925 bool HasVar = Var != nullptr; 926 void *Mem = Ctx.Allocate( 927 totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar), 928 alignof(SwitchStmt)); 929 return new (Mem) SwitchStmt(Ctx, Init, Var, Cond); 930 } 931 932 SwitchStmt *SwitchStmt::CreateEmpty(const ASTContext &Ctx, bool HasInit, 933 bool HasVar) { 934 void *Mem = Ctx.Allocate( 935 totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar), 936 alignof(SwitchStmt)); 937 return new (Mem) SwitchStmt(EmptyShell(), HasInit, HasVar); 938 } 939 940 VarDecl *SwitchStmt::getConditionVariable() { 941 auto *DS = getConditionVariableDeclStmt(); 942 if (!DS) 943 return nullptr; 944 return cast<VarDecl>(DS->getSingleDecl()); 945 } 946 947 void SwitchStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) { 948 assert(hasVarStorage() && 949 "This switch statement has no storage for a condition variable!"); 950 951 if (!V) { 952 getTrailingObjects<Stmt *>()[varOffset()] = nullptr; 953 return; 954 } 955 956 SourceRange VarRange = V->getSourceRange(); 957 getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx) 958 DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd()); 959 } 960 961 WhileStmt::WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, 962 Stmt *Body, SourceLocation WL) 963 : Stmt(WhileStmtClass) { 964 bool HasVar = Var != nullptr; 965 WhileStmtBits.HasVar = HasVar; 966 967 setCond(Cond); 968 setBody(Body); 969 if (HasVar) 970 setConditionVariable(Ctx, Var); 971 972 setWhileLoc(WL); 973 } 974 975 WhileStmt::WhileStmt(EmptyShell Empty, bool HasVar) 976 : Stmt(WhileStmtClass, Empty) { 977 WhileStmtBits.HasVar = HasVar; 978 } 979 980 WhileStmt *WhileStmt::Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, 981 Stmt *Body, SourceLocation WL) { 982 bool HasVar = Var != nullptr; 983 void *Mem = 984 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar), 985 alignof(WhileStmt)); 986 return new (Mem) WhileStmt(Ctx, Var, Cond, Body, WL); 987 } 988 989 WhileStmt *WhileStmt::CreateEmpty(const ASTContext &Ctx, bool HasVar) { 990 void *Mem = 991 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar), 992 alignof(WhileStmt)); 993 return new (Mem) WhileStmt(EmptyShell(), HasVar); 994 } 995 996 VarDecl *WhileStmt::getConditionVariable() { 997 auto *DS = getConditionVariableDeclStmt(); 998 if (!DS) 999 return nullptr; 1000 return cast<VarDecl>(DS->getSingleDecl()); 1001 } 1002 1003 void WhileStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) { 1004 assert(hasVarStorage() && 1005 "This while statement has no storage for a condition variable!"); 1006 1007 if (!V) { 1008 getTrailingObjects<Stmt *>()[varOffset()] = nullptr; 1009 return; 1010 } 1011 1012 SourceRange VarRange = V->getSourceRange(); 1013 getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx) 1014 DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd()); 1015 } 1016 1017 // IndirectGotoStmt 1018 LabelDecl *IndirectGotoStmt::getConstantTarget() { 1019 if (auto *E = dyn_cast<AddrLabelExpr>(getTarget()->IgnoreParenImpCasts())) 1020 return E->getLabel(); 1021 return nullptr; 1022 } 1023 1024 // ReturnStmt 1025 ReturnStmt::ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate) 1026 : Stmt(ReturnStmtClass), RetExpr(E) { 1027 bool HasNRVOCandidate = NRVOCandidate != nullptr; 1028 ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate; 1029 if (HasNRVOCandidate) 1030 setNRVOCandidate(NRVOCandidate); 1031 setReturnLoc(RL); 1032 } 1033 1034 ReturnStmt::ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate) 1035 : Stmt(ReturnStmtClass, Empty) { 1036 ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate; 1037 } 1038 1039 ReturnStmt *ReturnStmt::Create(const ASTContext &Ctx, SourceLocation RL, 1040 Expr *E, const VarDecl *NRVOCandidate) { 1041 bool HasNRVOCandidate = NRVOCandidate != nullptr; 1042 void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate), 1043 alignof(ReturnStmt)); 1044 return new (Mem) ReturnStmt(RL, E, NRVOCandidate); 1045 } 1046 1047 ReturnStmt *ReturnStmt::CreateEmpty(const ASTContext &Ctx, 1048 bool HasNRVOCandidate) { 1049 void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate), 1050 alignof(ReturnStmt)); 1051 return new (Mem) ReturnStmt(EmptyShell(), HasNRVOCandidate); 1052 } 1053 1054 // CaseStmt 1055 CaseStmt *CaseStmt::Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs, 1056 SourceLocation caseLoc, SourceLocation ellipsisLoc, 1057 SourceLocation colonLoc) { 1058 bool CaseStmtIsGNURange = rhs != nullptr; 1059 void *Mem = Ctx.Allocate( 1060 totalSizeToAlloc<Stmt *, SourceLocation>( 1061 NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange), 1062 alignof(CaseStmt)); 1063 return new (Mem) CaseStmt(lhs, rhs, caseLoc, ellipsisLoc, colonLoc); 1064 } 1065 1066 CaseStmt *CaseStmt::CreateEmpty(const ASTContext &Ctx, 1067 bool CaseStmtIsGNURange) { 1068 void *Mem = Ctx.Allocate( 1069 totalSizeToAlloc<Stmt *, SourceLocation>( 1070 NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange), 1071 alignof(CaseStmt)); 1072 return new (Mem) CaseStmt(EmptyShell(), CaseStmtIsGNURange); 1073 } 1074 1075 SEHTryStmt::SEHTryStmt(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock, 1076 Stmt *Handler) 1077 : Stmt(SEHTryStmtClass), IsCXXTry(IsCXXTry), TryLoc(TryLoc) { 1078 Children[TRY] = TryBlock; 1079 Children[HANDLER] = Handler; 1080 } 1081 1082 SEHTryStmt* SEHTryStmt::Create(const ASTContext &C, bool IsCXXTry, 1083 SourceLocation TryLoc, Stmt *TryBlock, 1084 Stmt *Handler) { 1085 return new(C) SEHTryStmt(IsCXXTry,TryLoc,TryBlock,Handler); 1086 } 1087 1088 SEHExceptStmt* SEHTryStmt::getExceptHandler() const { 1089 return dyn_cast<SEHExceptStmt>(getHandler()); 1090 } 1091 1092 SEHFinallyStmt* SEHTryStmt::getFinallyHandler() const { 1093 return dyn_cast<SEHFinallyStmt>(getHandler()); 1094 } 1095 1096 SEHExceptStmt::SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block) 1097 : Stmt(SEHExceptStmtClass), Loc(Loc) { 1098 Children[FILTER_EXPR] = FilterExpr; 1099 Children[BLOCK] = Block; 1100 } 1101 1102 SEHExceptStmt* SEHExceptStmt::Create(const ASTContext &C, SourceLocation Loc, 1103 Expr *FilterExpr, Stmt *Block) { 1104 return new(C) SEHExceptStmt(Loc,FilterExpr,Block); 1105 } 1106 1107 SEHFinallyStmt::SEHFinallyStmt(SourceLocation Loc, Stmt *Block) 1108 : Stmt(SEHFinallyStmtClass), Loc(Loc), Block(Block) {} 1109 1110 SEHFinallyStmt* SEHFinallyStmt::Create(const ASTContext &C, SourceLocation Loc, 1111 Stmt *Block) { 1112 return new(C)SEHFinallyStmt(Loc,Block); 1113 } 1114 1115 CapturedStmt::Capture::Capture(SourceLocation Loc, VariableCaptureKind Kind, 1116 VarDecl *Var) 1117 : VarAndKind(Var, Kind), Loc(Loc) { 1118 switch (Kind) { 1119 case VCK_This: 1120 assert(!Var && "'this' capture cannot have a variable!"); 1121 break; 1122 case VCK_ByRef: 1123 assert(Var && "capturing by reference must have a variable!"); 1124 break; 1125 case VCK_ByCopy: 1126 assert(Var && "capturing by copy must have a variable!"); 1127 assert( 1128 (Var->getType()->isScalarType() || (Var->getType()->isReferenceType() && 1129 Var->getType() 1130 ->castAs<ReferenceType>() 1131 ->getPointeeType() 1132 ->isScalarType())) && 1133 "captures by copy are expected to have a scalar type!"); 1134 break; 1135 case VCK_VLAType: 1136 assert(!Var && 1137 "Variable-length array type capture cannot have a variable!"); 1138 break; 1139 } 1140 } 1141 1142 CapturedStmt::VariableCaptureKind 1143 CapturedStmt::Capture::getCaptureKind() const { 1144 return VarAndKind.getInt(); 1145 } 1146 1147 VarDecl *CapturedStmt::Capture::getCapturedVar() const { 1148 assert((capturesVariable() || capturesVariableByCopy()) && 1149 "No variable available for 'this' or VAT capture"); 1150 return VarAndKind.getPointer(); 1151 } 1152 1153 CapturedStmt::Capture *CapturedStmt::getStoredCaptures() const { 1154 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1); 1155 1156 // Offset of the first Capture object. 1157 unsigned FirstCaptureOffset = llvm::alignTo(Size, alignof(Capture)); 1158 1159 return reinterpret_cast<Capture *>( 1160 reinterpret_cast<char *>(const_cast<CapturedStmt *>(this)) 1161 + FirstCaptureOffset); 1162 } 1163 1164 CapturedStmt::CapturedStmt(Stmt *S, CapturedRegionKind Kind, 1165 ArrayRef<Capture> Captures, 1166 ArrayRef<Expr *> CaptureInits, 1167 CapturedDecl *CD, 1168 RecordDecl *RD) 1169 : Stmt(CapturedStmtClass), NumCaptures(Captures.size()), 1170 CapDeclAndKind(CD, Kind), TheRecordDecl(RD) { 1171 assert( S && "null captured statement"); 1172 assert(CD && "null captured declaration for captured statement"); 1173 assert(RD && "null record declaration for captured statement"); 1174 1175 // Copy initialization expressions. 1176 Stmt **Stored = getStoredStmts(); 1177 for (unsigned I = 0, N = NumCaptures; I != N; ++I) 1178 *Stored++ = CaptureInits[I]; 1179 1180 // Copy the statement being captured. 1181 *Stored = S; 1182 1183 // Copy all Capture objects. 1184 Capture *Buffer = getStoredCaptures(); 1185 std::copy(Captures.begin(), Captures.end(), Buffer); 1186 } 1187 1188 CapturedStmt::CapturedStmt(EmptyShell Empty, unsigned NumCaptures) 1189 : Stmt(CapturedStmtClass, Empty), NumCaptures(NumCaptures), 1190 CapDeclAndKind(nullptr, CR_Default) { 1191 getStoredStmts()[NumCaptures] = nullptr; 1192 } 1193 1194 CapturedStmt *CapturedStmt::Create(const ASTContext &Context, Stmt *S, 1195 CapturedRegionKind Kind, 1196 ArrayRef<Capture> Captures, 1197 ArrayRef<Expr *> CaptureInits, 1198 CapturedDecl *CD, 1199 RecordDecl *RD) { 1200 // The layout is 1201 // 1202 // ----------------------------------------------------------- 1203 // | CapturedStmt, Init, ..., Init, S, Capture, ..., Capture | 1204 // ----------------^-------------------^---------------------- 1205 // getStoredStmts() getStoredCaptures() 1206 // 1207 // where S is the statement being captured. 1208 // 1209 assert(CaptureInits.size() == Captures.size() && "wrong number of arguments"); 1210 1211 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (Captures.size() + 1); 1212 if (!Captures.empty()) { 1213 // Realign for the following Capture array. 1214 Size = llvm::alignTo(Size, alignof(Capture)); 1215 Size += sizeof(Capture) * Captures.size(); 1216 } 1217 1218 void *Mem = Context.Allocate(Size); 1219 return new (Mem) CapturedStmt(S, Kind, Captures, CaptureInits, CD, RD); 1220 } 1221 1222 CapturedStmt *CapturedStmt::CreateDeserialized(const ASTContext &Context, 1223 unsigned NumCaptures) { 1224 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1); 1225 if (NumCaptures > 0) { 1226 // Realign for the following Capture array. 1227 Size = llvm::alignTo(Size, alignof(Capture)); 1228 Size += sizeof(Capture) * NumCaptures; 1229 } 1230 1231 void *Mem = Context.Allocate(Size); 1232 return new (Mem) CapturedStmt(EmptyShell(), NumCaptures); 1233 } 1234 1235 Stmt::child_range CapturedStmt::children() { 1236 // Children are captured field initializers. 1237 return child_range(getStoredStmts(), getStoredStmts() + NumCaptures); 1238 } 1239 1240 CapturedDecl *CapturedStmt::getCapturedDecl() { 1241 return CapDeclAndKind.getPointer(); 1242 } 1243 1244 const CapturedDecl *CapturedStmt::getCapturedDecl() const { 1245 return CapDeclAndKind.getPointer(); 1246 } 1247 1248 /// Set the outlined function declaration. 1249 void CapturedStmt::setCapturedDecl(CapturedDecl *D) { 1250 assert(D && "null CapturedDecl"); 1251 CapDeclAndKind.setPointer(D); 1252 } 1253 1254 /// Retrieve the captured region kind. 1255 CapturedRegionKind CapturedStmt::getCapturedRegionKind() const { 1256 return CapDeclAndKind.getInt(); 1257 } 1258 1259 /// Set the captured region kind. 1260 void CapturedStmt::setCapturedRegionKind(CapturedRegionKind Kind) { 1261 CapDeclAndKind.setInt(Kind); 1262 } 1263 1264 bool CapturedStmt::capturesVariable(const VarDecl *Var) const { 1265 for (const auto &I : captures()) { 1266 if (!I.capturesVariable() && !I.capturesVariableByCopy()) 1267 continue; 1268 if (I.getCapturedVar()->getCanonicalDecl() == Var->getCanonicalDecl()) 1269 return true; 1270 } 1271 1272 return false; 1273 } 1274