1 //===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the main API hooks in the Clang-C Source Indexing 11 // library. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "CIndexDiagnostic.h" 16 #include "CIndexer.h" 17 #include "CLog.h" 18 #include "CXCursor.h" 19 #include "CXSourceLocation.h" 20 #include "CXString.h" 21 #include "CXTranslationUnit.h" 22 #include "CXType.h" 23 #include "CursorVisitor.h" 24 #include "clang/AST/Attr.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/Basic/Diagnostic.h" 27 #include "clang/Basic/DiagnosticCategories.h" 28 #include "clang/Basic/DiagnosticIDs.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Basic/Version.h" 31 #include "clang/Frontend/ASTUnit.h" 32 #include "clang/Frontend/CompilerInstance.h" 33 #include "clang/Frontend/FrontendDiagnostic.h" 34 #include "clang/Index/CodegenNameGenerator.h" 35 #include "clang/Index/CommentToXML.h" 36 #include "clang/Lex/HeaderSearch.h" 37 #include "clang/Lex/Lexer.h" 38 #include "clang/Lex/PreprocessingRecord.h" 39 #include "clang/Lex/Preprocessor.h" 40 #include "clang/Serialization/SerializationDiagnostic.h" 41 #include "llvm/ADT/Optional.h" 42 #include "llvm/ADT/STLExtras.h" 43 #include "llvm/ADT/StringSwitch.h" 44 #include "llvm/Config/llvm-config.h" 45 #include "llvm/Support/Compiler.h" 46 #include "llvm/Support/CrashRecoveryContext.h" 47 #include "llvm/Support/Format.h" 48 #include "llvm/Support/ManagedStatic.h" 49 #include "llvm/Support/MemoryBuffer.h" 50 #include "llvm/Support/Mutex.h" 51 #include "llvm/Support/Program.h" 52 #include "llvm/Support/SaveAndRestore.h" 53 #include "llvm/Support/Signals.h" 54 #include "llvm/Support/TargetSelect.h" 55 #include "llvm/Support/Threading.h" 56 #include "llvm/Support/Timer.h" 57 #include "llvm/Support/raw_ostream.h" 58 59 #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__) 60 #define USE_DARWIN_THREADS 61 #endif 62 63 #ifdef USE_DARWIN_THREADS 64 #include <pthread.h> 65 #endif 66 67 using namespace clang; 68 using namespace clang::cxcursor; 69 using namespace clang::cxtu; 70 using namespace clang::cxindex; 71 72 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, 73 std::unique_ptr<ASTUnit> AU) { 74 if (!AU) 75 return nullptr; 76 assert(CIdx); 77 CXTranslationUnit D = new CXTranslationUnitImpl(); 78 D->CIdx = CIdx; 79 D->TheASTUnit = AU.release(); 80 D->StringPool = new cxstring::CXStringPool(); 81 D->Diagnostics = nullptr; 82 D->OverridenCursorsPool = createOverridenCXCursorsPool(); 83 D->CommentToXML = nullptr; 84 return D; 85 } 86 87 bool cxtu::isASTReadError(ASTUnit *AU) { 88 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(), 89 DEnd = AU->stored_diag_end(); 90 D != DEnd; ++D) { 91 if (D->getLevel() >= DiagnosticsEngine::Error && 92 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) == 93 diag::DiagCat_AST_Deserialization_Issue) 94 return true; 95 } 96 return false; 97 } 98 99 cxtu::CXTUOwner::~CXTUOwner() { 100 if (TU) 101 clang_disposeTranslationUnit(TU); 102 } 103 104 /// \brief Compare two source ranges to determine their relative position in 105 /// the translation unit. 106 static RangeComparisonResult RangeCompare(SourceManager &SM, 107 SourceRange R1, 108 SourceRange R2) { 109 assert(R1.isValid() && "First range is invalid?"); 110 assert(R2.isValid() && "Second range is invalid?"); 111 if (R1.getEnd() != R2.getBegin() && 112 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) 113 return RangeBefore; 114 if (R2.getEnd() != R1.getBegin() && 115 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) 116 return RangeAfter; 117 return RangeOverlap; 118 } 119 120 /// \brief Determine if a source location falls within, before, or after a 121 /// a given source range. 122 static RangeComparisonResult LocationCompare(SourceManager &SM, 123 SourceLocation L, SourceRange R) { 124 assert(R.isValid() && "First range is invalid?"); 125 assert(L.isValid() && "Second range is invalid?"); 126 if (L == R.getBegin() || L == R.getEnd()) 127 return RangeOverlap; 128 if (SM.isBeforeInTranslationUnit(L, R.getBegin())) 129 return RangeBefore; 130 if (SM.isBeforeInTranslationUnit(R.getEnd(), L)) 131 return RangeAfter; 132 return RangeOverlap; 133 } 134 135 /// \brief Translate a Clang source range into a CIndex source range. 136 /// 137 /// Clang internally represents ranges where the end location points to the 138 /// start of the token at the end. However, for external clients it is more 139 /// useful to have a CXSourceRange be a proper half-open interval. This routine 140 /// does the appropriate translation. 141 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, 142 const LangOptions &LangOpts, 143 const CharSourceRange &R) { 144 // We want the last character in this location, so we will adjust the 145 // location accordingly. 146 SourceLocation EndLoc = R.getEnd(); 147 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) 148 EndLoc = SM.getExpansionRange(EndLoc).second; 149 if (R.isTokenRange() && EndLoc.isValid()) { 150 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), 151 SM, LangOpts); 152 EndLoc = EndLoc.getLocWithOffset(Length); 153 } 154 155 CXSourceRange Result = { 156 { &SM, &LangOpts }, 157 R.getBegin().getRawEncoding(), 158 EndLoc.getRawEncoding() 159 }; 160 return Result; 161 } 162 163 //===----------------------------------------------------------------------===// 164 // Cursor visitor. 165 //===----------------------------------------------------------------------===// 166 167 static SourceRange getRawCursorExtent(CXCursor C); 168 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr); 169 170 171 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) { 172 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest); 173 } 174 175 /// \brief Visit the given cursor and, if requested by the visitor, 176 /// its children. 177 /// 178 /// \param Cursor the cursor to visit. 179 /// 180 /// \param CheckedRegionOfInterest if true, then the caller already checked 181 /// that this cursor is within the region of interest. 182 /// 183 /// \returns true if the visitation should be aborted, false if it 184 /// should continue. 185 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) { 186 if (clang_isInvalid(Cursor.kind)) 187 return false; 188 189 if (clang_isDeclaration(Cursor.kind)) { 190 const Decl *D = getCursorDecl(Cursor); 191 if (!D) { 192 assert(0 && "Invalid declaration cursor"); 193 return true; // abort. 194 } 195 196 // Ignore implicit declarations, unless it's an objc method because 197 // currently we should report implicit methods for properties when indexing. 198 if (D->isImplicit() && !isa<ObjCMethodDecl>(D)) 199 return false; 200 } 201 202 // If we have a range of interest, and this cursor doesn't intersect with it, 203 // we're done. 204 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) { 205 SourceRange Range = getRawCursorExtent(Cursor); 206 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 207 return false; 208 } 209 210 switch (Visitor(Cursor, Parent, ClientData)) { 211 case CXChildVisit_Break: 212 return true; 213 214 case CXChildVisit_Continue: 215 return false; 216 217 case CXChildVisit_Recurse: { 218 bool ret = VisitChildren(Cursor); 219 if (PostChildrenVisitor) 220 if (PostChildrenVisitor(Cursor, ClientData)) 221 return true; 222 return ret; 223 } 224 } 225 226 llvm_unreachable("Invalid CXChildVisitResult!"); 227 } 228 229 static bool visitPreprocessedEntitiesInRange(SourceRange R, 230 PreprocessingRecord &PPRec, 231 CursorVisitor &Visitor) { 232 SourceManager &SM = Visitor.getASTUnit()->getSourceManager(); 233 FileID FID; 234 235 if (!Visitor.shouldVisitIncludedEntities()) { 236 // If the begin/end of the range lie in the same FileID, do the optimization 237 // where we skip preprocessed entities that do not come from the same FileID. 238 FID = SM.getFileID(SM.getFileLoc(R.getBegin())); 239 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd()))) 240 FID = FileID(); 241 } 242 243 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R); 244 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(), 245 PPRec, FID); 246 } 247 248 bool CursorVisitor::visitFileRegion() { 249 if (RegionOfInterest.isInvalid()) 250 return false; 251 252 ASTUnit *Unit = cxtu::getASTUnit(TU); 253 SourceManager &SM = Unit->getSourceManager(); 254 255 std::pair<FileID, unsigned> 256 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())), 257 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd())); 258 259 if (End.first != Begin.first) { 260 // If the end does not reside in the same file, try to recover by 261 // picking the end of the file of begin location. 262 End.first = Begin.first; 263 End.second = SM.getFileIDSize(Begin.first); 264 } 265 266 assert(Begin.first == End.first); 267 if (Begin.second > End.second) 268 return false; 269 270 FileID File = Begin.first; 271 unsigned Offset = Begin.second; 272 unsigned Length = End.second - Begin.second; 273 274 if (!VisitDeclsOnly && !VisitPreprocessorLast) 275 if (visitPreprocessedEntitiesInRegion()) 276 return true; // visitation break. 277 278 if (visitDeclsFromFileRegion(File, Offset, Length)) 279 return true; // visitation break. 280 281 if (!VisitDeclsOnly && VisitPreprocessorLast) 282 return visitPreprocessedEntitiesInRegion(); 283 284 return false; 285 } 286 287 static bool isInLexicalContext(Decl *D, DeclContext *DC) { 288 if (!DC) 289 return false; 290 291 for (DeclContext *DeclDC = D->getLexicalDeclContext(); 292 DeclDC; DeclDC = DeclDC->getLexicalParent()) { 293 if (DeclDC == DC) 294 return true; 295 } 296 return false; 297 } 298 299 bool CursorVisitor::visitDeclsFromFileRegion(FileID File, 300 unsigned Offset, unsigned Length) { 301 ASTUnit *Unit = cxtu::getASTUnit(TU); 302 SourceManager &SM = Unit->getSourceManager(); 303 SourceRange Range = RegionOfInterest; 304 305 SmallVector<Decl *, 16> Decls; 306 Unit->findFileRegionDecls(File, Offset, Length, Decls); 307 308 // If we didn't find any file level decls for the file, try looking at the 309 // file that it was included from. 310 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) { 311 bool Invalid = false; 312 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid); 313 if (Invalid) 314 return false; 315 316 SourceLocation Outer; 317 if (SLEntry.isFile()) 318 Outer = SLEntry.getFile().getIncludeLoc(); 319 else 320 Outer = SLEntry.getExpansion().getExpansionLocStart(); 321 if (Outer.isInvalid()) 322 return false; 323 324 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer); 325 Length = 0; 326 Unit->findFileRegionDecls(File, Offset, Length, Decls); 327 } 328 329 assert(!Decls.empty()); 330 331 bool VisitedAtLeastOnce = false; 332 DeclContext *CurDC = nullptr; 333 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin(); 334 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) { 335 Decl *D = *DIt; 336 if (D->getSourceRange().isInvalid()) 337 continue; 338 339 if (isInLexicalContext(D, CurDC)) 340 continue; 341 342 CurDC = dyn_cast<DeclContext>(D); 343 344 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 345 if (!TD->isFreeStanding()) 346 continue; 347 348 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range); 349 if (CompRes == RangeBefore) 350 continue; 351 if (CompRes == RangeAfter) 352 break; 353 354 assert(CompRes == RangeOverlap); 355 VisitedAtLeastOnce = true; 356 357 if (isa<ObjCContainerDecl>(D)) { 358 FileDI_current = &DIt; 359 FileDE_current = DE; 360 } else { 361 FileDI_current = nullptr; 362 } 363 364 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) 365 return true; // visitation break. 366 } 367 368 if (VisitedAtLeastOnce) 369 return false; 370 371 // No Decls overlapped with the range. Move up the lexical context until there 372 // is a context that contains the range or we reach the translation unit 373 // level. 374 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext() 375 : (*(DIt-1))->getLexicalDeclContext(); 376 377 while (DC && !DC->isTranslationUnit()) { 378 Decl *D = cast<Decl>(DC); 379 SourceRange CurDeclRange = D->getSourceRange(); 380 if (CurDeclRange.isInvalid()) 381 break; 382 383 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) { 384 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) 385 return true; // visitation break. 386 } 387 388 DC = D->getLexicalDeclContext(); 389 } 390 391 return false; 392 } 393 394 bool CursorVisitor::visitPreprocessedEntitiesInRegion() { 395 if (!AU->getPreprocessor().getPreprocessingRecord()) 396 return false; 397 398 PreprocessingRecord &PPRec 399 = *AU->getPreprocessor().getPreprocessingRecord(); 400 SourceManager &SM = AU->getSourceManager(); 401 402 if (RegionOfInterest.isValid()) { 403 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest); 404 SourceLocation B = MappedRange.getBegin(); 405 SourceLocation E = MappedRange.getEnd(); 406 407 if (AU->isInPreambleFileID(B)) { 408 if (SM.isLoadedSourceLocation(E)) 409 return visitPreprocessedEntitiesInRange(SourceRange(B, E), 410 PPRec, *this); 411 412 // Beginning of range lies in the preamble but it also extends beyond 413 // it into the main file. Split the range into 2 parts, one covering 414 // the preamble and another covering the main file. This allows subsequent 415 // calls to visitPreprocessedEntitiesInRange to accept a source range that 416 // lies in the same FileID, allowing it to skip preprocessed entities that 417 // do not come from the same FileID. 418 bool breaked = 419 visitPreprocessedEntitiesInRange( 420 SourceRange(B, AU->getEndOfPreambleFileID()), 421 PPRec, *this); 422 if (breaked) return true; 423 return visitPreprocessedEntitiesInRange( 424 SourceRange(AU->getStartOfMainFileID(), E), 425 PPRec, *this); 426 } 427 428 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this); 429 } 430 431 bool OnlyLocalDecls 432 = !AU->isMainFileAST() && AU->getOnlyLocalDecls(); 433 434 if (OnlyLocalDecls) 435 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(), 436 PPRec); 437 438 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec); 439 } 440 441 template<typename InputIterator> 442 bool CursorVisitor::visitPreprocessedEntities(InputIterator First, 443 InputIterator Last, 444 PreprocessingRecord &PPRec, 445 FileID FID) { 446 for (; First != Last; ++First) { 447 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID)) 448 continue; 449 450 PreprocessedEntity *PPE = *First; 451 if (!PPE) 452 continue; 453 454 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) { 455 if (Visit(MakeMacroExpansionCursor(ME, TU))) 456 return true; 457 458 continue; 459 } 460 461 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) { 462 if (Visit(MakeMacroDefinitionCursor(MD, TU))) 463 return true; 464 465 continue; 466 } 467 468 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) { 469 if (Visit(MakeInclusionDirectiveCursor(ID, TU))) 470 return true; 471 472 continue; 473 } 474 } 475 476 return false; 477 } 478 479 /// \brief Visit the children of the given cursor. 480 /// 481 /// \returns true if the visitation should be aborted, false if it 482 /// should continue. 483 bool CursorVisitor::VisitChildren(CXCursor Cursor) { 484 if (clang_isReference(Cursor.kind) && 485 Cursor.kind != CXCursor_CXXBaseSpecifier) { 486 // By definition, references have no children. 487 return false; 488 } 489 490 // Set the Parent field to Cursor, then back to its old value once we're 491 // done. 492 SetParentRAII SetParent(Parent, StmtParent, Cursor); 493 494 if (clang_isDeclaration(Cursor.kind)) { 495 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor)); 496 if (!D) 497 return false; 498 499 return VisitAttributes(D) || Visit(D); 500 } 501 502 if (clang_isStatement(Cursor.kind)) { 503 if (const Stmt *S = getCursorStmt(Cursor)) 504 return Visit(S); 505 506 return false; 507 } 508 509 if (clang_isExpression(Cursor.kind)) { 510 if (const Expr *E = getCursorExpr(Cursor)) 511 return Visit(E); 512 513 return false; 514 } 515 516 if (clang_isTranslationUnit(Cursor.kind)) { 517 CXTranslationUnit TU = getCursorTU(Cursor); 518 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 519 520 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast }; 521 for (unsigned I = 0; I != 2; ++I) { 522 if (VisitOrder[I]) { 523 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() && 524 RegionOfInterest.isInvalid()) { 525 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(), 526 TLEnd = CXXUnit->top_level_end(); 527 TL != TLEnd; ++TL) { 528 const Optional<bool> V = handleDeclForVisitation(*TL); 529 if (!V.hasValue()) 530 continue; 531 return V.getValue(); 532 } 533 } else if (VisitDeclContext( 534 CXXUnit->getASTContext().getTranslationUnitDecl())) 535 return true; 536 continue; 537 } 538 539 // Walk the preprocessing record. 540 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) 541 visitPreprocessedEntitiesInRegion(); 542 } 543 544 return false; 545 } 546 547 if (Cursor.kind == CXCursor_CXXBaseSpecifier) { 548 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) { 549 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) { 550 return Visit(BaseTSInfo->getTypeLoc()); 551 } 552 } 553 } 554 555 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) { 556 const IBOutletCollectionAttr *A = 557 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor)); 558 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>()) 559 return Visit(cxcursor::MakeCursorObjCClassRef( 560 ObjT->getInterface(), 561 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU)); 562 } 563 564 // If pointing inside a macro definition, check if the token is an identifier 565 // that was ever defined as a macro. In such a case, create a "pseudo" macro 566 // expansion cursor for that token. 567 SourceLocation BeginLoc = RegionOfInterest.getBegin(); 568 if (Cursor.kind == CXCursor_MacroDefinition && 569 BeginLoc == RegionOfInterest.getEnd()) { 570 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc); 571 const MacroInfo *MI = 572 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU); 573 if (MacroDefinitionRecord *MacroDef = 574 checkForMacroInMacroDefinition(MI, Loc, TU)) 575 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU)); 576 } 577 578 // Nothing to visit at the moment. 579 return false; 580 } 581 582 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { 583 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten()) 584 if (Visit(TSInfo->getTypeLoc())) 585 return true; 586 587 if (Stmt *Body = B->getBody()) 588 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest)); 589 590 return false; 591 } 592 593 Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) { 594 if (RegionOfInterest.isValid()) { 595 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager()); 596 if (Range.isInvalid()) 597 return None; 598 599 switch (CompareRegionOfInterest(Range)) { 600 case RangeBefore: 601 // This declaration comes before the region of interest; skip it. 602 return None; 603 604 case RangeAfter: 605 // This declaration comes after the region of interest; we're done. 606 return false; 607 608 case RangeOverlap: 609 // This declaration overlaps the region of interest; visit it. 610 break; 611 } 612 } 613 return true; 614 } 615 616 bool CursorVisitor::VisitDeclContext(DeclContext *DC) { 617 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); 618 619 // FIXME: Eventually remove. This part of a hack to support proper 620 // iteration over all Decls contained lexically within an ObjC container. 621 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I); 622 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E); 623 624 for ( ; I != E; ++I) { 625 Decl *D = *I; 626 if (D->getLexicalDeclContext() != DC) 627 continue; 628 const Optional<bool> V = handleDeclForVisitation(D); 629 if (!V.hasValue()) 630 continue; 631 return V.getValue(); 632 } 633 return false; 634 } 635 636 Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) { 637 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest); 638 639 // Ignore synthesized ivars here, otherwise if we have something like: 640 // @synthesize prop = _prop; 641 // and '_prop' is not declared, we will encounter a '_prop' ivar before 642 // encountering the 'prop' synthesize declaration and we will think that 643 // we passed the region-of-interest. 644 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) { 645 if (ivarD->getSynthesize()) 646 return None; 647 } 648 649 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol 650 // declarations is a mismatch with the compiler semantics. 651 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) { 652 auto *ID = cast<ObjCInterfaceDecl>(D); 653 if (!ID->isThisDeclarationADefinition()) 654 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU); 655 656 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) { 657 auto *PD = cast<ObjCProtocolDecl>(D); 658 if (!PD->isThisDeclarationADefinition()) 659 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU); 660 } 661 662 const Optional<bool> V = shouldVisitCursor(Cursor); 663 if (!V.hasValue()) 664 return None; 665 if (!V.getValue()) 666 return false; 667 if (Visit(Cursor, true)) 668 return true; 669 return None; 670 } 671 672 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 673 llvm_unreachable("Translation units are visited directly by Visit()"); 674 } 675 676 bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 677 if (VisitTemplateParameters(D->getTemplateParameters())) 678 return true; 679 680 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest)); 681 } 682 683 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) { 684 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 685 return Visit(TSInfo->getTypeLoc()); 686 687 return false; 688 } 689 690 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) { 691 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 692 return Visit(TSInfo->getTypeLoc()); 693 694 return false; 695 } 696 697 bool CursorVisitor::VisitTagDecl(TagDecl *D) { 698 return VisitDeclContext(D); 699 } 700 701 bool CursorVisitor::VisitClassTemplateSpecializationDecl( 702 ClassTemplateSpecializationDecl *D) { 703 bool ShouldVisitBody = false; 704 switch (D->getSpecializationKind()) { 705 case TSK_Undeclared: 706 case TSK_ImplicitInstantiation: 707 // Nothing to visit 708 return false; 709 710 case TSK_ExplicitInstantiationDeclaration: 711 case TSK_ExplicitInstantiationDefinition: 712 break; 713 714 case TSK_ExplicitSpecialization: 715 ShouldVisitBody = true; 716 break; 717 } 718 719 // Visit the template arguments used in the specialization. 720 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) { 721 TypeLoc TL = SpecType->getTypeLoc(); 722 if (TemplateSpecializationTypeLoc TSTLoc = 723 TL.getAs<TemplateSpecializationTypeLoc>()) { 724 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I) 725 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I))) 726 return true; 727 } 728 } 729 730 return ShouldVisitBody && VisitCXXRecordDecl(D); 731 } 732 733 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl( 734 ClassTemplatePartialSpecializationDecl *D) { 735 // FIXME: Visit the "outer" template parameter lists on the TagDecl 736 // before visiting these template parameters. 737 if (VisitTemplateParameters(D->getTemplateParameters())) 738 return true; 739 740 // Visit the partial specialization arguments. 741 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten(); 742 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs(); 743 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I) 744 if (VisitTemplateArgumentLoc(TemplateArgs[I])) 745 return true; 746 747 return VisitCXXRecordDecl(D); 748 } 749 750 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 751 // Visit the default argument. 752 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 753 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo()) 754 if (Visit(DefArg->getTypeLoc())) 755 return true; 756 757 return false; 758 } 759 760 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) { 761 if (Expr *Init = D->getInitExpr()) 762 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 763 return false; 764 } 765 766 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) { 767 unsigned NumParamList = DD->getNumTemplateParameterLists(); 768 for (unsigned i = 0; i < NumParamList; i++) { 769 TemplateParameterList* Params = DD->getTemplateParameterList(i); 770 if (VisitTemplateParameters(Params)) 771 return true; 772 } 773 774 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) 775 if (Visit(TSInfo->getTypeLoc())) 776 return true; 777 778 // Visit the nested-name-specifier, if present. 779 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc()) 780 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 781 return true; 782 783 return false; 784 } 785 786 /// \brief Compare two base or member initializers based on their source order. 787 static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X, 788 CXXCtorInitializer *const *Y) { 789 return (*X)->getSourceOrder() - (*Y)->getSourceOrder(); 790 } 791 792 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) { 793 unsigned NumParamList = ND->getNumTemplateParameterLists(); 794 for (unsigned i = 0; i < NumParamList; i++) { 795 TemplateParameterList* Params = ND->getTemplateParameterList(i); 796 if (VisitTemplateParameters(Params)) 797 return true; 798 } 799 800 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) { 801 // Visit the function declaration's syntactic components in the order 802 // written. This requires a bit of work. 803 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens(); 804 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>(); 805 806 // If we have a function declared directly (without the use of a typedef), 807 // visit just the return type. Otherwise, just visit the function's type 808 // now. 809 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) || 810 (!FTL && Visit(TL))) 811 return true; 812 813 // Visit the nested-name-specifier, if present. 814 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc()) 815 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 816 return true; 817 818 // Visit the declaration name. 819 if (!isa<CXXDestructorDecl>(ND)) 820 if (VisitDeclarationNameInfo(ND->getNameInfo())) 821 return true; 822 823 // FIXME: Visit explicitly-specified template arguments! 824 825 // Visit the function parameters, if we have a function type. 826 if (FTL && VisitFunctionTypeLoc(FTL, true)) 827 return true; 828 829 // FIXME: Attributes? 830 } 831 832 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) { 833 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) { 834 // Find the initializers that were written in the source. 835 SmallVector<CXXCtorInitializer *, 4> WrittenInits; 836 for (auto *I : Constructor->inits()) { 837 if (!I->isWritten()) 838 continue; 839 840 WrittenInits.push_back(I); 841 } 842 843 // Sort the initializers in source order 844 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(), 845 &CompareCXXCtorInitializers); 846 847 // Visit the initializers in source order 848 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) { 849 CXXCtorInitializer *Init = WrittenInits[I]; 850 if (Init->isAnyMemberInitializer()) { 851 if (Visit(MakeCursorMemberRef(Init->getAnyMember(), 852 Init->getMemberLocation(), TU))) 853 return true; 854 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) { 855 if (Visit(TInfo->getTypeLoc())) 856 return true; 857 } 858 859 // Visit the initializer value. 860 if (Expr *Initializer = Init->getInit()) 861 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest))) 862 return true; 863 } 864 } 865 866 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest))) 867 return true; 868 } 869 870 return false; 871 } 872 873 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) { 874 if (VisitDeclaratorDecl(D)) 875 return true; 876 877 if (Expr *BitWidth = D->getBitWidth()) 878 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest)); 879 880 return false; 881 } 882 883 bool CursorVisitor::VisitVarDecl(VarDecl *D) { 884 if (VisitDeclaratorDecl(D)) 885 return true; 886 887 if (Expr *Init = D->getInit()) 888 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 889 890 return false; 891 } 892 893 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 894 if (VisitDeclaratorDecl(D)) 895 return true; 896 897 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 898 if (Expr *DefArg = D->getDefaultArgument()) 899 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest)); 900 901 return false; 902 } 903 904 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 905 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl 906 // before visiting these template parameters. 907 if (VisitTemplateParameters(D->getTemplateParameters())) 908 return true; 909 910 auto* FD = D->getTemplatedDecl(); 911 return VisitAttributes(FD) || VisitFunctionDecl(FD); 912 } 913 914 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) { 915 // FIXME: Visit the "outer" template parameter lists on the TagDecl 916 // before visiting these template parameters. 917 if (VisitTemplateParameters(D->getTemplateParameters())) 918 return true; 919 920 auto* CD = D->getTemplatedDecl(); 921 return VisitAttributes(CD) || VisitCXXRecordDecl(CD); 922 } 923 924 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 925 if (VisitTemplateParameters(D->getTemplateParameters())) 926 return true; 927 928 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() && 929 VisitTemplateArgumentLoc(D->getDefaultArgument())) 930 return true; 931 932 return false; 933 } 934 935 bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) { 936 // Visit the bound, if it's explicit. 937 if (D->hasExplicitBound()) { 938 if (auto TInfo = D->getTypeSourceInfo()) { 939 if (Visit(TInfo->getTypeLoc())) 940 return true; 941 } 942 } 943 944 return false; 945 } 946 947 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) { 948 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo()) 949 if (Visit(TSInfo->getTypeLoc())) 950 return true; 951 952 for (const auto *P : ND->parameters()) { 953 if (Visit(MakeCXCursor(P, TU, RegionOfInterest))) 954 return true; 955 } 956 957 return ND->isThisDeclarationADefinition() && 958 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)); 959 } 960 961 template <typename DeclIt> 962 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current, 963 SourceManager &SM, SourceLocation EndLoc, 964 SmallVectorImpl<Decl *> &Decls) { 965 DeclIt next = *DI_current; 966 while (++next != DE_current) { 967 Decl *D_next = *next; 968 if (!D_next) 969 break; 970 SourceLocation L = D_next->getLocStart(); 971 if (!L.isValid()) 972 break; 973 if (SM.isBeforeInTranslationUnit(L, EndLoc)) { 974 *DI_current = next; 975 Decls.push_back(D_next); 976 continue; 977 } 978 break; 979 } 980 } 981 982 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { 983 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially 984 // an @implementation can lexically contain Decls that are not properly 985 // nested in the AST. When we identify such cases, we need to retrofit 986 // this nesting here. 987 if (!DI_current && !FileDI_current) 988 return VisitDeclContext(D); 989 990 // Scan the Decls that immediately come after the container 991 // in the current DeclContext. If any fall within the 992 // container's lexical region, stash them into a vector 993 // for later processing. 994 SmallVector<Decl *, 24> DeclsInContainer; 995 SourceLocation EndLoc = D->getSourceRange().getEnd(); 996 SourceManager &SM = AU->getSourceManager(); 997 if (EndLoc.isValid()) { 998 if (DI_current) { 999 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc, 1000 DeclsInContainer); 1001 } else { 1002 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc, 1003 DeclsInContainer); 1004 } 1005 } 1006 1007 // The common case. 1008 if (DeclsInContainer.empty()) 1009 return VisitDeclContext(D); 1010 1011 // Get all the Decls in the DeclContext, and sort them with the 1012 // additional ones we've collected. Then visit them. 1013 for (auto *SubDecl : D->decls()) { 1014 if (!SubDecl || SubDecl->getLexicalDeclContext() != D || 1015 SubDecl->getLocStart().isInvalid()) 1016 continue; 1017 DeclsInContainer.push_back(SubDecl); 1018 } 1019 1020 // Now sort the Decls so that they appear in lexical order. 1021 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(), 1022 [&SM](Decl *A, Decl *B) { 1023 SourceLocation L_A = A->getLocStart(); 1024 SourceLocation L_B = B->getLocStart(); 1025 assert(L_A.isValid() && L_B.isValid()); 1026 return SM.isBeforeInTranslationUnit(L_A, L_B); 1027 }); 1028 1029 // Now visit the decls. 1030 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(), 1031 E = DeclsInContainer.end(); I != E; ++I) { 1032 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest); 1033 const Optional<bool> &V = shouldVisitCursor(Cursor); 1034 if (!V.hasValue()) 1035 continue; 1036 if (!V.getValue()) 1037 return false; 1038 if (Visit(Cursor, true)) 1039 return true; 1040 } 1041 return false; 1042 } 1043 1044 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) { 1045 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(), 1046 TU))) 1047 return true; 1048 1049 if (VisitObjCTypeParamList(ND->getTypeParamList())) 1050 return true; 1051 1052 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin(); 1053 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(), 1054 E = ND->protocol_end(); I != E; ++I, ++PL) 1055 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1056 return true; 1057 1058 return VisitObjCContainerDecl(ND); 1059 } 1060 1061 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { 1062 if (!PID->isThisDeclarationADefinition()) 1063 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU)); 1064 1065 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin(); 1066 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), 1067 E = PID->protocol_end(); I != E; ++I, ++PL) 1068 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1069 return true; 1070 1071 return VisitObjCContainerDecl(PID); 1072 } 1073 1074 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) { 1075 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc())) 1076 return true; 1077 1078 // FIXME: This implements a workaround with @property declarations also being 1079 // installed in the DeclContext for the @interface. Eventually this code 1080 // should be removed. 1081 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext()); 1082 if (!CDecl || !CDecl->IsClassExtension()) 1083 return false; 1084 1085 ObjCInterfaceDecl *ID = CDecl->getClassInterface(); 1086 if (!ID) 1087 return false; 1088 1089 IdentifierInfo *PropertyId = PD->getIdentifier(); 1090 ObjCPropertyDecl *prevDecl = 1091 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId, 1092 PD->getQueryKind()); 1093 1094 if (!prevDecl) 1095 return false; 1096 1097 // Visit synthesized methods since they will be skipped when visiting 1098 // the @interface. 1099 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl()) 1100 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) 1101 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) 1102 return true; 1103 1104 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl()) 1105 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) 1106 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) 1107 return true; 1108 1109 return false; 1110 } 1111 1112 bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) { 1113 if (!typeParamList) 1114 return false; 1115 1116 for (auto *typeParam : *typeParamList) { 1117 // Visit the type parameter. 1118 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest))) 1119 return true; 1120 } 1121 1122 return false; 1123 } 1124 1125 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { 1126 if (!D->isThisDeclarationADefinition()) { 1127 // Forward declaration is treated like a reference. 1128 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU)); 1129 } 1130 1131 // Objective-C type parameters. 1132 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten())) 1133 return true; 1134 1135 // Issue callbacks for super class. 1136 if (D->getSuperClass() && 1137 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 1138 D->getSuperClassLoc(), 1139 TU))) 1140 return true; 1141 1142 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo()) 1143 if (Visit(SuperClassTInfo->getTypeLoc())) 1144 return true; 1145 1146 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); 1147 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(), 1148 E = D->protocol_end(); I != E; ++I, ++PL) 1149 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1150 return true; 1151 1152 return VisitObjCContainerDecl(D); 1153 } 1154 1155 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) { 1156 return VisitObjCContainerDecl(D); 1157 } 1158 1159 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { 1160 // 'ID' could be null when dealing with invalid code. 1161 if (ObjCInterfaceDecl *ID = D->getClassInterface()) 1162 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU))) 1163 return true; 1164 1165 return VisitObjCImplDecl(D); 1166 } 1167 1168 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { 1169 #if 0 1170 // Issue callbacks for super class. 1171 // FIXME: No source location information! 1172 if (D->getSuperClass() && 1173 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 1174 D->getSuperClassLoc(), 1175 TU))) 1176 return true; 1177 #endif 1178 1179 return VisitObjCImplDecl(D); 1180 } 1181 1182 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) { 1183 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl()) 1184 if (PD->isIvarNameSpecified()) 1185 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU)); 1186 1187 return false; 1188 } 1189 1190 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) { 1191 return VisitDeclContext(D); 1192 } 1193 1194 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 1195 // Visit nested-name-specifier. 1196 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1197 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1198 return true; 1199 1200 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(), 1201 D->getTargetNameLoc(), TU)); 1202 } 1203 1204 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) { 1205 // Visit nested-name-specifier. 1206 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { 1207 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1208 return true; 1209 } 1210 1211 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU))) 1212 return true; 1213 1214 return VisitDeclarationNameInfo(D->getNameInfo()); 1215 } 1216 1217 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1218 // Visit nested-name-specifier. 1219 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1220 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1221 return true; 1222 1223 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(), 1224 D->getIdentLocation(), TU)); 1225 } 1226 1227 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1228 // Visit nested-name-specifier. 1229 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { 1230 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1231 return true; 1232 } 1233 1234 return VisitDeclarationNameInfo(D->getNameInfo()); 1235 } 1236 1237 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl( 1238 UnresolvedUsingTypenameDecl *D) { 1239 // Visit nested-name-specifier. 1240 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1241 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1242 return true; 1243 1244 return false; 1245 } 1246 1247 bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) { 1248 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest))) 1249 return true; 1250 if (StringLiteral *Message = D->getMessage()) 1251 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest))) 1252 return true; 1253 return false; 1254 } 1255 1256 bool CursorVisitor::VisitFriendDecl(FriendDecl *D) { 1257 if (NamedDecl *FriendD = D->getFriendDecl()) { 1258 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest))) 1259 return true; 1260 } else if (TypeSourceInfo *TI = D->getFriendType()) { 1261 if (Visit(TI->getTypeLoc())) 1262 return true; 1263 } 1264 return false; 1265 } 1266 1267 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) { 1268 switch (Name.getName().getNameKind()) { 1269 case clang::DeclarationName::Identifier: 1270 case clang::DeclarationName::CXXLiteralOperatorName: 1271 case clang::DeclarationName::CXXDeductionGuideName: 1272 case clang::DeclarationName::CXXOperatorName: 1273 case clang::DeclarationName::CXXUsingDirective: 1274 return false; 1275 1276 case clang::DeclarationName::CXXConstructorName: 1277 case clang::DeclarationName::CXXDestructorName: 1278 case clang::DeclarationName::CXXConversionFunctionName: 1279 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo()) 1280 return Visit(TSInfo->getTypeLoc()); 1281 return false; 1282 1283 case clang::DeclarationName::ObjCZeroArgSelector: 1284 case clang::DeclarationName::ObjCOneArgSelector: 1285 case clang::DeclarationName::ObjCMultiArgSelector: 1286 // FIXME: Per-identifier location info? 1287 return false; 1288 } 1289 1290 llvm_unreachable("Invalid DeclarationName::Kind!"); 1291 } 1292 1293 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS, 1294 SourceRange Range) { 1295 // FIXME: This whole routine is a hack to work around the lack of proper 1296 // source information in nested-name-specifiers (PR5791). Since we do have 1297 // a beginning source location, we can visit the first component of the 1298 // nested-name-specifier, if it's a single-token component. 1299 if (!NNS) 1300 return false; 1301 1302 // Get the first component in the nested-name-specifier. 1303 while (NestedNameSpecifier *Prefix = NNS->getPrefix()) 1304 NNS = Prefix; 1305 1306 switch (NNS->getKind()) { 1307 case NestedNameSpecifier::Namespace: 1308 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), 1309 TU)); 1310 1311 case NestedNameSpecifier::NamespaceAlias: 1312 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 1313 Range.getBegin(), TU)); 1314 1315 case NestedNameSpecifier::TypeSpec: { 1316 // If the type has a form where we know that the beginning of the source 1317 // range matches up with a reference cursor. Visit the appropriate reference 1318 // cursor. 1319 const Type *T = NNS->getAsType(); 1320 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T)) 1321 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU)); 1322 if (const TagType *Tag = dyn_cast<TagType>(T)) 1323 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU)); 1324 if (const TemplateSpecializationType *TST 1325 = dyn_cast<TemplateSpecializationType>(T)) 1326 return VisitTemplateName(TST->getTemplateName(), Range.getBegin()); 1327 break; 1328 } 1329 1330 case NestedNameSpecifier::TypeSpecWithTemplate: 1331 case NestedNameSpecifier::Global: 1332 case NestedNameSpecifier::Identifier: 1333 case NestedNameSpecifier::Super: 1334 break; 1335 } 1336 1337 return false; 1338 } 1339 1340 bool 1341 CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) { 1342 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers; 1343 for (; Qualifier; Qualifier = Qualifier.getPrefix()) 1344 Qualifiers.push_back(Qualifier); 1345 1346 while (!Qualifiers.empty()) { 1347 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val(); 1348 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier(); 1349 switch (NNS->getKind()) { 1350 case NestedNameSpecifier::Namespace: 1351 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), 1352 Q.getLocalBeginLoc(), 1353 TU))) 1354 return true; 1355 1356 break; 1357 1358 case NestedNameSpecifier::NamespaceAlias: 1359 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 1360 Q.getLocalBeginLoc(), 1361 TU))) 1362 return true; 1363 1364 break; 1365 1366 case NestedNameSpecifier::TypeSpec: 1367 case NestedNameSpecifier::TypeSpecWithTemplate: 1368 if (Visit(Q.getTypeLoc())) 1369 return true; 1370 1371 break; 1372 1373 case NestedNameSpecifier::Global: 1374 case NestedNameSpecifier::Identifier: 1375 case NestedNameSpecifier::Super: 1376 break; 1377 } 1378 } 1379 1380 return false; 1381 } 1382 1383 bool CursorVisitor::VisitTemplateParameters( 1384 const TemplateParameterList *Params) { 1385 if (!Params) 1386 return false; 1387 1388 for (TemplateParameterList::const_iterator P = Params->begin(), 1389 PEnd = Params->end(); 1390 P != PEnd; ++P) { 1391 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest))) 1392 return true; 1393 } 1394 1395 return false; 1396 } 1397 1398 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) { 1399 switch (Name.getKind()) { 1400 case TemplateName::Template: 1401 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU)); 1402 1403 case TemplateName::OverloadedTemplate: 1404 // Visit the overloaded template set. 1405 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU))) 1406 return true; 1407 1408 return false; 1409 1410 case TemplateName::DependentTemplate: 1411 // FIXME: Visit nested-name-specifier. 1412 return false; 1413 1414 case TemplateName::QualifiedTemplate: 1415 // FIXME: Visit nested-name-specifier. 1416 return Visit(MakeCursorTemplateRef( 1417 Name.getAsQualifiedTemplateName()->getDecl(), 1418 Loc, TU)); 1419 1420 case TemplateName::SubstTemplateTemplateParm: 1421 return Visit(MakeCursorTemplateRef( 1422 Name.getAsSubstTemplateTemplateParm()->getParameter(), 1423 Loc, TU)); 1424 1425 case TemplateName::SubstTemplateTemplateParmPack: 1426 return Visit(MakeCursorTemplateRef( 1427 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), 1428 Loc, TU)); 1429 } 1430 1431 llvm_unreachable("Invalid TemplateName::Kind!"); 1432 } 1433 1434 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) { 1435 switch (TAL.getArgument().getKind()) { 1436 case TemplateArgument::Null: 1437 case TemplateArgument::Integral: 1438 case TemplateArgument::Pack: 1439 return false; 1440 1441 case TemplateArgument::Type: 1442 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo()) 1443 return Visit(TSInfo->getTypeLoc()); 1444 return false; 1445 1446 case TemplateArgument::Declaration: 1447 if (Expr *E = TAL.getSourceDeclExpression()) 1448 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1449 return false; 1450 1451 case TemplateArgument::NullPtr: 1452 if (Expr *E = TAL.getSourceNullPtrExpression()) 1453 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1454 return false; 1455 1456 case TemplateArgument::Expression: 1457 if (Expr *E = TAL.getSourceExpression()) 1458 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1459 return false; 1460 1461 case TemplateArgument::Template: 1462 case TemplateArgument::TemplateExpansion: 1463 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc())) 1464 return true; 1465 1466 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(), 1467 TAL.getTemplateNameLoc()); 1468 } 1469 1470 llvm_unreachable("Invalid TemplateArgument::Kind!"); 1471 } 1472 1473 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 1474 return VisitDeclContext(D); 1475 } 1476 1477 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1478 return Visit(TL.getUnqualifiedLoc()); 1479 } 1480 1481 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1482 ASTContext &Context = AU->getASTContext(); 1483 1484 // Some builtin types (such as Objective-C's "id", "sel", and 1485 // "Class") have associated declarations. Create cursors for those. 1486 QualType VisitType; 1487 switch (TL.getTypePtr()->getKind()) { 1488 1489 case BuiltinType::Void: 1490 case BuiltinType::NullPtr: 1491 case BuiltinType::Dependent: 1492 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1493 case BuiltinType::Id: 1494 #include "clang/Basic/OpenCLImageTypes.def" 1495 case BuiltinType::OCLSampler: 1496 case BuiltinType::OCLEvent: 1497 case BuiltinType::OCLClkEvent: 1498 case BuiltinType::OCLQueue: 1499 case BuiltinType::OCLReserveID: 1500 #define BUILTIN_TYPE(Id, SingletonId) 1501 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 1502 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 1503 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: 1504 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: 1505 #include "clang/AST/BuiltinTypes.def" 1506 break; 1507 1508 case BuiltinType::ObjCId: 1509 VisitType = Context.getObjCIdType(); 1510 break; 1511 1512 case BuiltinType::ObjCClass: 1513 VisitType = Context.getObjCClassType(); 1514 break; 1515 1516 case BuiltinType::ObjCSel: 1517 VisitType = Context.getObjCSelType(); 1518 break; 1519 } 1520 1521 if (!VisitType.isNull()) { 1522 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>()) 1523 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), 1524 TU)); 1525 } 1526 1527 return false; 1528 } 1529 1530 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 1531 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU)); 1532 } 1533 1534 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 1535 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1536 } 1537 1538 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { 1539 if (TL.isDefinition()) 1540 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest)); 1541 1542 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1543 } 1544 1545 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 1546 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1547 } 1548 1549 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 1550 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)); 1551 } 1552 1553 bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { 1554 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getLocStart(), TU))) 1555 return true; 1556 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { 1557 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), 1558 TU))) 1559 return true; 1560 } 1561 1562 return false; 1563 } 1564 1565 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 1566 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc())) 1567 return true; 1568 1569 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) { 1570 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc())) 1571 return true; 1572 } 1573 1574 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { 1575 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), 1576 TU))) 1577 return true; 1578 } 1579 1580 return false; 1581 } 1582 1583 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1584 return Visit(TL.getPointeeLoc()); 1585 } 1586 1587 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) { 1588 return Visit(TL.getInnerLoc()); 1589 } 1590 1591 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { 1592 return Visit(TL.getPointeeLoc()); 1593 } 1594 1595 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 1596 return Visit(TL.getPointeeLoc()); 1597 } 1598 1599 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 1600 return Visit(TL.getPointeeLoc()); 1601 } 1602 1603 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 1604 return Visit(TL.getPointeeLoc()); 1605 } 1606 1607 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 1608 return Visit(TL.getPointeeLoc()); 1609 } 1610 1611 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 1612 return Visit(TL.getModifiedLoc()); 1613 } 1614 1615 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL, 1616 bool SkipResultType) { 1617 if (!SkipResultType && Visit(TL.getReturnLoc())) 1618 return true; 1619 1620 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I) 1621 if (Decl *D = TL.getParam(I)) 1622 if (Visit(MakeCXCursor(D, TU, RegionOfInterest))) 1623 return true; 1624 1625 return false; 1626 } 1627 1628 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { 1629 if (Visit(TL.getElementLoc())) 1630 return true; 1631 1632 if (Expr *Size = TL.getSizeExpr()) 1633 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest)); 1634 1635 return false; 1636 } 1637 1638 bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) { 1639 return Visit(TL.getOriginalLoc()); 1640 } 1641 1642 bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 1643 return Visit(TL.getOriginalLoc()); 1644 } 1645 1646 bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc( 1647 DeducedTemplateSpecializationTypeLoc TL) { 1648 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 1649 TL.getTemplateNameLoc())) 1650 return true; 1651 1652 return false; 1653 } 1654 1655 bool CursorVisitor::VisitTemplateSpecializationTypeLoc( 1656 TemplateSpecializationTypeLoc TL) { 1657 // Visit the template name. 1658 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 1659 TL.getTemplateNameLoc())) 1660 return true; 1661 1662 // Visit the template arguments. 1663 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1664 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1665 return true; 1666 1667 return false; 1668 } 1669 1670 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 1671 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); 1672 } 1673 1674 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 1675 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1676 return Visit(TSInfo->getTypeLoc()); 1677 1678 return false; 1679 } 1680 1681 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 1682 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1683 return Visit(TSInfo->getTypeLoc()); 1684 1685 return false; 1686 } 1687 1688 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 1689 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc()); 1690 } 1691 1692 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc( 1693 DependentTemplateSpecializationTypeLoc TL) { 1694 // Visit the nested-name-specifier, if there is one. 1695 if (TL.getQualifierLoc() && 1696 VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1697 return true; 1698 1699 // Visit the template arguments. 1700 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1701 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1702 return true; 1703 1704 return false; 1705 } 1706 1707 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 1708 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1709 return true; 1710 1711 return Visit(TL.getNamedTypeLoc()); 1712 } 1713 1714 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 1715 return Visit(TL.getPatternLoc()); 1716 } 1717 1718 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 1719 if (Expr *E = TL.getUnderlyingExpr()) 1720 return Visit(MakeCXCursor(E, StmtParent, TU)); 1721 1722 return false; 1723 } 1724 1725 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 1726 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1727 } 1728 1729 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 1730 return Visit(TL.getValueLoc()); 1731 } 1732 1733 bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) { 1734 return Visit(TL.getValueLoc()); 1735 } 1736 1737 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \ 1738 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \ 1739 return Visit##PARENT##Loc(TL); \ 1740 } 1741 1742 DEFAULT_TYPELOC_IMPL(Complex, Type) 1743 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType) 1744 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType) 1745 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType) 1746 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType) 1747 DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type) 1748 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type) 1749 DEFAULT_TYPELOC_IMPL(Vector, Type) 1750 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType) 1751 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType) 1752 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType) 1753 DEFAULT_TYPELOC_IMPL(Record, TagType) 1754 DEFAULT_TYPELOC_IMPL(Enum, TagType) 1755 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type) 1756 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type) 1757 DEFAULT_TYPELOC_IMPL(Auto, Type) 1758 1759 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) { 1760 // Visit the nested-name-specifier, if present. 1761 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1762 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1763 return true; 1764 1765 if (D->isCompleteDefinition()) { 1766 for (const auto &I : D->bases()) { 1767 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU))) 1768 return true; 1769 } 1770 } 1771 1772 return VisitTagDecl(D); 1773 } 1774 1775 bool CursorVisitor::VisitAttributes(Decl *D) { 1776 for (const auto *I : D->attrs()) 1777 if (Visit(MakeCXCursor(I, D, TU))) 1778 return true; 1779 1780 return false; 1781 } 1782 1783 //===----------------------------------------------------------------------===// 1784 // Data-recursive visitor methods. 1785 //===----------------------------------------------------------------------===// 1786 1787 namespace { 1788 #define DEF_JOB(NAME, DATA, KIND)\ 1789 class NAME : public VisitorJob {\ 1790 public:\ 1791 NAME(const DATA *d, CXCursor parent) : \ 1792 VisitorJob(parent, VisitorJob::KIND, d) {} \ 1793 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\ 1794 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\ 1795 }; 1796 1797 DEF_JOB(StmtVisit, Stmt, StmtVisitKind) 1798 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind) 1799 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind) 1800 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind) 1801 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind) 1802 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind) 1803 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind) 1804 #undef DEF_JOB 1805 1806 class ExplicitTemplateArgsVisit : public VisitorJob { 1807 public: 1808 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin, 1809 const TemplateArgumentLoc *End, CXCursor parent) 1810 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin, 1811 End) {} 1812 static bool classof(const VisitorJob *VJ) { 1813 return VJ->getKind() == ExplicitTemplateArgsVisitKind; 1814 } 1815 const TemplateArgumentLoc *begin() const { 1816 return static_cast<const TemplateArgumentLoc *>(data[0]); 1817 } 1818 const TemplateArgumentLoc *end() { 1819 return static_cast<const TemplateArgumentLoc *>(data[1]); 1820 } 1821 }; 1822 class DeclVisit : public VisitorJob { 1823 public: 1824 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) : 1825 VisitorJob(parent, VisitorJob::DeclVisitKind, 1826 D, isFirst ? (void*) 1 : (void*) nullptr) {} 1827 static bool classof(const VisitorJob *VJ) { 1828 return VJ->getKind() == DeclVisitKind; 1829 } 1830 const Decl *get() const { return static_cast<const Decl *>(data[0]); } 1831 bool isFirst() const { return data[1] != nullptr; } 1832 }; 1833 class TypeLocVisit : public VisitorJob { 1834 public: 1835 TypeLocVisit(TypeLoc tl, CXCursor parent) : 1836 VisitorJob(parent, VisitorJob::TypeLocVisitKind, 1837 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {} 1838 1839 static bool classof(const VisitorJob *VJ) { 1840 return VJ->getKind() == TypeLocVisitKind; 1841 } 1842 1843 TypeLoc get() const { 1844 QualType T = QualType::getFromOpaquePtr(data[0]); 1845 return TypeLoc(T, const_cast<void *>(data[1])); 1846 } 1847 }; 1848 1849 class LabelRefVisit : public VisitorJob { 1850 public: 1851 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent) 1852 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD, 1853 labelLoc.getPtrEncoding()) {} 1854 1855 static bool classof(const VisitorJob *VJ) { 1856 return VJ->getKind() == VisitorJob::LabelRefVisitKind; 1857 } 1858 const LabelDecl *get() const { 1859 return static_cast<const LabelDecl *>(data[0]); 1860 } 1861 SourceLocation getLoc() const { 1862 return SourceLocation::getFromPtrEncoding(data[1]); } 1863 }; 1864 1865 class NestedNameSpecifierLocVisit : public VisitorJob { 1866 public: 1867 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent) 1868 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind, 1869 Qualifier.getNestedNameSpecifier(), 1870 Qualifier.getOpaqueData()) { } 1871 1872 static bool classof(const VisitorJob *VJ) { 1873 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind; 1874 } 1875 1876 NestedNameSpecifierLoc get() const { 1877 return NestedNameSpecifierLoc( 1878 const_cast<NestedNameSpecifier *>( 1879 static_cast<const NestedNameSpecifier *>(data[0])), 1880 const_cast<void *>(data[1])); 1881 } 1882 }; 1883 1884 class DeclarationNameInfoVisit : public VisitorJob { 1885 public: 1886 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent) 1887 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {} 1888 static bool classof(const VisitorJob *VJ) { 1889 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind; 1890 } 1891 DeclarationNameInfo get() const { 1892 const Stmt *S = static_cast<const Stmt *>(data[0]); 1893 switch (S->getStmtClass()) { 1894 default: 1895 llvm_unreachable("Unhandled Stmt"); 1896 case clang::Stmt::MSDependentExistsStmtClass: 1897 return cast<MSDependentExistsStmt>(S)->getNameInfo(); 1898 case Stmt::CXXDependentScopeMemberExprClass: 1899 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo(); 1900 case Stmt::DependentScopeDeclRefExprClass: 1901 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo(); 1902 case Stmt::OMPCriticalDirectiveClass: 1903 return cast<OMPCriticalDirective>(S)->getDirectiveName(); 1904 } 1905 } 1906 }; 1907 class MemberRefVisit : public VisitorJob { 1908 public: 1909 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent) 1910 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D, 1911 L.getPtrEncoding()) {} 1912 static bool classof(const VisitorJob *VJ) { 1913 return VJ->getKind() == VisitorJob::MemberRefVisitKind; 1914 } 1915 const FieldDecl *get() const { 1916 return static_cast<const FieldDecl *>(data[0]); 1917 } 1918 SourceLocation getLoc() const { 1919 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]); 1920 } 1921 }; 1922 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> { 1923 friend class OMPClauseEnqueue; 1924 VisitorWorkList &WL; 1925 CXCursor Parent; 1926 public: 1927 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent) 1928 : WL(wl), Parent(parent) {} 1929 1930 void VisitAddrLabelExpr(const AddrLabelExpr *E); 1931 void VisitBlockExpr(const BlockExpr *B); 1932 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 1933 void VisitCompoundStmt(const CompoundStmt *S); 1934 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ } 1935 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S); 1936 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E); 1937 void VisitCXXNewExpr(const CXXNewExpr *E); 1938 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E); 1939 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E); 1940 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E); 1941 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E); 1942 void VisitCXXTypeidExpr(const CXXTypeidExpr *E); 1943 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E); 1944 void VisitCXXUuidofExpr(const CXXUuidofExpr *E); 1945 void VisitCXXCatchStmt(const CXXCatchStmt *S); 1946 void VisitCXXForRangeStmt(const CXXForRangeStmt *S); 1947 void VisitDeclRefExpr(const DeclRefExpr *D); 1948 void VisitDeclStmt(const DeclStmt *S); 1949 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E); 1950 void VisitDesignatedInitExpr(const DesignatedInitExpr *E); 1951 void VisitExplicitCastExpr(const ExplicitCastExpr *E); 1952 void VisitForStmt(const ForStmt *FS); 1953 void VisitGotoStmt(const GotoStmt *GS); 1954 void VisitIfStmt(const IfStmt *If); 1955 void VisitInitListExpr(const InitListExpr *IE); 1956 void VisitMemberExpr(const MemberExpr *M); 1957 void VisitOffsetOfExpr(const OffsetOfExpr *E); 1958 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E); 1959 void VisitObjCMessageExpr(const ObjCMessageExpr *M); 1960 void VisitOverloadExpr(const OverloadExpr *E); 1961 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 1962 void VisitStmt(const Stmt *S); 1963 void VisitSwitchStmt(const SwitchStmt *S); 1964 void VisitWhileStmt(const WhileStmt *W); 1965 void VisitTypeTraitExpr(const TypeTraitExpr *E); 1966 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E); 1967 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E); 1968 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U); 1969 void VisitVAArgExpr(const VAArgExpr *E); 1970 void VisitSizeOfPackExpr(const SizeOfPackExpr *E); 1971 void VisitPseudoObjectExpr(const PseudoObjectExpr *E); 1972 void VisitOpaqueValueExpr(const OpaqueValueExpr *E); 1973 void VisitLambdaExpr(const LambdaExpr *E); 1974 void VisitOMPExecutableDirective(const OMPExecutableDirective *D); 1975 void VisitOMPLoopDirective(const OMPLoopDirective *D); 1976 void VisitOMPParallelDirective(const OMPParallelDirective *D); 1977 void VisitOMPSimdDirective(const OMPSimdDirective *D); 1978 void VisitOMPForDirective(const OMPForDirective *D); 1979 void VisitOMPForSimdDirective(const OMPForSimdDirective *D); 1980 void VisitOMPSectionsDirective(const OMPSectionsDirective *D); 1981 void VisitOMPSectionDirective(const OMPSectionDirective *D); 1982 void VisitOMPSingleDirective(const OMPSingleDirective *D); 1983 void VisitOMPMasterDirective(const OMPMasterDirective *D); 1984 void VisitOMPCriticalDirective(const OMPCriticalDirective *D); 1985 void VisitOMPParallelForDirective(const OMPParallelForDirective *D); 1986 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D); 1987 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D); 1988 void VisitOMPTaskDirective(const OMPTaskDirective *D); 1989 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D); 1990 void VisitOMPBarrierDirective(const OMPBarrierDirective *D); 1991 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D); 1992 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D); 1993 void 1994 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D); 1995 void VisitOMPCancelDirective(const OMPCancelDirective *D); 1996 void VisitOMPFlushDirective(const OMPFlushDirective *D); 1997 void VisitOMPOrderedDirective(const OMPOrderedDirective *D); 1998 void VisitOMPAtomicDirective(const OMPAtomicDirective *D); 1999 void VisitOMPTargetDirective(const OMPTargetDirective *D); 2000 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D); 2001 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D); 2002 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D); 2003 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D); 2004 void 2005 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D); 2006 void VisitOMPTeamsDirective(const OMPTeamsDirective *D); 2007 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D); 2008 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D); 2009 void VisitOMPDistributeDirective(const OMPDistributeDirective *D); 2010 void VisitOMPDistributeParallelForDirective( 2011 const OMPDistributeParallelForDirective *D); 2012 void VisitOMPDistributeParallelForSimdDirective( 2013 const OMPDistributeParallelForSimdDirective *D); 2014 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D); 2015 void VisitOMPTargetParallelForSimdDirective( 2016 const OMPTargetParallelForSimdDirective *D); 2017 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D); 2018 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D); 2019 void VisitOMPTeamsDistributeSimdDirective( 2020 const OMPTeamsDistributeSimdDirective *D); 2021 void VisitOMPTeamsDistributeParallelForSimdDirective( 2022 const OMPTeamsDistributeParallelForSimdDirective *D); 2023 void VisitOMPTeamsDistributeParallelForDirective( 2024 const OMPTeamsDistributeParallelForDirective *D); 2025 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D); 2026 void VisitOMPTargetTeamsDistributeDirective( 2027 const OMPTargetTeamsDistributeDirective *D); 2028 void VisitOMPTargetTeamsDistributeParallelForDirective( 2029 const OMPTargetTeamsDistributeParallelForDirective *D); 2030 void VisitOMPTargetTeamsDistributeParallelForSimdDirective( 2031 const OMPTargetTeamsDistributeParallelForSimdDirective *D); 2032 void VisitOMPTargetTeamsDistributeSimdDirective( 2033 const OMPTargetTeamsDistributeSimdDirective *D); 2034 2035 private: 2036 void AddDeclarationNameInfo(const Stmt *S); 2037 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier); 2038 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A, 2039 unsigned NumTemplateArgs); 2040 void AddMemberRef(const FieldDecl *D, SourceLocation L); 2041 void AddStmt(const Stmt *S); 2042 void AddDecl(const Decl *D, bool isFirst = true); 2043 void AddTypeLoc(TypeSourceInfo *TI); 2044 void EnqueueChildren(const Stmt *S); 2045 void EnqueueChildren(const OMPClause *S); 2046 }; 2047 } // end anonyous namespace 2048 2049 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) { 2050 // 'S' should always be non-null, since it comes from the 2051 // statement we are visiting. 2052 WL.push_back(DeclarationNameInfoVisit(S, Parent)); 2053 } 2054 2055 void 2056 EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) { 2057 if (Qualifier) 2058 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent)); 2059 } 2060 2061 void EnqueueVisitor::AddStmt(const Stmt *S) { 2062 if (S) 2063 WL.push_back(StmtVisit(S, Parent)); 2064 } 2065 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) { 2066 if (D) 2067 WL.push_back(DeclVisit(D, Parent, isFirst)); 2068 } 2069 void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A, 2070 unsigned NumTemplateArgs) { 2071 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent)); 2072 } 2073 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) { 2074 if (D) 2075 WL.push_back(MemberRefVisit(D, L, Parent)); 2076 } 2077 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) { 2078 if (TI) 2079 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent)); 2080 } 2081 void EnqueueVisitor::EnqueueChildren(const Stmt *S) { 2082 unsigned size = WL.size(); 2083 for (const Stmt *SubStmt : S->children()) { 2084 AddStmt(SubStmt); 2085 } 2086 if (size == WL.size()) 2087 return; 2088 // Now reverse the entries we just added. This will match the DFS 2089 // ordering performed by the worklist. 2090 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 2091 std::reverse(I, E); 2092 } 2093 namespace { 2094 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> { 2095 EnqueueVisitor *Visitor; 2096 /// \brief Process clauses with list of variables. 2097 template <typename T> 2098 void VisitOMPClauseList(T *Node); 2099 public: 2100 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { } 2101 #define OPENMP_CLAUSE(Name, Class) \ 2102 void Visit##Class(const Class *C); 2103 #include "clang/Basic/OpenMPKinds.def" 2104 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C); 2105 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C); 2106 }; 2107 2108 void OMPClauseEnqueue::VisitOMPClauseWithPreInit( 2109 const OMPClauseWithPreInit *C) { 2110 Visitor->AddStmt(C->getPreInitStmt()); 2111 } 2112 2113 void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate( 2114 const OMPClauseWithPostUpdate *C) { 2115 VisitOMPClauseWithPreInit(C); 2116 Visitor->AddStmt(C->getPostUpdateExpr()); 2117 } 2118 2119 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) { 2120 VisitOMPClauseWithPreInit(C); 2121 Visitor->AddStmt(C->getCondition()); 2122 } 2123 2124 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) { 2125 Visitor->AddStmt(C->getCondition()); 2126 } 2127 2128 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) { 2129 VisitOMPClauseWithPreInit(C); 2130 Visitor->AddStmt(C->getNumThreads()); 2131 } 2132 2133 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) { 2134 Visitor->AddStmt(C->getSafelen()); 2135 } 2136 2137 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) { 2138 Visitor->AddStmt(C->getSimdlen()); 2139 } 2140 2141 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) { 2142 Visitor->AddStmt(C->getNumForLoops()); 2143 } 2144 2145 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { } 2146 2147 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { } 2148 2149 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) { 2150 VisitOMPClauseWithPreInit(C); 2151 Visitor->AddStmt(C->getChunkSize()); 2152 } 2153 2154 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) { 2155 Visitor->AddStmt(C->getNumForLoops()); 2156 } 2157 2158 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {} 2159 2160 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {} 2161 2162 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {} 2163 2164 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {} 2165 2166 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {} 2167 2168 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {} 2169 2170 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {} 2171 2172 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {} 2173 2174 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {} 2175 2176 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {} 2177 2178 void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {} 2179 2180 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) { 2181 Visitor->AddStmt(C->getDevice()); 2182 } 2183 2184 void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) { 2185 VisitOMPClauseWithPreInit(C); 2186 Visitor->AddStmt(C->getNumTeams()); 2187 } 2188 2189 void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) { 2190 VisitOMPClauseWithPreInit(C); 2191 Visitor->AddStmt(C->getThreadLimit()); 2192 } 2193 2194 void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) { 2195 Visitor->AddStmt(C->getPriority()); 2196 } 2197 2198 void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) { 2199 Visitor->AddStmt(C->getGrainsize()); 2200 } 2201 2202 void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) { 2203 Visitor->AddStmt(C->getNumTasks()); 2204 } 2205 2206 void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) { 2207 Visitor->AddStmt(C->getHint()); 2208 } 2209 2210 template<typename T> 2211 void OMPClauseEnqueue::VisitOMPClauseList(T *Node) { 2212 for (const auto *I : Node->varlists()) { 2213 Visitor->AddStmt(I); 2214 } 2215 } 2216 2217 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) { 2218 VisitOMPClauseList(C); 2219 for (const auto *E : C->private_copies()) { 2220 Visitor->AddStmt(E); 2221 } 2222 } 2223 void OMPClauseEnqueue::VisitOMPFirstprivateClause( 2224 const OMPFirstprivateClause *C) { 2225 VisitOMPClauseList(C); 2226 VisitOMPClauseWithPreInit(C); 2227 for (const auto *E : C->private_copies()) { 2228 Visitor->AddStmt(E); 2229 } 2230 for (const auto *E : C->inits()) { 2231 Visitor->AddStmt(E); 2232 } 2233 } 2234 void OMPClauseEnqueue::VisitOMPLastprivateClause( 2235 const OMPLastprivateClause *C) { 2236 VisitOMPClauseList(C); 2237 VisitOMPClauseWithPostUpdate(C); 2238 for (auto *E : C->private_copies()) { 2239 Visitor->AddStmt(E); 2240 } 2241 for (auto *E : C->source_exprs()) { 2242 Visitor->AddStmt(E); 2243 } 2244 for (auto *E : C->destination_exprs()) { 2245 Visitor->AddStmt(E); 2246 } 2247 for (auto *E : C->assignment_ops()) { 2248 Visitor->AddStmt(E); 2249 } 2250 } 2251 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) { 2252 VisitOMPClauseList(C); 2253 } 2254 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) { 2255 VisitOMPClauseList(C); 2256 VisitOMPClauseWithPostUpdate(C); 2257 for (auto *E : C->privates()) { 2258 Visitor->AddStmt(E); 2259 } 2260 for (auto *E : C->lhs_exprs()) { 2261 Visitor->AddStmt(E); 2262 } 2263 for (auto *E : C->rhs_exprs()) { 2264 Visitor->AddStmt(E); 2265 } 2266 for (auto *E : C->reduction_ops()) { 2267 Visitor->AddStmt(E); 2268 } 2269 } 2270 void OMPClauseEnqueue::VisitOMPTaskReductionClause( 2271 const OMPTaskReductionClause *C) { 2272 VisitOMPClauseList(C); 2273 VisitOMPClauseWithPostUpdate(C); 2274 for (auto *E : C->privates()) { 2275 Visitor->AddStmt(E); 2276 } 2277 for (auto *E : C->lhs_exprs()) { 2278 Visitor->AddStmt(E); 2279 } 2280 for (auto *E : C->rhs_exprs()) { 2281 Visitor->AddStmt(E); 2282 } 2283 for (auto *E : C->reduction_ops()) { 2284 Visitor->AddStmt(E); 2285 } 2286 } 2287 void OMPClauseEnqueue::VisitOMPInReductionClause( 2288 const OMPInReductionClause *C) { 2289 VisitOMPClauseList(C); 2290 VisitOMPClauseWithPostUpdate(C); 2291 for (auto *E : C->privates()) { 2292 Visitor->AddStmt(E); 2293 } 2294 for (auto *E : C->lhs_exprs()) { 2295 Visitor->AddStmt(E); 2296 } 2297 for (auto *E : C->rhs_exprs()) { 2298 Visitor->AddStmt(E); 2299 } 2300 for (auto *E : C->reduction_ops()) { 2301 Visitor->AddStmt(E); 2302 } 2303 for (auto *E : C->taskgroup_descriptors()) 2304 Visitor->AddStmt(E); 2305 } 2306 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) { 2307 VisitOMPClauseList(C); 2308 VisitOMPClauseWithPostUpdate(C); 2309 for (const auto *E : C->privates()) { 2310 Visitor->AddStmt(E); 2311 } 2312 for (const auto *E : C->inits()) { 2313 Visitor->AddStmt(E); 2314 } 2315 for (const auto *E : C->updates()) { 2316 Visitor->AddStmt(E); 2317 } 2318 for (const auto *E : C->finals()) { 2319 Visitor->AddStmt(E); 2320 } 2321 Visitor->AddStmt(C->getStep()); 2322 Visitor->AddStmt(C->getCalcStep()); 2323 } 2324 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) { 2325 VisitOMPClauseList(C); 2326 Visitor->AddStmt(C->getAlignment()); 2327 } 2328 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) { 2329 VisitOMPClauseList(C); 2330 for (auto *E : C->source_exprs()) { 2331 Visitor->AddStmt(E); 2332 } 2333 for (auto *E : C->destination_exprs()) { 2334 Visitor->AddStmt(E); 2335 } 2336 for (auto *E : C->assignment_ops()) { 2337 Visitor->AddStmt(E); 2338 } 2339 } 2340 void 2341 OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) { 2342 VisitOMPClauseList(C); 2343 for (auto *E : C->source_exprs()) { 2344 Visitor->AddStmt(E); 2345 } 2346 for (auto *E : C->destination_exprs()) { 2347 Visitor->AddStmt(E); 2348 } 2349 for (auto *E : C->assignment_ops()) { 2350 Visitor->AddStmt(E); 2351 } 2352 } 2353 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) { 2354 VisitOMPClauseList(C); 2355 } 2356 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) { 2357 VisitOMPClauseList(C); 2358 } 2359 void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) { 2360 VisitOMPClauseList(C); 2361 } 2362 void OMPClauseEnqueue::VisitOMPDistScheduleClause( 2363 const OMPDistScheduleClause *C) { 2364 VisitOMPClauseWithPreInit(C); 2365 Visitor->AddStmt(C->getChunkSize()); 2366 } 2367 void OMPClauseEnqueue::VisitOMPDefaultmapClause( 2368 const OMPDefaultmapClause * /*C*/) {} 2369 void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) { 2370 VisitOMPClauseList(C); 2371 } 2372 void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) { 2373 VisitOMPClauseList(C); 2374 } 2375 void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) { 2376 VisitOMPClauseList(C); 2377 } 2378 void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) { 2379 VisitOMPClauseList(C); 2380 } 2381 } 2382 2383 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) { 2384 unsigned size = WL.size(); 2385 OMPClauseEnqueue Visitor(this); 2386 Visitor.Visit(S); 2387 if (size == WL.size()) 2388 return; 2389 // Now reverse the entries we just added. This will match the DFS 2390 // ordering performed by the worklist. 2391 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 2392 std::reverse(I, E); 2393 } 2394 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) { 2395 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent)); 2396 } 2397 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) { 2398 AddDecl(B->getBlockDecl()); 2399 } 2400 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 2401 EnqueueChildren(E); 2402 AddTypeLoc(E->getTypeSourceInfo()); 2403 } 2404 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) { 2405 for (auto &I : llvm::reverse(S->body())) 2406 AddStmt(I); 2407 } 2408 void EnqueueVisitor:: 2409 VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) { 2410 AddStmt(S->getSubStmt()); 2411 AddDeclarationNameInfo(S); 2412 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc()) 2413 AddNestedNameSpecifierLoc(QualifierLoc); 2414 } 2415 2416 void EnqueueVisitor:: 2417 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) { 2418 if (E->hasExplicitTemplateArgs()) 2419 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); 2420 AddDeclarationNameInfo(E); 2421 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 2422 AddNestedNameSpecifierLoc(QualifierLoc); 2423 if (!E->isImplicitAccess()) 2424 AddStmt(E->getBase()); 2425 } 2426 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) { 2427 // Enqueue the initializer , if any. 2428 AddStmt(E->getInitializer()); 2429 // Enqueue the array size, if any. 2430 AddStmt(E->getArraySize()); 2431 // Enqueue the allocated type. 2432 AddTypeLoc(E->getAllocatedTypeSourceInfo()); 2433 // Enqueue the placement arguments. 2434 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I) 2435 AddStmt(E->getPlacementArg(I-1)); 2436 } 2437 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) { 2438 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I) 2439 AddStmt(CE->getArg(I-1)); 2440 AddStmt(CE->getCallee()); 2441 AddStmt(CE->getArg(0)); 2442 } 2443 void EnqueueVisitor::VisitCXXPseudoDestructorExpr( 2444 const CXXPseudoDestructorExpr *E) { 2445 // Visit the name of the type being destroyed. 2446 AddTypeLoc(E->getDestroyedTypeInfo()); 2447 // Visit the scope type that looks disturbingly like the nested-name-specifier 2448 // but isn't. 2449 AddTypeLoc(E->getScopeTypeInfo()); 2450 // Visit the nested-name-specifier. 2451 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 2452 AddNestedNameSpecifierLoc(QualifierLoc); 2453 // Visit base expression. 2454 AddStmt(E->getBase()); 2455 } 2456 void EnqueueVisitor::VisitCXXScalarValueInitExpr( 2457 const CXXScalarValueInitExpr *E) { 2458 AddTypeLoc(E->getTypeSourceInfo()); 2459 } 2460 void EnqueueVisitor::VisitCXXTemporaryObjectExpr( 2461 const CXXTemporaryObjectExpr *E) { 2462 EnqueueChildren(E); 2463 AddTypeLoc(E->getTypeSourceInfo()); 2464 } 2465 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 2466 EnqueueChildren(E); 2467 if (E->isTypeOperand()) 2468 AddTypeLoc(E->getTypeOperandSourceInfo()); 2469 } 2470 2471 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr( 2472 const CXXUnresolvedConstructExpr *E) { 2473 EnqueueChildren(E); 2474 AddTypeLoc(E->getTypeSourceInfo()); 2475 } 2476 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 2477 EnqueueChildren(E); 2478 if (E->isTypeOperand()) 2479 AddTypeLoc(E->getTypeOperandSourceInfo()); 2480 } 2481 2482 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) { 2483 EnqueueChildren(S); 2484 AddDecl(S->getExceptionDecl()); 2485 } 2486 2487 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 2488 AddStmt(S->getBody()); 2489 AddStmt(S->getRangeInit()); 2490 AddDecl(S->getLoopVariable()); 2491 } 2492 2493 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) { 2494 if (DR->hasExplicitTemplateArgs()) 2495 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs()); 2496 WL.push_back(DeclRefExprParts(DR, Parent)); 2497 } 2498 void EnqueueVisitor::VisitDependentScopeDeclRefExpr( 2499 const DependentScopeDeclRefExpr *E) { 2500 if (E->hasExplicitTemplateArgs()) 2501 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); 2502 AddDeclarationNameInfo(E); 2503 AddNestedNameSpecifierLoc(E->getQualifierLoc()); 2504 } 2505 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) { 2506 unsigned size = WL.size(); 2507 bool isFirst = true; 2508 for (const auto *D : S->decls()) { 2509 AddDecl(D, isFirst); 2510 isFirst = false; 2511 } 2512 if (size == WL.size()) 2513 return; 2514 // Now reverse the entries we just added. This will match the DFS 2515 // ordering performed by the worklist. 2516 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 2517 std::reverse(I, E); 2518 } 2519 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) { 2520 AddStmt(E->getInit()); 2521 for (const DesignatedInitExpr::Designator &D : 2522 llvm::reverse(E->designators())) { 2523 if (D.isFieldDesignator()) { 2524 if (FieldDecl *Field = D.getField()) 2525 AddMemberRef(Field, D.getFieldLoc()); 2526 continue; 2527 } 2528 if (D.isArrayDesignator()) { 2529 AddStmt(E->getArrayIndex(D)); 2530 continue; 2531 } 2532 assert(D.isArrayRangeDesignator() && "Unknown designator kind"); 2533 AddStmt(E->getArrayRangeEnd(D)); 2534 AddStmt(E->getArrayRangeStart(D)); 2535 } 2536 } 2537 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) { 2538 EnqueueChildren(E); 2539 AddTypeLoc(E->getTypeInfoAsWritten()); 2540 } 2541 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) { 2542 AddStmt(FS->getBody()); 2543 AddStmt(FS->getInc()); 2544 AddStmt(FS->getCond()); 2545 AddDecl(FS->getConditionVariable()); 2546 AddStmt(FS->getInit()); 2547 } 2548 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) { 2549 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent)); 2550 } 2551 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) { 2552 AddStmt(If->getElse()); 2553 AddStmt(If->getThen()); 2554 AddStmt(If->getCond()); 2555 AddDecl(If->getConditionVariable()); 2556 } 2557 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) { 2558 // We care about the syntactic form of the initializer list, only. 2559 if (InitListExpr *Syntactic = IE->getSyntacticForm()) 2560 IE = Syntactic; 2561 EnqueueChildren(IE); 2562 } 2563 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) { 2564 WL.push_back(MemberExprParts(M, Parent)); 2565 2566 // If the base of the member access expression is an implicit 'this', don't 2567 // visit it. 2568 // FIXME: If we ever want to show these implicit accesses, this will be 2569 // unfortunate. However, clang_getCursor() relies on this behavior. 2570 if (M->isImplicitAccess()) 2571 return; 2572 2573 // Ignore base anonymous struct/union fields, otherwise they will shadow the 2574 // real field that that we are interested in. 2575 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) { 2576 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) { 2577 if (FD->isAnonymousStructOrUnion()) { 2578 AddStmt(SubME->getBase()); 2579 return; 2580 } 2581 } 2582 } 2583 2584 AddStmt(M->getBase()); 2585 } 2586 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 2587 AddTypeLoc(E->getEncodedTypeSourceInfo()); 2588 } 2589 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) { 2590 EnqueueChildren(M); 2591 AddTypeLoc(M->getClassReceiverTypeInfo()); 2592 } 2593 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) { 2594 // Visit the components of the offsetof expression. 2595 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) { 2596 const OffsetOfNode &Node = E->getComponent(I-1); 2597 switch (Node.getKind()) { 2598 case OffsetOfNode::Array: 2599 AddStmt(E->getIndexExpr(Node.getArrayExprIndex())); 2600 break; 2601 case OffsetOfNode::Field: 2602 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd()); 2603 break; 2604 case OffsetOfNode::Identifier: 2605 case OffsetOfNode::Base: 2606 continue; 2607 } 2608 } 2609 // Visit the type into which we're computing the offset. 2610 AddTypeLoc(E->getTypeSourceInfo()); 2611 } 2612 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) { 2613 if (E->hasExplicitTemplateArgs()) 2614 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); 2615 WL.push_back(OverloadExprParts(E, Parent)); 2616 } 2617 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr( 2618 const UnaryExprOrTypeTraitExpr *E) { 2619 EnqueueChildren(E); 2620 if (E->isArgumentType()) 2621 AddTypeLoc(E->getArgumentTypeInfo()); 2622 } 2623 void EnqueueVisitor::VisitStmt(const Stmt *S) { 2624 EnqueueChildren(S); 2625 } 2626 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) { 2627 AddStmt(S->getBody()); 2628 AddStmt(S->getCond()); 2629 AddDecl(S->getConditionVariable()); 2630 } 2631 2632 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) { 2633 AddStmt(W->getBody()); 2634 AddStmt(W->getCond()); 2635 AddDecl(W->getConditionVariable()); 2636 } 2637 2638 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) { 2639 for (unsigned I = E->getNumArgs(); I > 0; --I) 2640 AddTypeLoc(E->getArg(I-1)); 2641 } 2642 2643 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 2644 AddTypeLoc(E->getQueriedTypeSourceInfo()); 2645 } 2646 2647 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 2648 EnqueueChildren(E); 2649 } 2650 2651 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) { 2652 VisitOverloadExpr(U); 2653 if (!U->isImplicitAccess()) 2654 AddStmt(U->getBase()); 2655 } 2656 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) { 2657 AddStmt(E->getSubExpr()); 2658 AddTypeLoc(E->getWrittenTypeInfo()); 2659 } 2660 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 2661 WL.push_back(SizeOfPackExprParts(E, Parent)); 2662 } 2663 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 2664 // If the opaque value has a source expression, just transparently 2665 // visit that. This is useful for (e.g.) pseudo-object expressions. 2666 if (Expr *SourceExpr = E->getSourceExpr()) 2667 return Visit(SourceExpr); 2668 } 2669 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) { 2670 AddStmt(E->getBody()); 2671 WL.push_back(LambdaExprParts(E, Parent)); 2672 } 2673 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 2674 // Treat the expression like its syntactic form. 2675 Visit(E->getSyntacticForm()); 2676 } 2677 2678 void EnqueueVisitor::VisitOMPExecutableDirective( 2679 const OMPExecutableDirective *D) { 2680 EnqueueChildren(D); 2681 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(), 2682 E = D->clauses().end(); 2683 I != E; ++I) 2684 EnqueueChildren(*I); 2685 } 2686 2687 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) { 2688 VisitOMPExecutableDirective(D); 2689 } 2690 2691 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) { 2692 VisitOMPExecutableDirective(D); 2693 } 2694 2695 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) { 2696 VisitOMPLoopDirective(D); 2697 } 2698 2699 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) { 2700 VisitOMPLoopDirective(D); 2701 } 2702 2703 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) { 2704 VisitOMPLoopDirective(D); 2705 } 2706 2707 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) { 2708 VisitOMPExecutableDirective(D); 2709 } 2710 2711 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) { 2712 VisitOMPExecutableDirective(D); 2713 } 2714 2715 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) { 2716 VisitOMPExecutableDirective(D); 2717 } 2718 2719 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) { 2720 VisitOMPExecutableDirective(D); 2721 } 2722 2723 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) { 2724 VisitOMPExecutableDirective(D); 2725 AddDeclarationNameInfo(D); 2726 } 2727 2728 void 2729 EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) { 2730 VisitOMPLoopDirective(D); 2731 } 2732 2733 void EnqueueVisitor::VisitOMPParallelForSimdDirective( 2734 const OMPParallelForSimdDirective *D) { 2735 VisitOMPLoopDirective(D); 2736 } 2737 2738 void EnqueueVisitor::VisitOMPParallelSectionsDirective( 2739 const OMPParallelSectionsDirective *D) { 2740 VisitOMPExecutableDirective(D); 2741 } 2742 2743 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) { 2744 VisitOMPExecutableDirective(D); 2745 } 2746 2747 void 2748 EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) { 2749 VisitOMPExecutableDirective(D); 2750 } 2751 2752 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) { 2753 VisitOMPExecutableDirective(D); 2754 } 2755 2756 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) { 2757 VisitOMPExecutableDirective(D); 2758 } 2759 2760 void EnqueueVisitor::VisitOMPTaskgroupDirective( 2761 const OMPTaskgroupDirective *D) { 2762 VisitOMPExecutableDirective(D); 2763 if (const Expr *E = D->getReductionRef()) 2764 VisitStmt(E); 2765 } 2766 2767 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) { 2768 VisitOMPExecutableDirective(D); 2769 } 2770 2771 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) { 2772 VisitOMPExecutableDirective(D); 2773 } 2774 2775 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) { 2776 VisitOMPExecutableDirective(D); 2777 } 2778 2779 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) { 2780 VisitOMPExecutableDirective(D); 2781 } 2782 2783 void EnqueueVisitor::VisitOMPTargetDataDirective(const 2784 OMPTargetDataDirective *D) { 2785 VisitOMPExecutableDirective(D); 2786 } 2787 2788 void EnqueueVisitor::VisitOMPTargetEnterDataDirective( 2789 const OMPTargetEnterDataDirective *D) { 2790 VisitOMPExecutableDirective(D); 2791 } 2792 2793 void EnqueueVisitor::VisitOMPTargetExitDataDirective( 2794 const OMPTargetExitDataDirective *D) { 2795 VisitOMPExecutableDirective(D); 2796 } 2797 2798 void EnqueueVisitor::VisitOMPTargetParallelDirective( 2799 const OMPTargetParallelDirective *D) { 2800 VisitOMPExecutableDirective(D); 2801 } 2802 2803 void EnqueueVisitor::VisitOMPTargetParallelForDirective( 2804 const OMPTargetParallelForDirective *D) { 2805 VisitOMPLoopDirective(D); 2806 } 2807 2808 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) { 2809 VisitOMPExecutableDirective(D); 2810 } 2811 2812 void EnqueueVisitor::VisitOMPCancellationPointDirective( 2813 const OMPCancellationPointDirective *D) { 2814 VisitOMPExecutableDirective(D); 2815 } 2816 2817 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) { 2818 VisitOMPExecutableDirective(D); 2819 } 2820 2821 void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) { 2822 VisitOMPLoopDirective(D); 2823 } 2824 2825 void EnqueueVisitor::VisitOMPTaskLoopSimdDirective( 2826 const OMPTaskLoopSimdDirective *D) { 2827 VisitOMPLoopDirective(D); 2828 } 2829 2830 void EnqueueVisitor::VisitOMPDistributeDirective( 2831 const OMPDistributeDirective *D) { 2832 VisitOMPLoopDirective(D); 2833 } 2834 2835 void EnqueueVisitor::VisitOMPDistributeParallelForDirective( 2836 const OMPDistributeParallelForDirective *D) { 2837 VisitOMPLoopDirective(D); 2838 } 2839 2840 void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective( 2841 const OMPDistributeParallelForSimdDirective *D) { 2842 VisitOMPLoopDirective(D); 2843 } 2844 2845 void EnqueueVisitor::VisitOMPDistributeSimdDirective( 2846 const OMPDistributeSimdDirective *D) { 2847 VisitOMPLoopDirective(D); 2848 } 2849 2850 void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective( 2851 const OMPTargetParallelForSimdDirective *D) { 2852 VisitOMPLoopDirective(D); 2853 } 2854 2855 void EnqueueVisitor::VisitOMPTargetSimdDirective( 2856 const OMPTargetSimdDirective *D) { 2857 VisitOMPLoopDirective(D); 2858 } 2859 2860 void EnqueueVisitor::VisitOMPTeamsDistributeDirective( 2861 const OMPTeamsDistributeDirective *D) { 2862 VisitOMPLoopDirective(D); 2863 } 2864 2865 void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective( 2866 const OMPTeamsDistributeSimdDirective *D) { 2867 VisitOMPLoopDirective(D); 2868 } 2869 2870 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective( 2871 const OMPTeamsDistributeParallelForSimdDirective *D) { 2872 VisitOMPLoopDirective(D); 2873 } 2874 2875 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective( 2876 const OMPTeamsDistributeParallelForDirective *D) { 2877 VisitOMPLoopDirective(D); 2878 } 2879 2880 void EnqueueVisitor::VisitOMPTargetTeamsDirective( 2881 const OMPTargetTeamsDirective *D) { 2882 VisitOMPExecutableDirective(D); 2883 } 2884 2885 void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective( 2886 const OMPTargetTeamsDistributeDirective *D) { 2887 VisitOMPLoopDirective(D); 2888 } 2889 2890 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective( 2891 const OMPTargetTeamsDistributeParallelForDirective *D) { 2892 VisitOMPLoopDirective(D); 2893 } 2894 2895 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective( 2896 const OMPTargetTeamsDistributeParallelForSimdDirective *D) { 2897 VisitOMPLoopDirective(D); 2898 } 2899 2900 void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective( 2901 const OMPTargetTeamsDistributeSimdDirective *D) { 2902 VisitOMPLoopDirective(D); 2903 } 2904 2905 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) { 2906 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S); 2907 } 2908 2909 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) { 2910 if (RegionOfInterest.isValid()) { 2911 SourceRange Range = getRawCursorExtent(C); 2912 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 2913 return false; 2914 } 2915 return true; 2916 } 2917 2918 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) { 2919 while (!WL.empty()) { 2920 // Dequeue the worklist item. 2921 VisitorJob LI = WL.pop_back_val(); 2922 2923 // Set the Parent field, then back to its old value once we're done. 2924 SetParentRAII SetParent(Parent, StmtParent, LI.getParent()); 2925 2926 switch (LI.getKind()) { 2927 case VisitorJob::DeclVisitKind: { 2928 const Decl *D = cast<DeclVisit>(&LI)->get(); 2929 if (!D) 2930 continue; 2931 2932 // For now, perform default visitation for Decls. 2933 if (Visit(MakeCXCursor(D, TU, RegionOfInterest, 2934 cast<DeclVisit>(&LI)->isFirst()))) 2935 return true; 2936 2937 continue; 2938 } 2939 case VisitorJob::ExplicitTemplateArgsVisitKind: { 2940 for (const TemplateArgumentLoc &Arg : 2941 *cast<ExplicitTemplateArgsVisit>(&LI)) { 2942 if (VisitTemplateArgumentLoc(Arg)) 2943 return true; 2944 } 2945 continue; 2946 } 2947 case VisitorJob::TypeLocVisitKind: { 2948 // Perform default visitation for TypeLocs. 2949 if (Visit(cast<TypeLocVisit>(&LI)->get())) 2950 return true; 2951 continue; 2952 } 2953 case VisitorJob::LabelRefVisitKind: { 2954 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get(); 2955 if (LabelStmt *stmt = LS->getStmt()) { 2956 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(), 2957 TU))) { 2958 return true; 2959 } 2960 } 2961 continue; 2962 } 2963 2964 case VisitorJob::NestedNameSpecifierLocVisitKind: { 2965 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI); 2966 if (VisitNestedNameSpecifierLoc(V->get())) 2967 return true; 2968 continue; 2969 } 2970 2971 case VisitorJob::DeclarationNameInfoVisitKind: { 2972 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI) 2973 ->get())) 2974 return true; 2975 continue; 2976 } 2977 case VisitorJob::MemberRefVisitKind: { 2978 MemberRefVisit *V = cast<MemberRefVisit>(&LI); 2979 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU))) 2980 return true; 2981 continue; 2982 } 2983 case VisitorJob::StmtVisitKind: { 2984 const Stmt *S = cast<StmtVisit>(&LI)->get(); 2985 if (!S) 2986 continue; 2987 2988 // Update the current cursor. 2989 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest); 2990 if (!IsInRegionOfInterest(Cursor)) 2991 continue; 2992 switch (Visitor(Cursor, Parent, ClientData)) { 2993 case CXChildVisit_Break: return true; 2994 case CXChildVisit_Continue: break; 2995 case CXChildVisit_Recurse: 2996 if (PostChildrenVisitor) 2997 WL.push_back(PostChildrenVisit(nullptr, Cursor)); 2998 EnqueueWorkList(WL, S); 2999 break; 3000 } 3001 continue; 3002 } 3003 case VisitorJob::MemberExprPartsKind: { 3004 // Handle the other pieces in the MemberExpr besides the base. 3005 const MemberExpr *M = cast<MemberExprParts>(&LI)->get(); 3006 3007 // Visit the nested-name-specifier 3008 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc()) 3009 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 3010 return true; 3011 3012 // Visit the declaration name. 3013 if (VisitDeclarationNameInfo(M->getMemberNameInfo())) 3014 return true; 3015 3016 // Visit the explicitly-specified template arguments, if any. 3017 if (M->hasExplicitTemplateArgs()) { 3018 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(), 3019 *ArgEnd = Arg + M->getNumTemplateArgs(); 3020 Arg != ArgEnd; ++Arg) { 3021 if (VisitTemplateArgumentLoc(*Arg)) 3022 return true; 3023 } 3024 } 3025 continue; 3026 } 3027 case VisitorJob::DeclRefExprPartsKind: { 3028 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get(); 3029 // Visit nested-name-specifier, if present. 3030 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc()) 3031 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 3032 return true; 3033 // Visit declaration name. 3034 if (VisitDeclarationNameInfo(DR->getNameInfo())) 3035 return true; 3036 continue; 3037 } 3038 case VisitorJob::OverloadExprPartsKind: { 3039 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get(); 3040 // Visit the nested-name-specifier. 3041 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc()) 3042 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 3043 return true; 3044 // Visit the declaration name. 3045 if (VisitDeclarationNameInfo(O->getNameInfo())) 3046 return true; 3047 // Visit the overloaded declaration reference. 3048 if (Visit(MakeCursorOverloadedDeclRef(O, TU))) 3049 return true; 3050 continue; 3051 } 3052 case VisitorJob::SizeOfPackExprPartsKind: { 3053 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get(); 3054 NamedDecl *Pack = E->getPack(); 3055 if (isa<TemplateTypeParmDecl>(Pack)) { 3056 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack), 3057 E->getPackLoc(), TU))) 3058 return true; 3059 3060 continue; 3061 } 3062 3063 if (isa<TemplateTemplateParmDecl>(Pack)) { 3064 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack), 3065 E->getPackLoc(), TU))) 3066 return true; 3067 3068 continue; 3069 } 3070 3071 // Non-type template parameter packs and function parameter packs are 3072 // treated like DeclRefExpr cursors. 3073 continue; 3074 } 3075 3076 case VisitorJob::LambdaExprPartsKind: { 3077 // Visit captures. 3078 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get(); 3079 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(), 3080 CEnd = E->explicit_capture_end(); 3081 C != CEnd; ++C) { 3082 // FIXME: Lambda init-captures. 3083 if (!C->capturesVariable()) 3084 continue; 3085 3086 if (Visit(MakeCursorVariableRef(C->getCapturedVar(), 3087 C->getLocation(), 3088 TU))) 3089 return true; 3090 } 3091 3092 // Visit parameters and return type, if present. 3093 if (E->hasExplicitParameters() || E->hasExplicitResultType()) { 3094 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc(); 3095 if (E->hasExplicitParameters() && E->hasExplicitResultType()) { 3096 // Visit the whole type. 3097 if (Visit(TL)) 3098 return true; 3099 } else if (FunctionProtoTypeLoc Proto = 3100 TL.getAs<FunctionProtoTypeLoc>()) { 3101 if (E->hasExplicitParameters()) { 3102 // Visit parameters. 3103 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) 3104 if (Visit(MakeCXCursor(Proto.getParam(I), TU))) 3105 return true; 3106 } else { 3107 // Visit result type. 3108 if (Visit(Proto.getReturnLoc())) 3109 return true; 3110 } 3111 } 3112 } 3113 break; 3114 } 3115 3116 case VisitorJob::PostChildrenVisitKind: 3117 if (PostChildrenVisitor(Parent, ClientData)) 3118 return true; 3119 break; 3120 } 3121 } 3122 return false; 3123 } 3124 3125 bool CursorVisitor::Visit(const Stmt *S) { 3126 VisitorWorkList *WL = nullptr; 3127 if (!WorkListFreeList.empty()) { 3128 WL = WorkListFreeList.back(); 3129 WL->clear(); 3130 WorkListFreeList.pop_back(); 3131 } 3132 else { 3133 WL = new VisitorWorkList(); 3134 WorkListCache.push_back(WL); 3135 } 3136 EnqueueWorkList(*WL, S); 3137 bool result = RunVisitorWorkList(*WL); 3138 WorkListFreeList.push_back(WL); 3139 return result; 3140 } 3141 3142 namespace { 3143 typedef SmallVector<SourceRange, 4> RefNamePieces; 3144 RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr, 3145 const DeclarationNameInfo &NI, SourceRange QLoc, 3146 const SourceRange *TemplateArgsLoc = nullptr) { 3147 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier; 3148 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs; 3149 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece; 3150 3151 const DeclarationName::NameKind Kind = NI.getName().getNameKind(); 3152 3153 RefNamePieces Pieces; 3154 3155 if (WantQualifier && QLoc.isValid()) 3156 Pieces.push_back(QLoc); 3157 3158 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr) 3159 Pieces.push_back(NI.getLoc()); 3160 3161 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid()) 3162 Pieces.push_back(*TemplateArgsLoc); 3163 3164 if (Kind == DeclarationName::CXXOperatorName) { 3165 Pieces.push_back(SourceLocation::getFromRawEncoding( 3166 NI.getInfo().CXXOperatorName.BeginOpNameLoc)); 3167 Pieces.push_back(SourceLocation::getFromRawEncoding( 3168 NI.getInfo().CXXOperatorName.EndOpNameLoc)); 3169 } 3170 3171 if (WantSinglePiece) { 3172 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd()); 3173 Pieces.clear(); 3174 Pieces.push_back(R); 3175 } 3176 3177 return Pieces; 3178 } 3179 } 3180 3181 //===----------------------------------------------------------------------===// 3182 // Misc. API hooks. 3183 //===----------------------------------------------------------------------===// 3184 3185 static void fatal_error_handler(void *user_data, const std::string& reason, 3186 bool gen_crash_diag) { 3187 // Write the result out to stderr avoiding errs() because raw_ostreams can 3188 // call report_fatal_error. 3189 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str()); 3190 ::abort(); 3191 } 3192 3193 namespace { 3194 struct RegisterFatalErrorHandler { 3195 RegisterFatalErrorHandler() { 3196 llvm::install_fatal_error_handler(fatal_error_handler, nullptr); 3197 } 3198 }; 3199 } 3200 3201 static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce; 3202 3203 CXIndex clang_createIndex(int excludeDeclarationsFromPCH, 3204 int displayDiagnostics) { 3205 // We use crash recovery to make some of our APIs more reliable, implicitly 3206 // enable it. 3207 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY")) 3208 llvm::CrashRecoveryContext::Enable(); 3209 3210 // Look through the managed static to trigger construction of the managed 3211 // static which registers our fatal error handler. This ensures it is only 3212 // registered once. 3213 (void)*RegisterFatalErrorHandlerOnce; 3214 3215 // Initialize targets for clang module support. 3216 llvm::InitializeAllTargets(); 3217 llvm::InitializeAllTargetMCs(); 3218 llvm::InitializeAllAsmPrinters(); 3219 llvm::InitializeAllAsmParsers(); 3220 3221 CIndexer *CIdxr = new CIndexer(); 3222 3223 if (excludeDeclarationsFromPCH) 3224 CIdxr->setOnlyLocalDecls(); 3225 if (displayDiagnostics) 3226 CIdxr->setDisplayDiagnostics(); 3227 3228 if (getenv("LIBCLANG_BGPRIO_INDEX")) 3229 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | 3230 CXGlobalOpt_ThreadBackgroundPriorityForIndexing); 3231 if (getenv("LIBCLANG_BGPRIO_EDIT")) 3232 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | 3233 CXGlobalOpt_ThreadBackgroundPriorityForEditing); 3234 3235 return CIdxr; 3236 } 3237 3238 void clang_disposeIndex(CXIndex CIdx) { 3239 if (CIdx) 3240 delete static_cast<CIndexer *>(CIdx); 3241 } 3242 3243 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) { 3244 if (CIdx) 3245 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options); 3246 } 3247 3248 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) { 3249 if (CIdx) 3250 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags(); 3251 return 0; 3252 } 3253 3254 void clang_toggleCrashRecovery(unsigned isEnabled) { 3255 if (isEnabled) 3256 llvm::CrashRecoveryContext::Enable(); 3257 else 3258 llvm::CrashRecoveryContext::Disable(); 3259 } 3260 3261 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, 3262 const char *ast_filename) { 3263 CXTranslationUnit TU; 3264 enum CXErrorCode Result = 3265 clang_createTranslationUnit2(CIdx, ast_filename, &TU); 3266 (void)Result; 3267 assert((TU && Result == CXError_Success) || 3268 (!TU && Result != CXError_Success)); 3269 return TU; 3270 } 3271 3272 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx, 3273 const char *ast_filename, 3274 CXTranslationUnit *out_TU) { 3275 if (out_TU) 3276 *out_TU = nullptr; 3277 3278 if (!CIdx || !ast_filename || !out_TU) 3279 return CXError_InvalidArguments; 3280 3281 LOG_FUNC_SECTION { 3282 *Log << ast_filename; 3283 } 3284 3285 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 3286 FileSystemOptions FileSystemOpts; 3287 3288 IntrusiveRefCntPtr<DiagnosticsEngine> Diags = 3289 CompilerInstance::createDiagnostics(new DiagnosticOptions()); 3290 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile( 3291 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), 3292 ASTUnit::LoadEverything, Diags, 3293 FileSystemOpts, /*UseDebugInfo=*/false, 3294 CXXIdx->getOnlyLocalDecls(), None, 3295 /*CaptureDiagnostics=*/true, 3296 /*AllowPCHWithCompilerErrors=*/true, 3297 /*UserFilesAreVolatile=*/true); 3298 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU)); 3299 return *out_TU ? CXError_Success : CXError_Failure; 3300 } 3301 3302 unsigned clang_defaultEditingTranslationUnitOptions() { 3303 return CXTranslationUnit_PrecompiledPreamble | 3304 CXTranslationUnit_CacheCompletionResults; 3305 } 3306 3307 CXTranslationUnit 3308 clang_createTranslationUnitFromSourceFile(CXIndex CIdx, 3309 const char *source_filename, 3310 int num_command_line_args, 3311 const char * const *command_line_args, 3312 unsigned num_unsaved_files, 3313 struct CXUnsavedFile *unsaved_files) { 3314 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord; 3315 return clang_parseTranslationUnit(CIdx, source_filename, 3316 command_line_args, num_command_line_args, 3317 unsaved_files, num_unsaved_files, 3318 Options); 3319 } 3320 3321 static CXErrorCode 3322 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename, 3323 const char *const *command_line_args, 3324 int num_command_line_args, 3325 ArrayRef<CXUnsavedFile> unsaved_files, 3326 unsigned options, CXTranslationUnit *out_TU) { 3327 // Set up the initial return values. 3328 if (out_TU) 3329 *out_TU = nullptr; 3330 3331 // Check arguments. 3332 if (!CIdx || !out_TU) 3333 return CXError_InvalidArguments; 3334 3335 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 3336 3337 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 3338 setThreadBackgroundPriority(); 3339 3340 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; 3341 bool CreatePreambleOnFirstParse = 3342 options & CXTranslationUnit_CreatePreambleOnFirstParse; 3343 // FIXME: Add a flag for modules. 3344 TranslationUnitKind TUKind 3345 = (options & (CXTranslationUnit_Incomplete | 3346 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete; 3347 bool CacheCodeCompletionResults 3348 = options & CXTranslationUnit_CacheCompletionResults; 3349 bool IncludeBriefCommentsInCodeCompletion 3350 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion; 3351 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies; 3352 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse; 3353 bool ForSerialization = options & CXTranslationUnit_ForSerialization; 3354 3355 // Configure the diagnostics. 3356 IntrusiveRefCntPtr<DiagnosticsEngine> 3357 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions)); 3358 3359 if (options & CXTranslationUnit_KeepGoing) 3360 Diags->setSuppressAfterFatalError(false); 3361 3362 // Recover resources if we crash before exiting this function. 3363 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, 3364 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> > 3365 DiagCleanup(Diags.get()); 3366 3367 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles( 3368 new std::vector<ASTUnit::RemappedFile>()); 3369 3370 // Recover resources if we crash before exiting this function. 3371 llvm::CrashRecoveryContextCleanupRegistrar< 3372 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get()); 3373 3374 for (auto &UF : unsaved_files) { 3375 std::unique_ptr<llvm::MemoryBuffer> MB = 3376 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); 3377 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release())); 3378 } 3379 3380 std::unique_ptr<std::vector<const char *>> Args( 3381 new std::vector<const char *>()); 3382 3383 // Recover resources if we crash before exiting this method. 3384 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> > 3385 ArgsCleanup(Args.get()); 3386 3387 // Since the Clang C library is primarily used by batch tools dealing with 3388 // (often very broken) source code, where spell-checking can have a 3389 // significant negative impact on performance (particularly when 3390 // precompiled headers are involved), we disable it by default. 3391 // Only do this if we haven't found a spell-checking-related argument. 3392 bool FoundSpellCheckingArgument = false; 3393 for (int I = 0; I != num_command_line_args; ++I) { 3394 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 || 3395 strcmp(command_line_args[I], "-fspell-checking") == 0) { 3396 FoundSpellCheckingArgument = true; 3397 break; 3398 } 3399 } 3400 Args->insert(Args->end(), command_line_args, 3401 command_line_args + num_command_line_args); 3402 3403 if (!FoundSpellCheckingArgument) 3404 Args->insert(Args->begin() + 1, "-fno-spell-checking"); 3405 3406 // The 'source_filename' argument is optional. If the caller does not 3407 // specify it then it is assumed that the source file is specified 3408 // in the actual argument list. 3409 // Put the source file after command_line_args otherwise if '-x' flag is 3410 // present it will be unused. 3411 if (source_filename) 3412 Args->push_back(source_filename); 3413 3414 // Do we need the detailed preprocessing record? 3415 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 3416 Args->push_back("-Xclang"); 3417 Args->push_back("-detailed-preprocessing-record"); 3418 } 3419 3420 // Suppress any editor placeholder diagnostics. 3421 Args->push_back("-fallow-editor-placeholders"); 3422 3423 unsigned NumErrors = Diags->getClient()->getNumErrors(); 3424 std::unique_ptr<ASTUnit> ErrUnit; 3425 // Unless the user specified that they want the preamble on the first parse 3426 // set it up to be created on the first reparse. This makes the first parse 3427 // faster, trading for a slower (first) reparse. 3428 unsigned PrecompilePreambleAfterNParses = 3429 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse; 3430 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine( 3431 Args->data(), Args->data() + Args->size(), 3432 CXXIdx->getPCHContainerOperations(), Diags, 3433 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(), 3434 /*CaptureDiagnostics=*/true, *RemappedFiles.get(), 3435 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses, 3436 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion, 3437 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse, 3438 /*UserFilesAreVolatile=*/true, ForSerialization, 3439 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(), 3440 &ErrUnit)); 3441 3442 // Early failures in LoadFromCommandLine may return with ErrUnit unset. 3443 if (!Unit && !ErrUnit) 3444 return CXError_ASTReadError; 3445 3446 if (NumErrors != Diags->getClient()->getNumErrors()) { 3447 // Make sure to check that 'Unit' is non-NULL. 3448 if (CXXIdx->getDisplayDiagnostics()) 3449 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get()); 3450 } 3451 3452 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get())) 3453 return CXError_ASTReadError; 3454 3455 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit)); 3456 return *out_TU ? CXError_Success : CXError_Failure; 3457 } 3458 3459 CXTranslationUnit 3460 clang_parseTranslationUnit(CXIndex CIdx, 3461 const char *source_filename, 3462 const char *const *command_line_args, 3463 int num_command_line_args, 3464 struct CXUnsavedFile *unsaved_files, 3465 unsigned num_unsaved_files, 3466 unsigned options) { 3467 CXTranslationUnit TU; 3468 enum CXErrorCode Result = clang_parseTranslationUnit2( 3469 CIdx, source_filename, command_line_args, num_command_line_args, 3470 unsaved_files, num_unsaved_files, options, &TU); 3471 (void)Result; 3472 assert((TU && Result == CXError_Success) || 3473 (!TU && Result != CXError_Success)); 3474 return TU; 3475 } 3476 3477 enum CXErrorCode clang_parseTranslationUnit2( 3478 CXIndex CIdx, const char *source_filename, 3479 const char *const *command_line_args, int num_command_line_args, 3480 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, 3481 unsigned options, CXTranslationUnit *out_TU) { 3482 SmallVector<const char *, 4> Args; 3483 Args.push_back("clang"); 3484 Args.append(command_line_args, command_line_args + num_command_line_args); 3485 return clang_parseTranslationUnit2FullArgv( 3486 CIdx, source_filename, Args.data(), Args.size(), unsaved_files, 3487 num_unsaved_files, options, out_TU); 3488 } 3489 3490 enum CXErrorCode clang_parseTranslationUnit2FullArgv( 3491 CXIndex CIdx, const char *source_filename, 3492 const char *const *command_line_args, int num_command_line_args, 3493 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, 3494 unsigned options, CXTranslationUnit *out_TU) { 3495 LOG_FUNC_SECTION { 3496 *Log << source_filename << ": "; 3497 for (int i = 0; i != num_command_line_args; ++i) 3498 *Log << command_line_args[i] << " "; 3499 } 3500 3501 if (num_unsaved_files && !unsaved_files) 3502 return CXError_InvalidArguments; 3503 3504 CXErrorCode result = CXError_Failure; 3505 auto ParseTranslationUnitImpl = [=, &result] { 3506 result = clang_parseTranslationUnit_Impl( 3507 CIdx, source_filename, command_line_args, num_command_line_args, 3508 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU); 3509 }; 3510 3511 if (getenv("LIBCLANG_NOTHREADS")) { 3512 ParseTranslationUnitImpl(); 3513 return result; 3514 } 3515 3516 llvm::CrashRecoveryContext CRC; 3517 3518 if (!RunSafely(CRC, ParseTranslationUnitImpl)) { 3519 fprintf(stderr, "libclang: crash detected during parsing: {\n"); 3520 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 3521 fprintf(stderr, " 'command_line_args' : ["); 3522 for (int i = 0; i != num_command_line_args; ++i) { 3523 if (i) 3524 fprintf(stderr, ", "); 3525 fprintf(stderr, "'%s'", command_line_args[i]); 3526 } 3527 fprintf(stderr, "],\n"); 3528 fprintf(stderr, " 'unsaved_files' : ["); 3529 for (unsigned i = 0; i != num_unsaved_files; ++i) { 3530 if (i) 3531 fprintf(stderr, ", "); 3532 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 3533 unsaved_files[i].Length); 3534 } 3535 fprintf(stderr, "],\n"); 3536 fprintf(stderr, " 'options' : %d,\n", options); 3537 fprintf(stderr, "}\n"); 3538 3539 return CXError_Crashed; 3540 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 3541 if (CXTranslationUnit *TU = out_TU) 3542 PrintLibclangResourceUsage(*TU); 3543 } 3544 3545 return result; 3546 } 3547 3548 CXString clang_Type_getObjCEncoding(CXType CT) { 3549 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]); 3550 ASTContext &Ctx = getASTUnit(tu)->getASTContext(); 3551 std::string encoding; 3552 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]), 3553 encoding); 3554 3555 return cxstring::createDup(encoding); 3556 } 3557 3558 static const IdentifierInfo *getMacroIdentifier(CXCursor C) { 3559 if (C.kind == CXCursor_MacroDefinition) { 3560 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C)) 3561 return MDR->getName(); 3562 } else if (C.kind == CXCursor_MacroExpansion) { 3563 MacroExpansionCursor ME = getCursorMacroExpansion(C); 3564 return ME.getName(); 3565 } 3566 return nullptr; 3567 } 3568 3569 unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) { 3570 const IdentifierInfo *II = getMacroIdentifier(C); 3571 if (!II) { 3572 return false; 3573 } 3574 ASTUnit *ASTU = getCursorASTUnit(C); 3575 Preprocessor &PP = ASTU->getPreprocessor(); 3576 if (const MacroInfo *MI = PP.getMacroInfo(II)) 3577 return MI->isFunctionLike(); 3578 return false; 3579 } 3580 3581 unsigned clang_Cursor_isMacroBuiltin(CXCursor C) { 3582 const IdentifierInfo *II = getMacroIdentifier(C); 3583 if (!II) { 3584 return false; 3585 } 3586 ASTUnit *ASTU = getCursorASTUnit(C); 3587 Preprocessor &PP = ASTU->getPreprocessor(); 3588 if (const MacroInfo *MI = PP.getMacroInfo(II)) 3589 return MI->isBuiltinMacro(); 3590 return false; 3591 } 3592 3593 unsigned clang_Cursor_isFunctionInlined(CXCursor C) { 3594 const Decl *D = getCursorDecl(C); 3595 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 3596 if (!FD) { 3597 return false; 3598 } 3599 return FD->isInlined(); 3600 } 3601 3602 static StringLiteral* getCFSTR_value(CallExpr *callExpr) { 3603 if (callExpr->getNumArgs() != 1) { 3604 return nullptr; 3605 } 3606 3607 StringLiteral *S = nullptr; 3608 auto *arg = callExpr->getArg(0); 3609 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) { 3610 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg); 3611 auto *subExpr = I->getSubExprAsWritten(); 3612 3613 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){ 3614 return nullptr; 3615 } 3616 3617 S = static_cast<StringLiteral *>(I->getSubExprAsWritten()); 3618 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) { 3619 S = static_cast<StringLiteral *>(callExpr->getArg(0)); 3620 } else { 3621 return nullptr; 3622 } 3623 return S; 3624 } 3625 3626 struct ExprEvalResult { 3627 CXEvalResultKind EvalType; 3628 union { 3629 unsigned long long unsignedVal; 3630 long long intVal; 3631 double floatVal; 3632 char *stringVal; 3633 } EvalData; 3634 bool IsUnsignedInt; 3635 ~ExprEvalResult() { 3636 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float && 3637 EvalType != CXEval_Int) { 3638 delete EvalData.stringVal; 3639 } 3640 } 3641 }; 3642 3643 void clang_EvalResult_dispose(CXEvalResult E) { 3644 delete static_cast<ExprEvalResult *>(E); 3645 } 3646 3647 CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) { 3648 if (!E) { 3649 return CXEval_UnExposed; 3650 } 3651 return ((ExprEvalResult *)E)->EvalType; 3652 } 3653 3654 int clang_EvalResult_getAsInt(CXEvalResult E) { 3655 return clang_EvalResult_getAsLongLong(E); 3656 } 3657 3658 long long clang_EvalResult_getAsLongLong(CXEvalResult E) { 3659 if (!E) { 3660 return 0; 3661 } 3662 ExprEvalResult *Result = (ExprEvalResult*)E; 3663 if (Result->IsUnsignedInt) 3664 return Result->EvalData.unsignedVal; 3665 return Result->EvalData.intVal; 3666 } 3667 3668 unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) { 3669 return ((ExprEvalResult *)E)->IsUnsignedInt; 3670 } 3671 3672 unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) { 3673 if (!E) { 3674 return 0; 3675 } 3676 3677 ExprEvalResult *Result = (ExprEvalResult*)E; 3678 if (Result->IsUnsignedInt) 3679 return Result->EvalData.unsignedVal; 3680 return Result->EvalData.intVal; 3681 } 3682 3683 double clang_EvalResult_getAsDouble(CXEvalResult E) { 3684 if (!E) { 3685 return 0; 3686 } 3687 return ((ExprEvalResult *)E)->EvalData.floatVal; 3688 } 3689 3690 const char* clang_EvalResult_getAsStr(CXEvalResult E) { 3691 if (!E) { 3692 return nullptr; 3693 } 3694 return ((ExprEvalResult *)E)->EvalData.stringVal; 3695 } 3696 3697 static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) { 3698 Expr::EvalResult ER; 3699 ASTContext &ctx = getCursorContext(C); 3700 if (!expr) 3701 return nullptr; 3702 3703 expr = expr->IgnoreParens(); 3704 if (!expr->EvaluateAsRValue(ER, ctx)) 3705 return nullptr; 3706 3707 QualType rettype; 3708 CallExpr *callExpr; 3709 auto result = llvm::make_unique<ExprEvalResult>(); 3710 result->EvalType = CXEval_UnExposed; 3711 result->IsUnsignedInt = false; 3712 3713 if (ER.Val.isInt()) { 3714 result->EvalType = CXEval_Int; 3715 3716 auto& val = ER.Val.getInt(); 3717 if (val.isUnsigned()) { 3718 result->IsUnsignedInt = true; 3719 result->EvalData.unsignedVal = val.getZExtValue(); 3720 } else { 3721 result->EvalData.intVal = val.getExtValue(); 3722 } 3723 3724 return result.release(); 3725 } 3726 3727 if (ER.Val.isFloat()) { 3728 llvm::SmallVector<char, 100> Buffer; 3729 ER.Val.getFloat().toString(Buffer); 3730 std::string floatStr(Buffer.data(), Buffer.size()); 3731 result->EvalType = CXEval_Float; 3732 bool ignored; 3733 llvm::APFloat apFloat = ER.Val.getFloat(); 3734 apFloat.convert(llvm::APFloat::IEEEdouble(), 3735 llvm::APFloat::rmNearestTiesToEven, &ignored); 3736 result->EvalData.floatVal = apFloat.convertToDouble(); 3737 return result.release(); 3738 } 3739 3740 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) { 3741 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr); 3742 auto *subExpr = I->getSubExprAsWritten(); 3743 if (subExpr->getStmtClass() == Stmt::StringLiteralClass || 3744 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) { 3745 const StringLiteral *StrE = nullptr; 3746 const ObjCStringLiteral *ObjCExpr; 3747 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr); 3748 3749 if (ObjCExpr) { 3750 StrE = ObjCExpr->getString(); 3751 result->EvalType = CXEval_ObjCStrLiteral; 3752 } else { 3753 StrE = cast<StringLiteral>(I->getSubExprAsWritten()); 3754 result->EvalType = CXEval_StrLiteral; 3755 } 3756 3757 std::string strRef(StrE->getString().str()); 3758 result->EvalData.stringVal = new char[strRef.size() + 1]; 3759 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), 3760 strRef.size()); 3761 result->EvalData.stringVal[strRef.size()] = '\0'; 3762 return result.release(); 3763 } 3764 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass || 3765 expr->getStmtClass() == Stmt::StringLiteralClass) { 3766 const StringLiteral *StrE = nullptr; 3767 const ObjCStringLiteral *ObjCExpr; 3768 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr); 3769 3770 if (ObjCExpr) { 3771 StrE = ObjCExpr->getString(); 3772 result->EvalType = CXEval_ObjCStrLiteral; 3773 } else { 3774 StrE = cast<StringLiteral>(expr); 3775 result->EvalType = CXEval_StrLiteral; 3776 } 3777 3778 std::string strRef(StrE->getString().str()); 3779 result->EvalData.stringVal = new char[strRef.size() + 1]; 3780 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size()); 3781 result->EvalData.stringVal[strRef.size()] = '\0'; 3782 return result.release(); 3783 } 3784 3785 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) { 3786 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr); 3787 3788 rettype = CC->getType(); 3789 if (rettype.getAsString() == "CFStringRef" && 3790 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) { 3791 3792 callExpr = static_cast<CallExpr *>(CC->getSubExpr()); 3793 StringLiteral *S = getCFSTR_value(callExpr); 3794 if (S) { 3795 std::string strLiteral(S->getString().str()); 3796 result->EvalType = CXEval_CFStr; 3797 3798 result->EvalData.stringVal = new char[strLiteral.size() + 1]; 3799 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(), 3800 strLiteral.size()); 3801 result->EvalData.stringVal[strLiteral.size()] = '\0'; 3802 return result.release(); 3803 } 3804 } 3805 3806 } else if (expr->getStmtClass() == Stmt::CallExprClass) { 3807 callExpr = static_cast<CallExpr *>(expr); 3808 rettype = callExpr->getCallReturnType(ctx); 3809 3810 if (rettype->isVectorType() || callExpr->getNumArgs() > 1) 3811 return nullptr; 3812 3813 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) { 3814 if (callExpr->getNumArgs() == 1 && 3815 !callExpr->getArg(0)->getType()->isIntegralType(ctx)) 3816 return nullptr; 3817 } else if (rettype.getAsString() == "CFStringRef") { 3818 3819 StringLiteral *S = getCFSTR_value(callExpr); 3820 if (S) { 3821 std::string strLiteral(S->getString().str()); 3822 result->EvalType = CXEval_CFStr; 3823 result->EvalData.stringVal = new char[strLiteral.size() + 1]; 3824 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(), 3825 strLiteral.size()); 3826 result->EvalData.stringVal[strLiteral.size()] = '\0'; 3827 return result.release(); 3828 } 3829 } 3830 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) { 3831 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr); 3832 ValueDecl *V = D->getDecl(); 3833 if (V->getKind() == Decl::Function) { 3834 std::string strName = V->getNameAsString(); 3835 result->EvalType = CXEval_Other; 3836 result->EvalData.stringVal = new char[strName.size() + 1]; 3837 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size()); 3838 result->EvalData.stringVal[strName.size()] = '\0'; 3839 return result.release(); 3840 } 3841 } 3842 3843 return nullptr; 3844 } 3845 3846 CXEvalResult clang_Cursor_Evaluate(CXCursor C) { 3847 const Decl *D = getCursorDecl(C); 3848 if (D) { 3849 const Expr *expr = nullptr; 3850 if (auto *Var = dyn_cast<VarDecl>(D)) { 3851 expr = Var->getInit(); 3852 } else if (auto *Field = dyn_cast<FieldDecl>(D)) { 3853 expr = Field->getInClassInitializer(); 3854 } 3855 if (expr) 3856 return const_cast<CXEvalResult>(reinterpret_cast<const void *>( 3857 evaluateExpr(const_cast<Expr *>(expr), C))); 3858 return nullptr; 3859 } 3860 3861 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C)); 3862 if (compoundStmt) { 3863 Expr *expr = nullptr; 3864 for (auto *bodyIterator : compoundStmt->body()) { 3865 if ((expr = dyn_cast<Expr>(bodyIterator))) { 3866 break; 3867 } 3868 } 3869 if (expr) 3870 return const_cast<CXEvalResult>( 3871 reinterpret_cast<const void *>(evaluateExpr(expr, C))); 3872 } 3873 return nullptr; 3874 } 3875 3876 unsigned clang_Cursor_hasAttrs(CXCursor C) { 3877 const Decl *D = getCursorDecl(C); 3878 if (!D) { 3879 return 0; 3880 } 3881 3882 if (D->hasAttrs()) { 3883 return 1; 3884 } 3885 3886 return 0; 3887 } 3888 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) { 3889 return CXSaveTranslationUnit_None; 3890 } 3891 3892 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU, 3893 const char *FileName, 3894 unsigned options) { 3895 CIndexer *CXXIdx = TU->CIdx; 3896 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 3897 setThreadBackgroundPriority(); 3898 3899 bool hadError = cxtu::getASTUnit(TU)->Save(FileName); 3900 return hadError ? CXSaveError_Unknown : CXSaveError_None; 3901 } 3902 3903 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, 3904 unsigned options) { 3905 LOG_FUNC_SECTION { 3906 *Log << TU << ' ' << FileName; 3907 } 3908 3909 if (isNotUsableTU(TU)) { 3910 LOG_BAD_TU(TU); 3911 return CXSaveError_InvalidTU; 3912 } 3913 3914 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 3915 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 3916 if (!CXXUnit->hasSema()) 3917 return CXSaveError_InvalidTU; 3918 3919 CXSaveError result; 3920 auto SaveTranslationUnitImpl = [=, &result]() { 3921 result = clang_saveTranslationUnit_Impl(TU, FileName, options); 3922 }; 3923 3924 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() || 3925 getenv("LIBCLANG_NOTHREADS")) { 3926 SaveTranslationUnitImpl(); 3927 3928 if (getenv("LIBCLANG_RESOURCE_USAGE")) 3929 PrintLibclangResourceUsage(TU); 3930 3931 return result; 3932 } 3933 3934 // We have an AST that has invalid nodes due to compiler errors. 3935 // Use a crash recovery thread for protection. 3936 3937 llvm::CrashRecoveryContext CRC; 3938 3939 if (!RunSafely(CRC, SaveTranslationUnitImpl)) { 3940 fprintf(stderr, "libclang: crash detected during AST saving: {\n"); 3941 fprintf(stderr, " 'filename' : '%s'\n", FileName); 3942 fprintf(stderr, " 'options' : %d,\n", options); 3943 fprintf(stderr, "}\n"); 3944 3945 return CXSaveError_Unknown; 3946 3947 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 3948 PrintLibclangResourceUsage(TU); 3949 } 3950 3951 return result; 3952 } 3953 3954 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { 3955 if (CTUnit) { 3956 // If the translation unit has been marked as unsafe to free, just discard 3957 // it. 3958 ASTUnit *Unit = cxtu::getASTUnit(CTUnit); 3959 if (Unit && Unit->isUnsafeToFree()) 3960 return; 3961 3962 delete cxtu::getASTUnit(CTUnit); 3963 delete CTUnit->StringPool; 3964 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics); 3965 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool); 3966 delete CTUnit->CommentToXML; 3967 delete CTUnit; 3968 } 3969 } 3970 3971 unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) { 3972 if (CTUnit) { 3973 ASTUnit *Unit = cxtu::getASTUnit(CTUnit); 3974 3975 if (Unit && Unit->isUnsafeToFree()) 3976 return false; 3977 3978 Unit->ResetForParse(); 3979 return true; 3980 } 3981 3982 return false; 3983 } 3984 3985 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) { 3986 return CXReparse_None; 3987 } 3988 3989 static CXErrorCode 3990 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU, 3991 ArrayRef<CXUnsavedFile> unsaved_files, 3992 unsigned options) { 3993 // Check arguments. 3994 if (isNotUsableTU(TU)) { 3995 LOG_BAD_TU(TU); 3996 return CXError_InvalidArguments; 3997 } 3998 3999 // Reset the associated diagnostics. 4000 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics); 4001 TU->Diagnostics = nullptr; 4002 4003 CIndexer *CXXIdx = TU->CIdx; 4004 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) 4005 setThreadBackgroundPriority(); 4006 4007 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4008 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4009 4010 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles( 4011 new std::vector<ASTUnit::RemappedFile>()); 4012 4013 // Recover resources if we crash before exiting this function. 4014 llvm::CrashRecoveryContextCleanupRegistrar< 4015 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get()); 4016 4017 for (auto &UF : unsaved_files) { 4018 std::unique_ptr<llvm::MemoryBuffer> MB = 4019 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); 4020 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release())); 4021 } 4022 4023 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(), 4024 *RemappedFiles.get())) 4025 return CXError_Success; 4026 if (isASTReadError(CXXUnit)) 4027 return CXError_ASTReadError; 4028 return CXError_Failure; 4029 } 4030 4031 int clang_reparseTranslationUnit(CXTranslationUnit TU, 4032 unsigned num_unsaved_files, 4033 struct CXUnsavedFile *unsaved_files, 4034 unsigned options) { 4035 LOG_FUNC_SECTION { 4036 *Log << TU; 4037 } 4038 4039 if (num_unsaved_files && !unsaved_files) 4040 return CXError_InvalidArguments; 4041 4042 CXErrorCode result; 4043 auto ReparseTranslationUnitImpl = [=, &result]() { 4044 result = clang_reparseTranslationUnit_Impl( 4045 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options); 4046 }; 4047 4048 if (getenv("LIBCLANG_NOTHREADS")) { 4049 ReparseTranslationUnitImpl(); 4050 return result; 4051 } 4052 4053 llvm::CrashRecoveryContext CRC; 4054 4055 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) { 4056 fprintf(stderr, "libclang: crash detected during reparsing\n"); 4057 cxtu::getASTUnit(TU)->setUnsafeToFree(true); 4058 return CXError_Crashed; 4059 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) 4060 PrintLibclangResourceUsage(TU); 4061 4062 return result; 4063 } 4064 4065 4066 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { 4067 if (isNotUsableTU(CTUnit)) { 4068 LOG_BAD_TU(CTUnit); 4069 return cxstring::createEmpty(); 4070 } 4071 4072 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit); 4073 return cxstring::createDup(CXXUnit->getOriginalSourceFileName()); 4074 } 4075 4076 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { 4077 if (isNotUsableTU(TU)) { 4078 LOG_BAD_TU(TU); 4079 return clang_getNullCursor(); 4080 } 4081 4082 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4083 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU); 4084 } 4085 4086 CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) { 4087 if (isNotUsableTU(CTUnit)) { 4088 LOG_BAD_TU(CTUnit); 4089 return nullptr; 4090 } 4091 4092 CXTargetInfoImpl* impl = new CXTargetInfoImpl(); 4093 impl->TranslationUnit = CTUnit; 4094 return impl; 4095 } 4096 4097 CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) { 4098 if (!TargetInfo) 4099 return cxstring::createEmpty(); 4100 4101 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit; 4102 assert(!isNotUsableTU(CTUnit) && 4103 "Unexpected unusable translation unit in TargetInfo"); 4104 4105 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit); 4106 std::string Triple = 4107 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize(); 4108 return cxstring::createDup(Triple); 4109 } 4110 4111 int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) { 4112 if (!TargetInfo) 4113 return -1; 4114 4115 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit; 4116 assert(!isNotUsableTU(CTUnit) && 4117 "Unexpected unusable translation unit in TargetInfo"); 4118 4119 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit); 4120 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth(); 4121 } 4122 4123 void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) { 4124 if (!TargetInfo) 4125 return; 4126 4127 delete TargetInfo; 4128 } 4129 4130 //===----------------------------------------------------------------------===// 4131 // CXFile Operations. 4132 //===----------------------------------------------------------------------===// 4133 4134 CXString clang_getFileName(CXFile SFile) { 4135 if (!SFile) 4136 return cxstring::createNull(); 4137 4138 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 4139 return cxstring::createRef(FEnt->getName()); 4140 } 4141 4142 time_t clang_getFileTime(CXFile SFile) { 4143 if (!SFile) 4144 return 0; 4145 4146 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 4147 return FEnt->getModificationTime(); 4148 } 4149 4150 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) { 4151 if (isNotUsableTU(TU)) { 4152 LOG_BAD_TU(TU); 4153 return nullptr; 4154 } 4155 4156 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4157 4158 FileManager &FMgr = CXXUnit->getFileManager(); 4159 return const_cast<FileEntry *>(FMgr.getFile(file_name)); 4160 } 4161 4162 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, 4163 CXFile file) { 4164 if (isNotUsableTU(TU)) { 4165 LOG_BAD_TU(TU); 4166 return 0; 4167 } 4168 4169 if (!file) 4170 return 0; 4171 4172 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4173 FileEntry *FEnt = static_cast<FileEntry *>(file); 4174 return CXXUnit->getPreprocessor().getHeaderSearchInfo() 4175 .isFileMultipleIncludeGuarded(FEnt); 4176 } 4177 4178 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) { 4179 if (!file || !outID) 4180 return 1; 4181 4182 FileEntry *FEnt = static_cast<FileEntry *>(file); 4183 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID(); 4184 outID->data[0] = ID.getDevice(); 4185 outID->data[1] = ID.getFile(); 4186 outID->data[2] = FEnt->getModificationTime(); 4187 return 0; 4188 } 4189 4190 int clang_File_isEqual(CXFile file1, CXFile file2) { 4191 if (file1 == file2) 4192 return true; 4193 4194 if (!file1 || !file2) 4195 return false; 4196 4197 FileEntry *FEnt1 = static_cast<FileEntry *>(file1); 4198 FileEntry *FEnt2 = static_cast<FileEntry *>(file2); 4199 return FEnt1->getUniqueID() == FEnt2->getUniqueID(); 4200 } 4201 4202 //===----------------------------------------------------------------------===// 4203 // CXCursor Operations. 4204 //===----------------------------------------------------------------------===// 4205 4206 static const Decl *getDeclFromExpr(const Stmt *E) { 4207 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) 4208 return getDeclFromExpr(CE->getSubExpr()); 4209 4210 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 4211 return RefExpr->getDecl(); 4212 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 4213 return ME->getMemberDecl(); 4214 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 4215 return RE->getDecl(); 4216 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) { 4217 if (PRE->isExplicitProperty()) 4218 return PRE->getExplicitProperty(); 4219 // It could be messaging both getter and setter as in: 4220 // ++myobj.myprop; 4221 // in which case prefer to associate the setter since it is less obvious 4222 // from inspecting the source that the setter is going to get called. 4223 if (PRE->isMessagingSetter()) 4224 return PRE->getImplicitPropertySetter(); 4225 return PRE->getImplicitPropertyGetter(); 4226 } 4227 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 4228 return getDeclFromExpr(POE->getSyntacticForm()); 4229 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 4230 if (Expr *Src = OVE->getSourceExpr()) 4231 return getDeclFromExpr(Src); 4232 4233 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) 4234 return getDeclFromExpr(CE->getCallee()); 4235 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E)) 4236 if (!CE->isElidable()) 4237 return CE->getConstructor(); 4238 if (const CXXInheritedCtorInitExpr *CE = 4239 dyn_cast<CXXInheritedCtorInitExpr>(E)) 4240 return CE->getConstructor(); 4241 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 4242 return OME->getMethodDecl(); 4243 4244 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E)) 4245 return PE->getProtocol(); 4246 if (const SubstNonTypeTemplateParmPackExpr *NTTP 4247 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E)) 4248 return NTTP->getParameterPack(); 4249 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 4250 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) || 4251 isa<ParmVarDecl>(SizeOfPack->getPack())) 4252 return SizeOfPack->getPack(); 4253 4254 return nullptr; 4255 } 4256 4257 static SourceLocation getLocationFromExpr(const Expr *E) { 4258 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) 4259 return getLocationFromExpr(CE->getSubExpr()); 4260 4261 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 4262 return /*FIXME:*/Msg->getLeftLoc(); 4263 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 4264 return DRE->getLocation(); 4265 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E)) 4266 return Member->getMemberLoc(); 4267 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 4268 return Ivar->getLocation(); 4269 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 4270 return SizeOfPack->getPackLoc(); 4271 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E)) 4272 return PropRef->getLocation(); 4273 4274 return E->getLocStart(); 4275 } 4276 4277 extern "C" { 4278 4279 unsigned clang_visitChildren(CXCursor parent, 4280 CXCursorVisitor visitor, 4281 CXClientData client_data) { 4282 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data, 4283 /*VisitPreprocessorLast=*/false); 4284 return CursorVis.VisitChildren(parent); 4285 } 4286 4287 #ifndef __has_feature 4288 #define __has_feature(x) 0 4289 #endif 4290 #if __has_feature(blocks) 4291 typedef enum CXChildVisitResult 4292 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent); 4293 4294 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 4295 CXClientData client_data) { 4296 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 4297 return block(cursor, parent); 4298 } 4299 #else 4300 // If we are compiled with a compiler that doesn't have native blocks support, 4301 // define and call the block manually, so the 4302 typedef struct _CXChildVisitResult 4303 { 4304 void *isa; 4305 int flags; 4306 int reserved; 4307 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor, 4308 CXCursor); 4309 } *CXCursorVisitorBlock; 4310 4311 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 4312 CXClientData client_data) { 4313 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 4314 return block->invoke(block, cursor, parent); 4315 } 4316 #endif 4317 4318 4319 unsigned clang_visitChildrenWithBlock(CXCursor parent, 4320 CXCursorVisitorBlock block) { 4321 return clang_visitChildren(parent, visitWithBlock, block); 4322 } 4323 4324 static CXString getDeclSpelling(const Decl *D) { 4325 if (!D) 4326 return cxstring::createEmpty(); 4327 4328 const NamedDecl *ND = dyn_cast<NamedDecl>(D); 4329 if (!ND) { 4330 if (const ObjCPropertyImplDecl *PropImpl = 4331 dyn_cast<ObjCPropertyImplDecl>(D)) 4332 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 4333 return cxstring::createDup(Property->getIdentifier()->getName()); 4334 4335 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) 4336 if (Module *Mod = ImportD->getImportedModule()) 4337 return cxstring::createDup(Mod->getFullModuleName()); 4338 4339 return cxstring::createEmpty(); 4340 } 4341 4342 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 4343 return cxstring::createDup(OMD->getSelector().getAsString()); 4344 4345 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 4346 // No, this isn't the same as the code below. getIdentifier() is non-virtual 4347 // and returns different names. NamedDecl returns the class name and 4348 // ObjCCategoryImplDecl returns the category name. 4349 return cxstring::createRef(CIMP->getIdentifier()->getNameStart()); 4350 4351 if (isa<UsingDirectiveDecl>(D)) 4352 return cxstring::createEmpty(); 4353 4354 SmallString<1024> S; 4355 llvm::raw_svector_ostream os(S); 4356 ND->printName(os); 4357 4358 return cxstring::createDup(os.str()); 4359 } 4360 4361 CXString clang_getCursorSpelling(CXCursor C) { 4362 if (clang_isTranslationUnit(C.kind)) 4363 return clang_getTranslationUnitSpelling(getCursorTU(C)); 4364 4365 if (clang_isReference(C.kind)) { 4366 switch (C.kind) { 4367 case CXCursor_ObjCSuperClassRef: { 4368 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 4369 return cxstring::createRef(Super->getIdentifier()->getNameStart()); 4370 } 4371 case CXCursor_ObjCClassRef: { 4372 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 4373 return cxstring::createRef(Class->getIdentifier()->getNameStart()); 4374 } 4375 case CXCursor_ObjCProtocolRef: { 4376 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 4377 assert(OID && "getCursorSpelling(): Missing protocol decl"); 4378 return cxstring::createRef(OID->getIdentifier()->getNameStart()); 4379 } 4380 case CXCursor_CXXBaseSpecifier: { 4381 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 4382 return cxstring::createDup(B->getType().getAsString()); 4383 } 4384 case CXCursor_TypeRef: { 4385 const TypeDecl *Type = getCursorTypeRef(C).first; 4386 assert(Type && "Missing type decl"); 4387 4388 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type). 4389 getAsString()); 4390 } 4391 case CXCursor_TemplateRef: { 4392 const TemplateDecl *Template = getCursorTemplateRef(C).first; 4393 assert(Template && "Missing template decl"); 4394 4395 return cxstring::createDup(Template->getNameAsString()); 4396 } 4397 4398 case CXCursor_NamespaceRef: { 4399 const NamedDecl *NS = getCursorNamespaceRef(C).first; 4400 assert(NS && "Missing namespace decl"); 4401 4402 return cxstring::createDup(NS->getNameAsString()); 4403 } 4404 4405 case CXCursor_MemberRef: { 4406 const FieldDecl *Field = getCursorMemberRef(C).first; 4407 assert(Field && "Missing member decl"); 4408 4409 return cxstring::createDup(Field->getNameAsString()); 4410 } 4411 4412 case CXCursor_LabelRef: { 4413 const LabelStmt *Label = getCursorLabelRef(C).first; 4414 assert(Label && "Missing label"); 4415 4416 return cxstring::createRef(Label->getName()); 4417 } 4418 4419 case CXCursor_OverloadedDeclRef: { 4420 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 4421 if (const Decl *D = Storage.dyn_cast<const Decl *>()) { 4422 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 4423 return cxstring::createDup(ND->getNameAsString()); 4424 return cxstring::createEmpty(); 4425 } 4426 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) 4427 return cxstring::createDup(E->getName().getAsString()); 4428 OverloadedTemplateStorage *Ovl 4429 = Storage.get<OverloadedTemplateStorage*>(); 4430 if (Ovl->size() == 0) 4431 return cxstring::createEmpty(); 4432 return cxstring::createDup((*Ovl->begin())->getNameAsString()); 4433 } 4434 4435 case CXCursor_VariableRef: { 4436 const VarDecl *Var = getCursorVariableRef(C).first; 4437 assert(Var && "Missing variable decl"); 4438 4439 return cxstring::createDup(Var->getNameAsString()); 4440 } 4441 4442 default: 4443 return cxstring::createRef("<not implemented>"); 4444 } 4445 } 4446 4447 if (clang_isExpression(C.kind)) { 4448 const Expr *E = getCursorExpr(C); 4449 4450 if (C.kind == CXCursor_ObjCStringLiteral || 4451 C.kind == CXCursor_StringLiteral) { 4452 const StringLiteral *SLit; 4453 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) { 4454 SLit = OSL->getString(); 4455 } else { 4456 SLit = cast<StringLiteral>(E); 4457 } 4458 SmallString<256> Buf; 4459 llvm::raw_svector_ostream OS(Buf); 4460 SLit->outputString(OS); 4461 return cxstring::createDup(OS.str()); 4462 } 4463 4464 const Decl *D = getDeclFromExpr(getCursorExpr(C)); 4465 if (D) 4466 return getDeclSpelling(D); 4467 return cxstring::createEmpty(); 4468 } 4469 4470 if (clang_isStatement(C.kind)) { 4471 const Stmt *S = getCursorStmt(C); 4472 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 4473 return cxstring::createRef(Label->getName()); 4474 4475 return cxstring::createEmpty(); 4476 } 4477 4478 if (C.kind == CXCursor_MacroExpansion) 4479 return cxstring::createRef(getCursorMacroExpansion(C).getName() 4480 ->getNameStart()); 4481 4482 if (C.kind == CXCursor_MacroDefinition) 4483 return cxstring::createRef(getCursorMacroDefinition(C)->getName() 4484 ->getNameStart()); 4485 4486 if (C.kind == CXCursor_InclusionDirective) 4487 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName()); 4488 4489 if (clang_isDeclaration(C.kind)) 4490 return getDeclSpelling(getCursorDecl(C)); 4491 4492 if (C.kind == CXCursor_AnnotateAttr) { 4493 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C)); 4494 return cxstring::createDup(AA->getAnnotation()); 4495 } 4496 4497 if (C.kind == CXCursor_AsmLabelAttr) { 4498 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C)); 4499 return cxstring::createDup(AA->getLabel()); 4500 } 4501 4502 if (C.kind == CXCursor_PackedAttr) { 4503 return cxstring::createRef("packed"); 4504 } 4505 4506 if (C.kind == CXCursor_VisibilityAttr) { 4507 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C)); 4508 switch (AA->getVisibility()) { 4509 case VisibilityAttr::VisibilityType::Default: 4510 return cxstring::createRef("default"); 4511 case VisibilityAttr::VisibilityType::Hidden: 4512 return cxstring::createRef("hidden"); 4513 case VisibilityAttr::VisibilityType::Protected: 4514 return cxstring::createRef("protected"); 4515 } 4516 llvm_unreachable("unknown visibility type"); 4517 } 4518 4519 return cxstring::createEmpty(); 4520 } 4521 4522 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, 4523 unsigned pieceIndex, 4524 unsigned options) { 4525 if (clang_Cursor_isNull(C)) 4526 return clang_getNullRange(); 4527 4528 ASTContext &Ctx = getCursorContext(C); 4529 4530 if (clang_isStatement(C.kind)) { 4531 const Stmt *S = getCursorStmt(C); 4532 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) { 4533 if (pieceIndex > 0) 4534 return clang_getNullRange(); 4535 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc()); 4536 } 4537 4538 return clang_getNullRange(); 4539 } 4540 4541 if (C.kind == CXCursor_ObjCMessageExpr) { 4542 if (const ObjCMessageExpr * 4543 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) { 4544 if (pieceIndex >= ME->getNumSelectorLocs()) 4545 return clang_getNullRange(); 4546 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex)); 4547 } 4548 } 4549 4550 if (C.kind == CXCursor_ObjCInstanceMethodDecl || 4551 C.kind == CXCursor_ObjCClassMethodDecl) { 4552 if (const ObjCMethodDecl * 4553 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) { 4554 if (pieceIndex >= MD->getNumSelectorLocs()) 4555 return clang_getNullRange(); 4556 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex)); 4557 } 4558 } 4559 4560 if (C.kind == CXCursor_ObjCCategoryDecl || 4561 C.kind == CXCursor_ObjCCategoryImplDecl) { 4562 if (pieceIndex > 0) 4563 return clang_getNullRange(); 4564 if (const ObjCCategoryDecl * 4565 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C))) 4566 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc()); 4567 if (const ObjCCategoryImplDecl * 4568 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C))) 4569 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc()); 4570 } 4571 4572 if (C.kind == CXCursor_ModuleImportDecl) { 4573 if (pieceIndex > 0) 4574 return clang_getNullRange(); 4575 if (const ImportDecl *ImportD = 4576 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) { 4577 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs(); 4578 if (!Locs.empty()) 4579 return cxloc::translateSourceRange(Ctx, 4580 SourceRange(Locs.front(), Locs.back())); 4581 } 4582 return clang_getNullRange(); 4583 } 4584 4585 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor || 4586 C.kind == CXCursor_ConversionFunction || 4587 C.kind == CXCursor_FunctionDecl) { 4588 if (pieceIndex > 0) 4589 return clang_getNullRange(); 4590 if (const FunctionDecl *FD = 4591 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) { 4592 DeclarationNameInfo FunctionName = FD->getNameInfo(); 4593 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange()); 4594 } 4595 return clang_getNullRange(); 4596 } 4597 4598 // FIXME: A CXCursor_InclusionDirective should give the location of the 4599 // filename, but we don't keep track of this. 4600 4601 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation 4602 // but we don't keep track of this. 4603 4604 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label 4605 // but we don't keep track of this. 4606 4607 // Default handling, give the location of the cursor. 4608 4609 if (pieceIndex > 0) 4610 return clang_getNullRange(); 4611 4612 CXSourceLocation CXLoc = clang_getCursorLocation(C); 4613 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc); 4614 return cxloc::translateSourceRange(Ctx, Loc); 4615 } 4616 4617 CXString clang_Cursor_getMangling(CXCursor C) { 4618 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind)) 4619 return cxstring::createEmpty(); 4620 4621 // Mangling only works for functions and variables. 4622 const Decl *D = getCursorDecl(C); 4623 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D))) 4624 return cxstring::createEmpty(); 4625 4626 ASTContext &Ctx = D->getASTContext(); 4627 index::CodegenNameGenerator CGNameGen(Ctx); 4628 return cxstring::createDup(CGNameGen.getName(D)); 4629 } 4630 4631 CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) { 4632 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind)) 4633 return nullptr; 4634 4635 const Decl *D = getCursorDecl(C); 4636 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D))) 4637 return nullptr; 4638 4639 ASTContext &Ctx = D->getASTContext(); 4640 index::CodegenNameGenerator CGNameGen(Ctx); 4641 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D); 4642 return cxstring::createSet(Manglings); 4643 } 4644 4645 CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) { 4646 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind)) 4647 return nullptr; 4648 4649 const Decl *D = getCursorDecl(C); 4650 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D))) 4651 return nullptr; 4652 4653 ASTContext &Ctx = D->getASTContext(); 4654 index::CodegenNameGenerator CGNameGen(Ctx); 4655 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D); 4656 return cxstring::createSet(Manglings); 4657 } 4658 4659 CXString clang_getCursorDisplayName(CXCursor C) { 4660 if (!clang_isDeclaration(C.kind)) 4661 return clang_getCursorSpelling(C); 4662 4663 const Decl *D = getCursorDecl(C); 4664 if (!D) 4665 return cxstring::createEmpty(); 4666 4667 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy(); 4668 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 4669 D = FunTmpl->getTemplatedDecl(); 4670 4671 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 4672 SmallString<64> Str; 4673 llvm::raw_svector_ostream OS(Str); 4674 OS << *Function; 4675 if (Function->getPrimaryTemplate()) 4676 OS << "<>"; 4677 OS << "("; 4678 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { 4679 if (I) 4680 OS << ", "; 4681 OS << Function->getParamDecl(I)->getType().getAsString(Policy); 4682 } 4683 4684 if (Function->isVariadic()) { 4685 if (Function->getNumParams()) 4686 OS << ", "; 4687 OS << "..."; 4688 } 4689 OS << ")"; 4690 return cxstring::createDup(OS.str()); 4691 } 4692 4693 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) { 4694 SmallString<64> Str; 4695 llvm::raw_svector_ostream OS(Str); 4696 OS << *ClassTemplate; 4697 OS << "<"; 4698 TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); 4699 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 4700 if (I) 4701 OS << ", "; 4702 4703 NamedDecl *Param = Params->getParam(I); 4704 if (Param->getIdentifier()) { 4705 OS << Param->getIdentifier()->getName(); 4706 continue; 4707 } 4708 4709 // There is no parameter name, which makes this tricky. Try to come up 4710 // with something useful that isn't too long. 4711 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 4712 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class"); 4713 else if (NonTypeTemplateParmDecl *NTTP 4714 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 4715 OS << NTTP->getType().getAsString(Policy); 4716 else 4717 OS << "template<...> class"; 4718 } 4719 4720 OS << ">"; 4721 return cxstring::createDup(OS.str()); 4722 } 4723 4724 if (const ClassTemplateSpecializationDecl *ClassSpec 4725 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 4726 // If the type was explicitly written, use that. 4727 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) 4728 return cxstring::createDup(TSInfo->getType().getAsString(Policy)); 4729 4730 SmallString<128> Str; 4731 llvm::raw_svector_ostream OS(Str); 4732 OS << *ClassSpec; 4733 TemplateSpecializationType::PrintTemplateArgumentList( 4734 OS, ClassSpec->getTemplateArgs().asArray(), Policy); 4735 return cxstring::createDup(OS.str()); 4736 } 4737 4738 return clang_getCursorSpelling(C); 4739 } 4740 4741 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 4742 switch (Kind) { 4743 case CXCursor_FunctionDecl: 4744 return cxstring::createRef("FunctionDecl"); 4745 case CXCursor_TypedefDecl: 4746 return cxstring::createRef("TypedefDecl"); 4747 case CXCursor_EnumDecl: 4748 return cxstring::createRef("EnumDecl"); 4749 case CXCursor_EnumConstantDecl: 4750 return cxstring::createRef("EnumConstantDecl"); 4751 case CXCursor_StructDecl: 4752 return cxstring::createRef("StructDecl"); 4753 case CXCursor_UnionDecl: 4754 return cxstring::createRef("UnionDecl"); 4755 case CXCursor_ClassDecl: 4756 return cxstring::createRef("ClassDecl"); 4757 case CXCursor_FieldDecl: 4758 return cxstring::createRef("FieldDecl"); 4759 case CXCursor_VarDecl: 4760 return cxstring::createRef("VarDecl"); 4761 case CXCursor_ParmDecl: 4762 return cxstring::createRef("ParmDecl"); 4763 case CXCursor_ObjCInterfaceDecl: 4764 return cxstring::createRef("ObjCInterfaceDecl"); 4765 case CXCursor_ObjCCategoryDecl: 4766 return cxstring::createRef("ObjCCategoryDecl"); 4767 case CXCursor_ObjCProtocolDecl: 4768 return cxstring::createRef("ObjCProtocolDecl"); 4769 case CXCursor_ObjCPropertyDecl: 4770 return cxstring::createRef("ObjCPropertyDecl"); 4771 case CXCursor_ObjCIvarDecl: 4772 return cxstring::createRef("ObjCIvarDecl"); 4773 case CXCursor_ObjCInstanceMethodDecl: 4774 return cxstring::createRef("ObjCInstanceMethodDecl"); 4775 case CXCursor_ObjCClassMethodDecl: 4776 return cxstring::createRef("ObjCClassMethodDecl"); 4777 case CXCursor_ObjCImplementationDecl: 4778 return cxstring::createRef("ObjCImplementationDecl"); 4779 case CXCursor_ObjCCategoryImplDecl: 4780 return cxstring::createRef("ObjCCategoryImplDecl"); 4781 case CXCursor_CXXMethod: 4782 return cxstring::createRef("CXXMethod"); 4783 case CXCursor_UnexposedDecl: 4784 return cxstring::createRef("UnexposedDecl"); 4785 case CXCursor_ObjCSuperClassRef: 4786 return cxstring::createRef("ObjCSuperClassRef"); 4787 case CXCursor_ObjCProtocolRef: 4788 return cxstring::createRef("ObjCProtocolRef"); 4789 case CXCursor_ObjCClassRef: 4790 return cxstring::createRef("ObjCClassRef"); 4791 case CXCursor_TypeRef: 4792 return cxstring::createRef("TypeRef"); 4793 case CXCursor_TemplateRef: 4794 return cxstring::createRef("TemplateRef"); 4795 case CXCursor_NamespaceRef: 4796 return cxstring::createRef("NamespaceRef"); 4797 case CXCursor_MemberRef: 4798 return cxstring::createRef("MemberRef"); 4799 case CXCursor_LabelRef: 4800 return cxstring::createRef("LabelRef"); 4801 case CXCursor_OverloadedDeclRef: 4802 return cxstring::createRef("OverloadedDeclRef"); 4803 case CXCursor_VariableRef: 4804 return cxstring::createRef("VariableRef"); 4805 case CXCursor_IntegerLiteral: 4806 return cxstring::createRef("IntegerLiteral"); 4807 case CXCursor_FloatingLiteral: 4808 return cxstring::createRef("FloatingLiteral"); 4809 case CXCursor_ImaginaryLiteral: 4810 return cxstring::createRef("ImaginaryLiteral"); 4811 case CXCursor_StringLiteral: 4812 return cxstring::createRef("StringLiteral"); 4813 case CXCursor_CharacterLiteral: 4814 return cxstring::createRef("CharacterLiteral"); 4815 case CXCursor_ParenExpr: 4816 return cxstring::createRef("ParenExpr"); 4817 case CXCursor_UnaryOperator: 4818 return cxstring::createRef("UnaryOperator"); 4819 case CXCursor_ArraySubscriptExpr: 4820 return cxstring::createRef("ArraySubscriptExpr"); 4821 case CXCursor_OMPArraySectionExpr: 4822 return cxstring::createRef("OMPArraySectionExpr"); 4823 case CXCursor_BinaryOperator: 4824 return cxstring::createRef("BinaryOperator"); 4825 case CXCursor_CompoundAssignOperator: 4826 return cxstring::createRef("CompoundAssignOperator"); 4827 case CXCursor_ConditionalOperator: 4828 return cxstring::createRef("ConditionalOperator"); 4829 case CXCursor_CStyleCastExpr: 4830 return cxstring::createRef("CStyleCastExpr"); 4831 case CXCursor_CompoundLiteralExpr: 4832 return cxstring::createRef("CompoundLiteralExpr"); 4833 case CXCursor_InitListExpr: 4834 return cxstring::createRef("InitListExpr"); 4835 case CXCursor_AddrLabelExpr: 4836 return cxstring::createRef("AddrLabelExpr"); 4837 case CXCursor_StmtExpr: 4838 return cxstring::createRef("StmtExpr"); 4839 case CXCursor_GenericSelectionExpr: 4840 return cxstring::createRef("GenericSelectionExpr"); 4841 case CXCursor_GNUNullExpr: 4842 return cxstring::createRef("GNUNullExpr"); 4843 case CXCursor_CXXStaticCastExpr: 4844 return cxstring::createRef("CXXStaticCastExpr"); 4845 case CXCursor_CXXDynamicCastExpr: 4846 return cxstring::createRef("CXXDynamicCastExpr"); 4847 case CXCursor_CXXReinterpretCastExpr: 4848 return cxstring::createRef("CXXReinterpretCastExpr"); 4849 case CXCursor_CXXConstCastExpr: 4850 return cxstring::createRef("CXXConstCastExpr"); 4851 case CXCursor_CXXFunctionalCastExpr: 4852 return cxstring::createRef("CXXFunctionalCastExpr"); 4853 case CXCursor_CXXTypeidExpr: 4854 return cxstring::createRef("CXXTypeidExpr"); 4855 case CXCursor_CXXBoolLiteralExpr: 4856 return cxstring::createRef("CXXBoolLiteralExpr"); 4857 case CXCursor_CXXNullPtrLiteralExpr: 4858 return cxstring::createRef("CXXNullPtrLiteralExpr"); 4859 case CXCursor_CXXThisExpr: 4860 return cxstring::createRef("CXXThisExpr"); 4861 case CXCursor_CXXThrowExpr: 4862 return cxstring::createRef("CXXThrowExpr"); 4863 case CXCursor_CXXNewExpr: 4864 return cxstring::createRef("CXXNewExpr"); 4865 case CXCursor_CXXDeleteExpr: 4866 return cxstring::createRef("CXXDeleteExpr"); 4867 case CXCursor_UnaryExpr: 4868 return cxstring::createRef("UnaryExpr"); 4869 case CXCursor_ObjCStringLiteral: 4870 return cxstring::createRef("ObjCStringLiteral"); 4871 case CXCursor_ObjCBoolLiteralExpr: 4872 return cxstring::createRef("ObjCBoolLiteralExpr"); 4873 case CXCursor_ObjCAvailabilityCheckExpr: 4874 return cxstring::createRef("ObjCAvailabilityCheckExpr"); 4875 case CXCursor_ObjCSelfExpr: 4876 return cxstring::createRef("ObjCSelfExpr"); 4877 case CXCursor_ObjCEncodeExpr: 4878 return cxstring::createRef("ObjCEncodeExpr"); 4879 case CXCursor_ObjCSelectorExpr: 4880 return cxstring::createRef("ObjCSelectorExpr"); 4881 case CXCursor_ObjCProtocolExpr: 4882 return cxstring::createRef("ObjCProtocolExpr"); 4883 case CXCursor_ObjCBridgedCastExpr: 4884 return cxstring::createRef("ObjCBridgedCastExpr"); 4885 case CXCursor_BlockExpr: 4886 return cxstring::createRef("BlockExpr"); 4887 case CXCursor_PackExpansionExpr: 4888 return cxstring::createRef("PackExpansionExpr"); 4889 case CXCursor_SizeOfPackExpr: 4890 return cxstring::createRef("SizeOfPackExpr"); 4891 case CXCursor_LambdaExpr: 4892 return cxstring::createRef("LambdaExpr"); 4893 case CXCursor_UnexposedExpr: 4894 return cxstring::createRef("UnexposedExpr"); 4895 case CXCursor_DeclRefExpr: 4896 return cxstring::createRef("DeclRefExpr"); 4897 case CXCursor_MemberRefExpr: 4898 return cxstring::createRef("MemberRefExpr"); 4899 case CXCursor_CallExpr: 4900 return cxstring::createRef("CallExpr"); 4901 case CXCursor_ObjCMessageExpr: 4902 return cxstring::createRef("ObjCMessageExpr"); 4903 case CXCursor_UnexposedStmt: 4904 return cxstring::createRef("UnexposedStmt"); 4905 case CXCursor_DeclStmt: 4906 return cxstring::createRef("DeclStmt"); 4907 case CXCursor_LabelStmt: 4908 return cxstring::createRef("LabelStmt"); 4909 case CXCursor_CompoundStmt: 4910 return cxstring::createRef("CompoundStmt"); 4911 case CXCursor_CaseStmt: 4912 return cxstring::createRef("CaseStmt"); 4913 case CXCursor_DefaultStmt: 4914 return cxstring::createRef("DefaultStmt"); 4915 case CXCursor_IfStmt: 4916 return cxstring::createRef("IfStmt"); 4917 case CXCursor_SwitchStmt: 4918 return cxstring::createRef("SwitchStmt"); 4919 case CXCursor_WhileStmt: 4920 return cxstring::createRef("WhileStmt"); 4921 case CXCursor_DoStmt: 4922 return cxstring::createRef("DoStmt"); 4923 case CXCursor_ForStmt: 4924 return cxstring::createRef("ForStmt"); 4925 case CXCursor_GotoStmt: 4926 return cxstring::createRef("GotoStmt"); 4927 case CXCursor_IndirectGotoStmt: 4928 return cxstring::createRef("IndirectGotoStmt"); 4929 case CXCursor_ContinueStmt: 4930 return cxstring::createRef("ContinueStmt"); 4931 case CXCursor_BreakStmt: 4932 return cxstring::createRef("BreakStmt"); 4933 case CXCursor_ReturnStmt: 4934 return cxstring::createRef("ReturnStmt"); 4935 case CXCursor_GCCAsmStmt: 4936 return cxstring::createRef("GCCAsmStmt"); 4937 case CXCursor_MSAsmStmt: 4938 return cxstring::createRef("MSAsmStmt"); 4939 case CXCursor_ObjCAtTryStmt: 4940 return cxstring::createRef("ObjCAtTryStmt"); 4941 case CXCursor_ObjCAtCatchStmt: 4942 return cxstring::createRef("ObjCAtCatchStmt"); 4943 case CXCursor_ObjCAtFinallyStmt: 4944 return cxstring::createRef("ObjCAtFinallyStmt"); 4945 case CXCursor_ObjCAtThrowStmt: 4946 return cxstring::createRef("ObjCAtThrowStmt"); 4947 case CXCursor_ObjCAtSynchronizedStmt: 4948 return cxstring::createRef("ObjCAtSynchronizedStmt"); 4949 case CXCursor_ObjCAutoreleasePoolStmt: 4950 return cxstring::createRef("ObjCAutoreleasePoolStmt"); 4951 case CXCursor_ObjCForCollectionStmt: 4952 return cxstring::createRef("ObjCForCollectionStmt"); 4953 case CXCursor_CXXCatchStmt: 4954 return cxstring::createRef("CXXCatchStmt"); 4955 case CXCursor_CXXTryStmt: 4956 return cxstring::createRef("CXXTryStmt"); 4957 case CXCursor_CXXForRangeStmt: 4958 return cxstring::createRef("CXXForRangeStmt"); 4959 case CXCursor_SEHTryStmt: 4960 return cxstring::createRef("SEHTryStmt"); 4961 case CXCursor_SEHExceptStmt: 4962 return cxstring::createRef("SEHExceptStmt"); 4963 case CXCursor_SEHFinallyStmt: 4964 return cxstring::createRef("SEHFinallyStmt"); 4965 case CXCursor_SEHLeaveStmt: 4966 return cxstring::createRef("SEHLeaveStmt"); 4967 case CXCursor_NullStmt: 4968 return cxstring::createRef("NullStmt"); 4969 case CXCursor_InvalidFile: 4970 return cxstring::createRef("InvalidFile"); 4971 case CXCursor_InvalidCode: 4972 return cxstring::createRef("InvalidCode"); 4973 case CXCursor_NoDeclFound: 4974 return cxstring::createRef("NoDeclFound"); 4975 case CXCursor_NotImplemented: 4976 return cxstring::createRef("NotImplemented"); 4977 case CXCursor_TranslationUnit: 4978 return cxstring::createRef("TranslationUnit"); 4979 case CXCursor_UnexposedAttr: 4980 return cxstring::createRef("UnexposedAttr"); 4981 case CXCursor_IBActionAttr: 4982 return cxstring::createRef("attribute(ibaction)"); 4983 case CXCursor_IBOutletAttr: 4984 return cxstring::createRef("attribute(iboutlet)"); 4985 case CXCursor_IBOutletCollectionAttr: 4986 return cxstring::createRef("attribute(iboutletcollection)"); 4987 case CXCursor_CXXFinalAttr: 4988 return cxstring::createRef("attribute(final)"); 4989 case CXCursor_CXXOverrideAttr: 4990 return cxstring::createRef("attribute(override)"); 4991 case CXCursor_AnnotateAttr: 4992 return cxstring::createRef("attribute(annotate)"); 4993 case CXCursor_AsmLabelAttr: 4994 return cxstring::createRef("asm label"); 4995 case CXCursor_PackedAttr: 4996 return cxstring::createRef("attribute(packed)"); 4997 case CXCursor_PureAttr: 4998 return cxstring::createRef("attribute(pure)"); 4999 case CXCursor_ConstAttr: 5000 return cxstring::createRef("attribute(const)"); 5001 case CXCursor_NoDuplicateAttr: 5002 return cxstring::createRef("attribute(noduplicate)"); 5003 case CXCursor_CUDAConstantAttr: 5004 return cxstring::createRef("attribute(constant)"); 5005 case CXCursor_CUDADeviceAttr: 5006 return cxstring::createRef("attribute(device)"); 5007 case CXCursor_CUDAGlobalAttr: 5008 return cxstring::createRef("attribute(global)"); 5009 case CXCursor_CUDAHostAttr: 5010 return cxstring::createRef("attribute(host)"); 5011 case CXCursor_CUDASharedAttr: 5012 return cxstring::createRef("attribute(shared)"); 5013 case CXCursor_VisibilityAttr: 5014 return cxstring::createRef("attribute(visibility)"); 5015 case CXCursor_DLLExport: 5016 return cxstring::createRef("attribute(dllexport)"); 5017 case CXCursor_DLLImport: 5018 return cxstring::createRef("attribute(dllimport)"); 5019 case CXCursor_PreprocessingDirective: 5020 return cxstring::createRef("preprocessing directive"); 5021 case CXCursor_MacroDefinition: 5022 return cxstring::createRef("macro definition"); 5023 case CXCursor_MacroExpansion: 5024 return cxstring::createRef("macro expansion"); 5025 case CXCursor_InclusionDirective: 5026 return cxstring::createRef("inclusion directive"); 5027 case CXCursor_Namespace: 5028 return cxstring::createRef("Namespace"); 5029 case CXCursor_LinkageSpec: 5030 return cxstring::createRef("LinkageSpec"); 5031 case CXCursor_CXXBaseSpecifier: 5032 return cxstring::createRef("C++ base class specifier"); 5033 case CXCursor_Constructor: 5034 return cxstring::createRef("CXXConstructor"); 5035 case CXCursor_Destructor: 5036 return cxstring::createRef("CXXDestructor"); 5037 case CXCursor_ConversionFunction: 5038 return cxstring::createRef("CXXConversion"); 5039 case CXCursor_TemplateTypeParameter: 5040 return cxstring::createRef("TemplateTypeParameter"); 5041 case CXCursor_NonTypeTemplateParameter: 5042 return cxstring::createRef("NonTypeTemplateParameter"); 5043 case CXCursor_TemplateTemplateParameter: 5044 return cxstring::createRef("TemplateTemplateParameter"); 5045 case CXCursor_FunctionTemplate: 5046 return cxstring::createRef("FunctionTemplate"); 5047 case CXCursor_ClassTemplate: 5048 return cxstring::createRef("ClassTemplate"); 5049 case CXCursor_ClassTemplatePartialSpecialization: 5050 return cxstring::createRef("ClassTemplatePartialSpecialization"); 5051 case CXCursor_NamespaceAlias: 5052 return cxstring::createRef("NamespaceAlias"); 5053 case CXCursor_UsingDirective: 5054 return cxstring::createRef("UsingDirective"); 5055 case CXCursor_UsingDeclaration: 5056 return cxstring::createRef("UsingDeclaration"); 5057 case CXCursor_TypeAliasDecl: 5058 return cxstring::createRef("TypeAliasDecl"); 5059 case CXCursor_ObjCSynthesizeDecl: 5060 return cxstring::createRef("ObjCSynthesizeDecl"); 5061 case CXCursor_ObjCDynamicDecl: 5062 return cxstring::createRef("ObjCDynamicDecl"); 5063 case CXCursor_CXXAccessSpecifier: 5064 return cxstring::createRef("CXXAccessSpecifier"); 5065 case CXCursor_ModuleImportDecl: 5066 return cxstring::createRef("ModuleImport"); 5067 case CXCursor_OMPParallelDirective: 5068 return cxstring::createRef("OMPParallelDirective"); 5069 case CXCursor_OMPSimdDirective: 5070 return cxstring::createRef("OMPSimdDirective"); 5071 case CXCursor_OMPForDirective: 5072 return cxstring::createRef("OMPForDirective"); 5073 case CXCursor_OMPForSimdDirective: 5074 return cxstring::createRef("OMPForSimdDirective"); 5075 case CXCursor_OMPSectionsDirective: 5076 return cxstring::createRef("OMPSectionsDirective"); 5077 case CXCursor_OMPSectionDirective: 5078 return cxstring::createRef("OMPSectionDirective"); 5079 case CXCursor_OMPSingleDirective: 5080 return cxstring::createRef("OMPSingleDirective"); 5081 case CXCursor_OMPMasterDirective: 5082 return cxstring::createRef("OMPMasterDirective"); 5083 case CXCursor_OMPCriticalDirective: 5084 return cxstring::createRef("OMPCriticalDirective"); 5085 case CXCursor_OMPParallelForDirective: 5086 return cxstring::createRef("OMPParallelForDirective"); 5087 case CXCursor_OMPParallelForSimdDirective: 5088 return cxstring::createRef("OMPParallelForSimdDirective"); 5089 case CXCursor_OMPParallelSectionsDirective: 5090 return cxstring::createRef("OMPParallelSectionsDirective"); 5091 case CXCursor_OMPTaskDirective: 5092 return cxstring::createRef("OMPTaskDirective"); 5093 case CXCursor_OMPTaskyieldDirective: 5094 return cxstring::createRef("OMPTaskyieldDirective"); 5095 case CXCursor_OMPBarrierDirective: 5096 return cxstring::createRef("OMPBarrierDirective"); 5097 case CXCursor_OMPTaskwaitDirective: 5098 return cxstring::createRef("OMPTaskwaitDirective"); 5099 case CXCursor_OMPTaskgroupDirective: 5100 return cxstring::createRef("OMPTaskgroupDirective"); 5101 case CXCursor_OMPFlushDirective: 5102 return cxstring::createRef("OMPFlushDirective"); 5103 case CXCursor_OMPOrderedDirective: 5104 return cxstring::createRef("OMPOrderedDirective"); 5105 case CXCursor_OMPAtomicDirective: 5106 return cxstring::createRef("OMPAtomicDirective"); 5107 case CXCursor_OMPTargetDirective: 5108 return cxstring::createRef("OMPTargetDirective"); 5109 case CXCursor_OMPTargetDataDirective: 5110 return cxstring::createRef("OMPTargetDataDirective"); 5111 case CXCursor_OMPTargetEnterDataDirective: 5112 return cxstring::createRef("OMPTargetEnterDataDirective"); 5113 case CXCursor_OMPTargetExitDataDirective: 5114 return cxstring::createRef("OMPTargetExitDataDirective"); 5115 case CXCursor_OMPTargetParallelDirective: 5116 return cxstring::createRef("OMPTargetParallelDirective"); 5117 case CXCursor_OMPTargetParallelForDirective: 5118 return cxstring::createRef("OMPTargetParallelForDirective"); 5119 case CXCursor_OMPTargetUpdateDirective: 5120 return cxstring::createRef("OMPTargetUpdateDirective"); 5121 case CXCursor_OMPTeamsDirective: 5122 return cxstring::createRef("OMPTeamsDirective"); 5123 case CXCursor_OMPCancellationPointDirective: 5124 return cxstring::createRef("OMPCancellationPointDirective"); 5125 case CXCursor_OMPCancelDirective: 5126 return cxstring::createRef("OMPCancelDirective"); 5127 case CXCursor_OMPTaskLoopDirective: 5128 return cxstring::createRef("OMPTaskLoopDirective"); 5129 case CXCursor_OMPTaskLoopSimdDirective: 5130 return cxstring::createRef("OMPTaskLoopSimdDirective"); 5131 case CXCursor_OMPDistributeDirective: 5132 return cxstring::createRef("OMPDistributeDirective"); 5133 case CXCursor_OMPDistributeParallelForDirective: 5134 return cxstring::createRef("OMPDistributeParallelForDirective"); 5135 case CXCursor_OMPDistributeParallelForSimdDirective: 5136 return cxstring::createRef("OMPDistributeParallelForSimdDirective"); 5137 case CXCursor_OMPDistributeSimdDirective: 5138 return cxstring::createRef("OMPDistributeSimdDirective"); 5139 case CXCursor_OMPTargetParallelForSimdDirective: 5140 return cxstring::createRef("OMPTargetParallelForSimdDirective"); 5141 case CXCursor_OMPTargetSimdDirective: 5142 return cxstring::createRef("OMPTargetSimdDirective"); 5143 case CXCursor_OMPTeamsDistributeDirective: 5144 return cxstring::createRef("OMPTeamsDistributeDirective"); 5145 case CXCursor_OMPTeamsDistributeSimdDirective: 5146 return cxstring::createRef("OMPTeamsDistributeSimdDirective"); 5147 case CXCursor_OMPTeamsDistributeParallelForSimdDirective: 5148 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective"); 5149 case CXCursor_OMPTeamsDistributeParallelForDirective: 5150 return cxstring::createRef("OMPTeamsDistributeParallelForDirective"); 5151 case CXCursor_OMPTargetTeamsDirective: 5152 return cxstring::createRef("OMPTargetTeamsDirective"); 5153 case CXCursor_OMPTargetTeamsDistributeDirective: 5154 return cxstring::createRef("OMPTargetTeamsDistributeDirective"); 5155 case CXCursor_OMPTargetTeamsDistributeParallelForDirective: 5156 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective"); 5157 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective: 5158 return cxstring::createRef( 5159 "OMPTargetTeamsDistributeParallelForSimdDirective"); 5160 case CXCursor_OMPTargetTeamsDistributeSimdDirective: 5161 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective"); 5162 case CXCursor_OverloadCandidate: 5163 return cxstring::createRef("OverloadCandidate"); 5164 case CXCursor_TypeAliasTemplateDecl: 5165 return cxstring::createRef("TypeAliasTemplateDecl"); 5166 case CXCursor_StaticAssert: 5167 return cxstring::createRef("StaticAssert"); 5168 case CXCursor_FriendDecl: 5169 return cxstring::createRef("FriendDecl"); 5170 } 5171 5172 llvm_unreachable("Unhandled CXCursorKind"); 5173 } 5174 5175 struct GetCursorData { 5176 SourceLocation TokenBeginLoc; 5177 bool PointsAtMacroArgExpansion; 5178 bool VisitedObjCPropertyImplDecl; 5179 SourceLocation VisitedDeclaratorDeclStartLoc; 5180 CXCursor &BestCursor; 5181 5182 GetCursorData(SourceManager &SM, 5183 SourceLocation tokenBegin, CXCursor &outputCursor) 5184 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { 5185 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin); 5186 VisitedObjCPropertyImplDecl = false; 5187 } 5188 }; 5189 5190 static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, 5191 CXCursor parent, 5192 CXClientData client_data) { 5193 GetCursorData *Data = static_cast<GetCursorData *>(client_data); 5194 CXCursor *BestCursor = &Data->BestCursor; 5195 5196 // If we point inside a macro argument we should provide info of what the 5197 // token is so use the actual cursor, don't replace it with a macro expansion 5198 // cursor. 5199 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion) 5200 return CXChildVisit_Recurse; 5201 5202 if (clang_isDeclaration(cursor.kind)) { 5203 // Avoid having the implicit methods override the property decls. 5204 if (const ObjCMethodDecl *MD 5205 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 5206 if (MD->isImplicit()) 5207 return CXChildVisit_Break; 5208 5209 } else if (const ObjCInterfaceDecl *ID 5210 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) { 5211 // Check that when we have multiple @class references in the same line, 5212 // that later ones do not override the previous ones. 5213 // If we have: 5214 // @class Foo, Bar; 5215 // source ranges for both start at '@', so 'Bar' will end up overriding 5216 // 'Foo' even though the cursor location was at 'Foo'. 5217 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl || 5218 BestCursor->kind == CXCursor_ObjCClassRef) 5219 if (const ObjCInterfaceDecl *PrevID 5220 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){ 5221 if (PrevID != ID && 5222 !PrevID->isThisDeclarationADefinition() && 5223 !ID->isThisDeclarationADefinition()) 5224 return CXChildVisit_Break; 5225 } 5226 5227 } else if (const DeclaratorDecl *DD 5228 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) { 5229 SourceLocation StartLoc = DD->getSourceRange().getBegin(); 5230 // Check that when we have multiple declarators in the same line, 5231 // that later ones do not override the previous ones. 5232 // If we have: 5233 // int Foo, Bar; 5234 // source ranges for both start at 'int', so 'Bar' will end up overriding 5235 // 'Foo' even though the cursor location was at 'Foo'. 5236 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc) 5237 return CXChildVisit_Break; 5238 Data->VisitedDeclaratorDeclStartLoc = StartLoc; 5239 5240 } else if (const ObjCPropertyImplDecl *PropImp 5241 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) { 5242 (void)PropImp; 5243 // Check that when we have multiple @synthesize in the same line, 5244 // that later ones do not override the previous ones. 5245 // If we have: 5246 // @synthesize Foo, Bar; 5247 // source ranges for both start at '@', so 'Bar' will end up overriding 5248 // 'Foo' even though the cursor location was at 'Foo'. 5249 if (Data->VisitedObjCPropertyImplDecl) 5250 return CXChildVisit_Break; 5251 Data->VisitedObjCPropertyImplDecl = true; 5252 } 5253 } 5254 5255 if (clang_isExpression(cursor.kind) && 5256 clang_isDeclaration(BestCursor->kind)) { 5257 if (const Decl *D = getCursorDecl(*BestCursor)) { 5258 // Avoid having the cursor of an expression replace the declaration cursor 5259 // when the expression source range overlaps the declaration range. 5260 // This can happen for C++ constructor expressions whose range generally 5261 // include the variable declaration, e.g.: 5262 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor. 5263 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() && 5264 D->getLocation() == Data->TokenBeginLoc) 5265 return CXChildVisit_Break; 5266 } 5267 } 5268 5269 // If our current best cursor is the construction of a temporary object, 5270 // don't replace that cursor with a type reference, because we want 5271 // clang_getCursor() to point at the constructor. 5272 if (clang_isExpression(BestCursor->kind) && 5273 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) && 5274 cursor.kind == CXCursor_TypeRef) { 5275 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it 5276 // as having the actual point on the type reference. 5277 *BestCursor = getTypeRefedCallExprCursor(*BestCursor); 5278 return CXChildVisit_Recurse; 5279 } 5280 5281 // If we already have an Objective-C superclass reference, don't 5282 // update it further. 5283 if (BestCursor->kind == CXCursor_ObjCSuperClassRef) 5284 return CXChildVisit_Break; 5285 5286 *BestCursor = cursor; 5287 return CXChildVisit_Recurse; 5288 } 5289 5290 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 5291 if (isNotUsableTU(TU)) { 5292 LOG_BAD_TU(TU); 5293 return clang_getNullCursor(); 5294 } 5295 5296 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 5297 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 5298 5299 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 5300 CXCursor Result = cxcursor::getCursor(TU, SLoc); 5301 5302 LOG_FUNC_SECTION { 5303 CXFile SearchFile; 5304 unsigned SearchLine, SearchColumn; 5305 CXFile ResultFile; 5306 unsigned ResultLine, ResultColumn; 5307 CXString SearchFileName, ResultFileName, KindSpelling, USR; 5308 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : ""; 5309 CXSourceLocation ResultLoc = clang_getCursorLocation(Result); 5310 5311 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 5312 nullptr); 5313 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine, 5314 &ResultColumn, nullptr); 5315 SearchFileName = clang_getFileName(SearchFile); 5316 ResultFileName = clang_getFileName(ResultFile); 5317 KindSpelling = clang_getCursorKindSpelling(Result.kind); 5318 USR = clang_getCursorUSR(Result); 5319 *Log << llvm::format("(%s:%d:%d) = %s", 5320 clang_getCString(SearchFileName), SearchLine, SearchColumn, 5321 clang_getCString(KindSpelling)) 5322 << llvm::format("(%s:%d:%d):%s%s", 5323 clang_getCString(ResultFileName), ResultLine, ResultColumn, 5324 clang_getCString(USR), IsDef); 5325 clang_disposeString(SearchFileName); 5326 clang_disposeString(ResultFileName); 5327 clang_disposeString(KindSpelling); 5328 clang_disposeString(USR); 5329 5330 CXCursor Definition = clang_getCursorDefinition(Result); 5331 if (!clang_equalCursors(Definition, clang_getNullCursor())) { 5332 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition); 5333 CXString DefinitionKindSpelling 5334 = clang_getCursorKindSpelling(Definition.kind); 5335 CXFile DefinitionFile; 5336 unsigned DefinitionLine, DefinitionColumn; 5337 clang_getFileLocation(DefinitionLoc, &DefinitionFile, 5338 &DefinitionLine, &DefinitionColumn, nullptr); 5339 CXString DefinitionFileName = clang_getFileName(DefinitionFile); 5340 *Log << llvm::format(" -> %s(%s:%d:%d)", 5341 clang_getCString(DefinitionKindSpelling), 5342 clang_getCString(DefinitionFileName), 5343 DefinitionLine, DefinitionColumn); 5344 clang_disposeString(DefinitionFileName); 5345 clang_disposeString(DefinitionKindSpelling); 5346 } 5347 } 5348 5349 return Result; 5350 } 5351 5352 CXCursor clang_getNullCursor(void) { 5353 return MakeCXCursorInvalid(CXCursor_InvalidFile); 5354 } 5355 5356 unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 5357 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we 5358 // can't set consistently. For example, when visiting a DeclStmt we will set 5359 // it but we don't set it on the result of clang_getCursorDefinition for 5360 // a reference of the same declaration. 5361 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works 5362 // when visiting a DeclStmt currently, the AST should be enhanced to be able 5363 // to provide that kind of info. 5364 if (clang_isDeclaration(X.kind)) 5365 X.data[1] = nullptr; 5366 if (clang_isDeclaration(Y.kind)) 5367 Y.data[1] = nullptr; 5368 5369 return X == Y; 5370 } 5371 5372 unsigned clang_hashCursor(CXCursor C) { 5373 unsigned Index = 0; 5374 if (clang_isExpression(C.kind) || clang_isStatement(C.kind)) 5375 Index = 1; 5376 5377 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue( 5378 std::make_pair(C.kind, C.data[Index])); 5379 } 5380 5381 unsigned clang_isInvalid(enum CXCursorKind K) { 5382 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 5383 } 5384 5385 unsigned clang_isDeclaration(enum CXCursorKind K) { 5386 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) || 5387 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl); 5388 } 5389 5390 unsigned clang_isReference(enum CXCursorKind K) { 5391 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 5392 } 5393 5394 unsigned clang_isExpression(enum CXCursorKind K) { 5395 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 5396 } 5397 5398 unsigned clang_isStatement(enum CXCursorKind K) { 5399 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 5400 } 5401 5402 unsigned clang_isAttribute(enum CXCursorKind K) { 5403 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr; 5404 } 5405 5406 unsigned clang_isTranslationUnit(enum CXCursorKind K) { 5407 return K == CXCursor_TranslationUnit; 5408 } 5409 5410 unsigned clang_isPreprocessing(enum CXCursorKind K) { 5411 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 5412 } 5413 5414 unsigned clang_isUnexposed(enum CXCursorKind K) { 5415 switch (K) { 5416 case CXCursor_UnexposedDecl: 5417 case CXCursor_UnexposedExpr: 5418 case CXCursor_UnexposedStmt: 5419 case CXCursor_UnexposedAttr: 5420 return true; 5421 default: 5422 return false; 5423 } 5424 } 5425 5426 CXCursorKind clang_getCursorKind(CXCursor C) { 5427 return C.kind; 5428 } 5429 5430 CXSourceLocation clang_getCursorLocation(CXCursor C) { 5431 if (clang_isReference(C.kind)) { 5432 switch (C.kind) { 5433 case CXCursor_ObjCSuperClassRef: { 5434 std::pair<const ObjCInterfaceDecl *, SourceLocation> P 5435 = getCursorObjCSuperClassRef(C); 5436 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5437 } 5438 5439 case CXCursor_ObjCProtocolRef: { 5440 std::pair<const ObjCProtocolDecl *, SourceLocation> P 5441 = getCursorObjCProtocolRef(C); 5442 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5443 } 5444 5445 case CXCursor_ObjCClassRef: { 5446 std::pair<const ObjCInterfaceDecl *, SourceLocation> P 5447 = getCursorObjCClassRef(C); 5448 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5449 } 5450 5451 case CXCursor_TypeRef: { 5452 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 5453 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5454 } 5455 5456 case CXCursor_TemplateRef: { 5457 std::pair<const TemplateDecl *, SourceLocation> P = 5458 getCursorTemplateRef(C); 5459 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5460 } 5461 5462 case CXCursor_NamespaceRef: { 5463 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 5464 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5465 } 5466 5467 case CXCursor_MemberRef: { 5468 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 5469 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5470 } 5471 5472 case CXCursor_VariableRef: { 5473 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C); 5474 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 5475 } 5476 5477 case CXCursor_CXXBaseSpecifier: { 5478 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); 5479 if (!BaseSpec) 5480 return clang_getNullLocation(); 5481 5482 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) 5483 return cxloc::translateSourceLocation(getCursorContext(C), 5484 TSInfo->getTypeLoc().getBeginLoc()); 5485 5486 return cxloc::translateSourceLocation(getCursorContext(C), 5487 BaseSpec->getLocStart()); 5488 } 5489 5490 case CXCursor_LabelRef: { 5491 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 5492 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 5493 } 5494 5495 case CXCursor_OverloadedDeclRef: 5496 return cxloc::translateSourceLocation(getCursorContext(C), 5497 getCursorOverloadedDeclRef(C).second); 5498 5499 default: 5500 // FIXME: Need a way to enumerate all non-reference cases. 5501 llvm_unreachable("Missed a reference kind"); 5502 } 5503 } 5504 5505 if (clang_isExpression(C.kind)) 5506 return cxloc::translateSourceLocation(getCursorContext(C), 5507 getLocationFromExpr(getCursorExpr(C))); 5508 5509 if (clang_isStatement(C.kind)) 5510 return cxloc::translateSourceLocation(getCursorContext(C), 5511 getCursorStmt(C)->getLocStart()); 5512 5513 if (C.kind == CXCursor_PreprocessingDirective) { 5514 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 5515 return cxloc::translateSourceLocation(getCursorContext(C), L); 5516 } 5517 5518 if (C.kind == CXCursor_MacroExpansion) { 5519 SourceLocation L 5520 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin(); 5521 return cxloc::translateSourceLocation(getCursorContext(C), L); 5522 } 5523 5524 if (C.kind == CXCursor_MacroDefinition) { 5525 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 5526 return cxloc::translateSourceLocation(getCursorContext(C), L); 5527 } 5528 5529 if (C.kind == CXCursor_InclusionDirective) { 5530 SourceLocation L 5531 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); 5532 return cxloc::translateSourceLocation(getCursorContext(C), L); 5533 } 5534 5535 if (clang_isAttribute(C.kind)) { 5536 SourceLocation L 5537 = cxcursor::getCursorAttr(C)->getLocation(); 5538 return cxloc::translateSourceLocation(getCursorContext(C), L); 5539 } 5540 5541 if (!clang_isDeclaration(C.kind)) 5542 return clang_getNullLocation(); 5543 5544 const Decl *D = getCursorDecl(C); 5545 if (!D) 5546 return clang_getNullLocation(); 5547 5548 SourceLocation Loc = D->getLocation(); 5549 // FIXME: Multiple variables declared in a single declaration 5550 // currently lack the information needed to correctly determine their 5551 // ranges when accounting for the type-specifier. We use context 5552 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 5553 // and if so, whether it is the first decl. 5554 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 5555 if (!cxcursor::isFirstInDeclGroup(C)) 5556 Loc = VD->getLocation(); 5557 } 5558 5559 // For ObjC methods, give the start location of the method name. 5560 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 5561 Loc = MD->getSelectorStartLoc(); 5562 5563 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 5564 } 5565 5566 } // end extern "C" 5567 5568 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) { 5569 assert(TU); 5570 5571 // Guard against an invalid SourceLocation, or we may assert in one 5572 // of the following calls. 5573 if (SLoc.isInvalid()) 5574 return clang_getNullCursor(); 5575 5576 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 5577 5578 // Translate the given source location to make it point at the beginning of 5579 // the token under the cursor. 5580 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 5581 CXXUnit->getASTContext().getLangOpts()); 5582 5583 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 5584 if (SLoc.isValid()) { 5585 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result); 5586 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData, 5587 /*VisitPreprocessorLast=*/true, 5588 /*VisitIncludedEntities=*/false, 5589 SourceLocation(SLoc)); 5590 CursorVis.visitFileRegion(); 5591 } 5592 5593 return Result; 5594 } 5595 5596 static SourceRange getRawCursorExtent(CXCursor C) { 5597 if (clang_isReference(C.kind)) { 5598 switch (C.kind) { 5599 case CXCursor_ObjCSuperClassRef: 5600 return getCursorObjCSuperClassRef(C).second; 5601 5602 case CXCursor_ObjCProtocolRef: 5603 return getCursorObjCProtocolRef(C).second; 5604 5605 case CXCursor_ObjCClassRef: 5606 return getCursorObjCClassRef(C).second; 5607 5608 case CXCursor_TypeRef: 5609 return getCursorTypeRef(C).second; 5610 5611 case CXCursor_TemplateRef: 5612 return getCursorTemplateRef(C).second; 5613 5614 case CXCursor_NamespaceRef: 5615 return getCursorNamespaceRef(C).second; 5616 5617 case CXCursor_MemberRef: 5618 return getCursorMemberRef(C).second; 5619 5620 case CXCursor_CXXBaseSpecifier: 5621 return getCursorCXXBaseSpecifier(C)->getSourceRange(); 5622 5623 case CXCursor_LabelRef: 5624 return getCursorLabelRef(C).second; 5625 5626 case CXCursor_OverloadedDeclRef: 5627 return getCursorOverloadedDeclRef(C).second; 5628 5629 case CXCursor_VariableRef: 5630 return getCursorVariableRef(C).second; 5631 5632 default: 5633 // FIXME: Need a way to enumerate all non-reference cases. 5634 llvm_unreachable("Missed a reference kind"); 5635 } 5636 } 5637 5638 if (clang_isExpression(C.kind)) 5639 return getCursorExpr(C)->getSourceRange(); 5640 5641 if (clang_isStatement(C.kind)) 5642 return getCursorStmt(C)->getSourceRange(); 5643 5644 if (clang_isAttribute(C.kind)) 5645 return getCursorAttr(C)->getRange(); 5646 5647 if (C.kind == CXCursor_PreprocessingDirective) 5648 return cxcursor::getCursorPreprocessingDirective(C); 5649 5650 if (C.kind == CXCursor_MacroExpansion) { 5651 ASTUnit *TU = getCursorASTUnit(C); 5652 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange(); 5653 return TU->mapRangeFromPreamble(Range); 5654 } 5655 5656 if (C.kind == CXCursor_MacroDefinition) { 5657 ASTUnit *TU = getCursorASTUnit(C); 5658 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 5659 return TU->mapRangeFromPreamble(Range); 5660 } 5661 5662 if (C.kind == CXCursor_InclusionDirective) { 5663 ASTUnit *TU = getCursorASTUnit(C); 5664 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange(); 5665 return TU->mapRangeFromPreamble(Range); 5666 } 5667 5668 if (C.kind == CXCursor_TranslationUnit) { 5669 ASTUnit *TU = getCursorASTUnit(C); 5670 FileID MainID = TU->getSourceManager().getMainFileID(); 5671 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID); 5672 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID); 5673 return SourceRange(Start, End); 5674 } 5675 5676 if (clang_isDeclaration(C.kind)) { 5677 const Decl *D = cxcursor::getCursorDecl(C); 5678 if (!D) 5679 return SourceRange(); 5680 5681 SourceRange R = D->getSourceRange(); 5682 // FIXME: Multiple variables declared in a single declaration 5683 // currently lack the information needed to correctly determine their 5684 // ranges when accounting for the type-specifier. We use context 5685 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 5686 // and if so, whether it is the first decl. 5687 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 5688 if (!cxcursor::isFirstInDeclGroup(C)) 5689 R.setBegin(VD->getLocation()); 5690 } 5691 return R; 5692 } 5693 return SourceRange(); 5694 } 5695 5696 /// \brief Retrieves the "raw" cursor extent, which is then extended to include 5697 /// the decl-specifier-seq for declarations. 5698 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) { 5699 if (clang_isDeclaration(C.kind)) { 5700 const Decl *D = cxcursor::getCursorDecl(C); 5701 if (!D) 5702 return SourceRange(); 5703 5704 SourceRange R = D->getSourceRange(); 5705 5706 // Adjust the start of the location for declarations preceded by 5707 // declaration specifiers. 5708 SourceLocation StartLoc; 5709 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 5710 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) 5711 StartLoc = TI->getTypeLoc().getLocStart(); 5712 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) { 5713 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) 5714 StartLoc = TI->getTypeLoc().getLocStart(); 5715 } 5716 5717 if (StartLoc.isValid() && R.getBegin().isValid() && 5718 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin())) 5719 R.setBegin(StartLoc); 5720 5721 // FIXME: Multiple variables declared in a single declaration 5722 // currently lack the information needed to correctly determine their 5723 // ranges when accounting for the type-specifier. We use context 5724 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 5725 // and if so, whether it is the first decl. 5726 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 5727 if (!cxcursor::isFirstInDeclGroup(C)) 5728 R.setBegin(VD->getLocation()); 5729 } 5730 5731 return R; 5732 } 5733 5734 return getRawCursorExtent(C); 5735 } 5736 5737 CXSourceRange clang_getCursorExtent(CXCursor C) { 5738 SourceRange R = getRawCursorExtent(C); 5739 if (R.isInvalid()) 5740 return clang_getNullRange(); 5741 5742 return cxloc::translateSourceRange(getCursorContext(C), R); 5743 } 5744 5745 CXCursor clang_getCursorReferenced(CXCursor C) { 5746 if (clang_isInvalid(C.kind)) 5747 return clang_getNullCursor(); 5748 5749 CXTranslationUnit tu = getCursorTU(C); 5750 if (clang_isDeclaration(C.kind)) { 5751 const Decl *D = getCursorDecl(C); 5752 if (!D) 5753 return clang_getNullCursor(); 5754 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) 5755 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu); 5756 if (const ObjCPropertyImplDecl *PropImpl = 5757 dyn_cast<ObjCPropertyImplDecl>(D)) 5758 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 5759 return MakeCXCursor(Property, tu); 5760 5761 return C; 5762 } 5763 5764 if (clang_isExpression(C.kind)) { 5765 const Expr *E = getCursorExpr(C); 5766 const Decl *D = getDeclFromExpr(E); 5767 if (D) { 5768 CXCursor declCursor = MakeCXCursor(D, tu); 5769 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C), 5770 declCursor); 5771 return declCursor; 5772 } 5773 5774 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) 5775 return MakeCursorOverloadedDeclRef(Ovl, tu); 5776 5777 return clang_getNullCursor(); 5778 } 5779 5780 if (clang_isStatement(C.kind)) { 5781 const Stmt *S = getCursorStmt(C); 5782 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 5783 if (LabelDecl *label = Goto->getLabel()) 5784 if (LabelStmt *labelS = label->getStmt()) 5785 return MakeCXCursor(labelS, getCursorDecl(C), tu); 5786 5787 return clang_getNullCursor(); 5788 } 5789 5790 if (C.kind == CXCursor_MacroExpansion) { 5791 if (const MacroDefinitionRecord *Def = 5792 getCursorMacroExpansion(C).getDefinition()) 5793 return MakeMacroDefinitionCursor(Def, tu); 5794 } 5795 5796 if (!clang_isReference(C.kind)) 5797 return clang_getNullCursor(); 5798 5799 switch (C.kind) { 5800 case CXCursor_ObjCSuperClassRef: 5801 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu); 5802 5803 case CXCursor_ObjCProtocolRef: { 5804 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first; 5805 if (const ObjCProtocolDecl *Def = Prot->getDefinition()) 5806 return MakeCXCursor(Def, tu); 5807 5808 return MakeCXCursor(Prot, tu); 5809 } 5810 5811 case CXCursor_ObjCClassRef: { 5812 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 5813 if (const ObjCInterfaceDecl *Def = Class->getDefinition()) 5814 return MakeCXCursor(Def, tu); 5815 5816 return MakeCXCursor(Class, tu); 5817 } 5818 5819 case CXCursor_TypeRef: 5820 return MakeCXCursor(getCursorTypeRef(C).first, tu ); 5821 5822 case CXCursor_TemplateRef: 5823 return MakeCXCursor(getCursorTemplateRef(C).first, tu ); 5824 5825 case CXCursor_NamespaceRef: 5826 return MakeCXCursor(getCursorNamespaceRef(C).first, tu ); 5827 5828 case CXCursor_MemberRef: 5829 return MakeCXCursor(getCursorMemberRef(C).first, tu ); 5830 5831 case CXCursor_CXXBaseSpecifier: { 5832 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 5833 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), 5834 tu )); 5835 } 5836 5837 case CXCursor_LabelRef: 5838 // FIXME: We end up faking the "parent" declaration here because we 5839 // don't want to make CXCursor larger. 5840 return MakeCXCursor(getCursorLabelRef(C).first, 5841 cxtu::getASTUnit(tu)->getASTContext() 5842 .getTranslationUnitDecl(), 5843 tu); 5844 5845 case CXCursor_OverloadedDeclRef: 5846 return C; 5847 5848 case CXCursor_VariableRef: 5849 return MakeCXCursor(getCursorVariableRef(C).first, tu); 5850 5851 default: 5852 // We would prefer to enumerate all non-reference cursor kinds here. 5853 llvm_unreachable("Unhandled reference cursor kind"); 5854 } 5855 } 5856 5857 CXCursor clang_getCursorDefinition(CXCursor C) { 5858 if (clang_isInvalid(C.kind)) 5859 return clang_getNullCursor(); 5860 5861 CXTranslationUnit TU = getCursorTU(C); 5862 5863 bool WasReference = false; 5864 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 5865 C = clang_getCursorReferenced(C); 5866 WasReference = true; 5867 } 5868 5869 if (C.kind == CXCursor_MacroExpansion) 5870 return clang_getCursorReferenced(C); 5871 5872 if (!clang_isDeclaration(C.kind)) 5873 return clang_getNullCursor(); 5874 5875 const Decl *D = getCursorDecl(C); 5876 if (!D) 5877 return clang_getNullCursor(); 5878 5879 switch (D->getKind()) { 5880 // Declaration kinds that don't really separate the notions of 5881 // declaration and definition. 5882 case Decl::Namespace: 5883 case Decl::Typedef: 5884 case Decl::TypeAlias: 5885 case Decl::TypeAliasTemplate: 5886 case Decl::TemplateTypeParm: 5887 case Decl::EnumConstant: 5888 case Decl::Field: 5889 case Decl::Binding: 5890 case Decl::MSProperty: 5891 case Decl::IndirectField: 5892 case Decl::ObjCIvar: 5893 case Decl::ObjCAtDefsField: 5894 case Decl::ImplicitParam: 5895 case Decl::ParmVar: 5896 case Decl::NonTypeTemplateParm: 5897 case Decl::TemplateTemplateParm: 5898 case Decl::ObjCCategoryImpl: 5899 case Decl::ObjCImplementation: 5900 case Decl::AccessSpec: 5901 case Decl::LinkageSpec: 5902 case Decl::Export: 5903 case Decl::ObjCPropertyImpl: 5904 case Decl::FileScopeAsm: 5905 case Decl::StaticAssert: 5906 case Decl::Block: 5907 case Decl::Captured: 5908 case Decl::OMPCapturedExpr: 5909 case Decl::Label: // FIXME: Is this right?? 5910 case Decl::ClassScopeFunctionSpecialization: 5911 case Decl::CXXDeductionGuide: 5912 case Decl::Import: 5913 case Decl::OMPThreadPrivate: 5914 case Decl::OMPDeclareReduction: 5915 case Decl::ObjCTypeParam: 5916 case Decl::BuiltinTemplate: 5917 case Decl::PragmaComment: 5918 case Decl::PragmaDetectMismatch: 5919 case Decl::UsingPack: 5920 return C; 5921 5922 // Declaration kinds that don't make any sense here, but are 5923 // nonetheless harmless. 5924 case Decl::Empty: 5925 case Decl::TranslationUnit: 5926 case Decl::ExternCContext: 5927 break; 5928 5929 // Declaration kinds for which the definition is not resolvable. 5930 case Decl::UnresolvedUsingTypename: 5931 case Decl::UnresolvedUsingValue: 5932 break; 5933 5934 case Decl::UsingDirective: 5935 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 5936 TU); 5937 5938 case Decl::NamespaceAlias: 5939 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU); 5940 5941 case Decl::Enum: 5942 case Decl::Record: 5943 case Decl::CXXRecord: 5944 case Decl::ClassTemplateSpecialization: 5945 case Decl::ClassTemplatePartialSpecialization: 5946 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 5947 return MakeCXCursor(Def, TU); 5948 return clang_getNullCursor(); 5949 5950 case Decl::Function: 5951 case Decl::CXXMethod: 5952 case Decl::CXXConstructor: 5953 case Decl::CXXDestructor: 5954 case Decl::CXXConversion: { 5955 const FunctionDecl *Def = nullptr; 5956 if (cast<FunctionDecl>(D)->getBody(Def)) 5957 return MakeCXCursor(Def, TU); 5958 return clang_getNullCursor(); 5959 } 5960 5961 case Decl::Var: 5962 case Decl::VarTemplateSpecialization: 5963 case Decl::VarTemplatePartialSpecialization: 5964 case Decl::Decomposition: { 5965 // Ask the variable if it has a definition. 5966 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 5967 return MakeCXCursor(Def, TU); 5968 return clang_getNullCursor(); 5969 } 5970 5971 case Decl::FunctionTemplate: { 5972 const FunctionDecl *Def = nullptr; 5973 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 5974 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU); 5975 return clang_getNullCursor(); 5976 } 5977 5978 case Decl::ClassTemplate: { 5979 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl() 5980 ->getDefinition()) 5981 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 5982 TU); 5983 return clang_getNullCursor(); 5984 } 5985 5986 case Decl::VarTemplate: { 5987 if (VarDecl *Def = 5988 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition()) 5989 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU); 5990 return clang_getNullCursor(); 5991 } 5992 5993 case Decl::Using: 5994 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), 5995 D->getLocation(), TU); 5996 5997 case Decl::UsingShadow: 5998 case Decl::ConstructorUsingShadow: 5999 return clang_getCursorDefinition( 6000 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), 6001 TU)); 6002 6003 case Decl::ObjCMethod: { 6004 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 6005 if (Method->isThisDeclarationADefinition()) 6006 return C; 6007 6008 // Dig out the method definition in the associated 6009 // @implementation, if we have it. 6010 // FIXME: The ASTs should make finding the definition easier. 6011 if (const ObjCInterfaceDecl *Class 6012 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 6013 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 6014 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), 6015 Method->isInstanceMethod())) 6016 if (Def->isThisDeclarationADefinition()) 6017 return MakeCXCursor(Def, TU); 6018 6019 return clang_getNullCursor(); 6020 } 6021 6022 case Decl::ObjCCategory: 6023 if (ObjCCategoryImplDecl *Impl 6024 = cast<ObjCCategoryDecl>(D)->getImplementation()) 6025 return MakeCXCursor(Impl, TU); 6026 return clang_getNullCursor(); 6027 6028 case Decl::ObjCProtocol: 6029 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition()) 6030 return MakeCXCursor(Def, TU); 6031 return clang_getNullCursor(); 6032 6033 case Decl::ObjCInterface: { 6034 // There are two notions of a "definition" for an Objective-C 6035 // class: the interface and its implementation. When we resolved a 6036 // reference to an Objective-C class, produce the @interface as 6037 // the definition; when we were provided with the interface, 6038 // produce the @implementation as the definition. 6039 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D); 6040 if (WasReference) { 6041 if (const ObjCInterfaceDecl *Def = IFace->getDefinition()) 6042 return MakeCXCursor(Def, TU); 6043 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 6044 return MakeCXCursor(Impl, TU); 6045 return clang_getNullCursor(); 6046 } 6047 6048 case Decl::ObjCProperty: 6049 // FIXME: We don't really know where to find the 6050 // ObjCPropertyImplDecls that implement this property. 6051 return clang_getNullCursor(); 6052 6053 case Decl::ObjCCompatibleAlias: 6054 if (const ObjCInterfaceDecl *Class 6055 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 6056 if (const ObjCInterfaceDecl *Def = Class->getDefinition()) 6057 return MakeCXCursor(Def, TU); 6058 6059 return clang_getNullCursor(); 6060 6061 case Decl::Friend: 6062 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 6063 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 6064 return clang_getNullCursor(); 6065 6066 case Decl::FriendTemplate: 6067 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 6068 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 6069 return clang_getNullCursor(); 6070 } 6071 6072 return clang_getNullCursor(); 6073 } 6074 6075 unsigned clang_isCursorDefinition(CXCursor C) { 6076 if (!clang_isDeclaration(C.kind)) 6077 return 0; 6078 6079 return clang_getCursorDefinition(C) == C; 6080 } 6081 6082 CXCursor clang_getCanonicalCursor(CXCursor C) { 6083 if (!clang_isDeclaration(C.kind)) 6084 return C; 6085 6086 if (const Decl *D = getCursorDecl(C)) { 6087 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D)) 6088 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl()) 6089 return MakeCXCursor(CatD, getCursorTU(C)); 6090 6091 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) 6092 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) 6093 return MakeCXCursor(IFD, getCursorTU(C)); 6094 6095 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C)); 6096 } 6097 6098 return C; 6099 } 6100 6101 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) { 6102 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first; 6103 } 6104 6105 unsigned clang_getNumOverloadedDecls(CXCursor C) { 6106 if (C.kind != CXCursor_OverloadedDeclRef) 6107 return 0; 6108 6109 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 6110 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) 6111 return E->getNumDecls(); 6112 6113 if (OverloadedTemplateStorage *S 6114 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 6115 return S->size(); 6116 6117 const Decl *D = Storage.get<const Decl *>(); 6118 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) 6119 return Using->shadow_size(); 6120 6121 return 0; 6122 } 6123 6124 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { 6125 if (cursor.kind != CXCursor_OverloadedDeclRef) 6126 return clang_getNullCursor(); 6127 6128 if (index >= clang_getNumOverloadedDecls(cursor)) 6129 return clang_getNullCursor(); 6130 6131 CXTranslationUnit TU = getCursorTU(cursor); 6132 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; 6133 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) 6134 return MakeCXCursor(E->decls_begin()[index], TU); 6135 6136 if (OverloadedTemplateStorage *S 6137 = Storage.dyn_cast<OverloadedTemplateStorage*>()) 6138 return MakeCXCursor(S->begin()[index], TU); 6139 6140 const Decl *D = Storage.get<const Decl *>(); 6141 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) { 6142 // FIXME: This is, unfortunately, linear time. 6143 UsingDecl::shadow_iterator Pos = Using->shadow_begin(); 6144 std::advance(Pos, index); 6145 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU); 6146 } 6147 6148 return clang_getNullCursor(); 6149 } 6150 6151 void clang_getDefinitionSpellingAndExtent(CXCursor C, 6152 const char **startBuf, 6153 const char **endBuf, 6154 unsigned *startLine, 6155 unsigned *startColumn, 6156 unsigned *endLine, 6157 unsigned *endColumn) { 6158 assert(getCursorDecl(C) && "CXCursor has null decl"); 6159 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C)); 6160 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody()); 6161 6162 SourceManager &SM = FD->getASTContext().getSourceManager(); 6163 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 6164 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 6165 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 6166 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 6167 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 6168 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 6169 } 6170 6171 6172 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags, 6173 unsigned PieceIndex) { 6174 RefNamePieces Pieces; 6175 6176 switch (C.kind) { 6177 case CXCursor_MemberRefExpr: 6178 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C))) 6179 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(), 6180 E->getQualifierLoc().getSourceRange()); 6181 break; 6182 6183 case CXCursor_DeclRefExpr: 6184 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) { 6185 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc()); 6186 Pieces = 6187 buildPieces(NameFlags, false, E->getNameInfo(), 6188 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc); 6189 } 6190 break; 6191 6192 case CXCursor_CallExpr: 6193 if (const CXXOperatorCallExpr *OCE = 6194 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) { 6195 const Expr *Callee = OCE->getCallee(); 6196 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) 6197 Callee = ICE->getSubExpr(); 6198 6199 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) 6200 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(), 6201 DRE->getQualifierLoc().getSourceRange()); 6202 } 6203 break; 6204 6205 default: 6206 break; 6207 } 6208 6209 if (Pieces.empty()) { 6210 if (PieceIndex == 0) 6211 return clang_getCursorExtent(C); 6212 } else if (PieceIndex < Pieces.size()) { 6213 SourceRange R = Pieces[PieceIndex]; 6214 if (R.isValid()) 6215 return cxloc::translateSourceRange(getCursorContext(C), R); 6216 } 6217 6218 return clang_getNullRange(); 6219 } 6220 6221 void clang_enableStackTraces(void) { 6222 // FIXME: Provide an argv0 here so we can find llvm-symbolizer. 6223 llvm::sys::PrintStackTraceOnErrorSignal(StringRef()); 6224 } 6225 6226 void clang_executeOnThread(void (*fn)(void*), void *user_data, 6227 unsigned stack_size) { 6228 llvm::llvm_execute_on_thread(fn, user_data, stack_size); 6229 } 6230 6231 //===----------------------------------------------------------------------===// 6232 // Token-based Operations. 6233 //===----------------------------------------------------------------------===// 6234 6235 /* CXToken layout: 6236 * int_data[0]: a CXTokenKind 6237 * int_data[1]: starting token location 6238 * int_data[2]: token length 6239 * int_data[3]: reserved 6240 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 6241 * otherwise unused. 6242 */ 6243 CXTokenKind clang_getTokenKind(CXToken CXTok) { 6244 return static_cast<CXTokenKind>(CXTok.int_data[0]); 6245 } 6246 6247 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 6248 switch (clang_getTokenKind(CXTok)) { 6249 case CXToken_Identifier: 6250 case CXToken_Keyword: 6251 // We know we have an IdentifierInfo*, so use that. 6252 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data) 6253 ->getNameStart()); 6254 6255 case CXToken_Literal: { 6256 // We have stashed the starting pointer in the ptr_data field. Use it. 6257 const char *Text = static_cast<const char *>(CXTok.ptr_data); 6258 return cxstring::createDup(StringRef(Text, CXTok.int_data[2])); 6259 } 6260 6261 case CXToken_Punctuation: 6262 case CXToken_Comment: 6263 break; 6264 } 6265 6266 if (isNotUsableTU(TU)) { 6267 LOG_BAD_TU(TU); 6268 return cxstring::createEmpty(); 6269 } 6270 6271 // We have to find the starting buffer pointer the hard way, by 6272 // deconstructing the source location. 6273 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6274 if (!CXXUnit) 6275 return cxstring::createEmpty(); 6276 6277 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 6278 std::pair<FileID, unsigned> LocInfo 6279 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc); 6280 bool Invalid = false; 6281 StringRef Buffer 6282 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 6283 if (Invalid) 6284 return cxstring::createEmpty(); 6285 6286 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 6287 } 6288 6289 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 6290 if (isNotUsableTU(TU)) { 6291 LOG_BAD_TU(TU); 6292 return clang_getNullLocation(); 6293 } 6294 6295 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6296 if (!CXXUnit) 6297 return clang_getNullLocation(); 6298 6299 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), 6300 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 6301 } 6302 6303 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 6304 if (isNotUsableTU(TU)) { 6305 LOG_BAD_TU(TU); 6306 return clang_getNullRange(); 6307 } 6308 6309 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6310 if (!CXXUnit) 6311 return clang_getNullRange(); 6312 6313 return cxloc::translateSourceRange(CXXUnit->getASTContext(), 6314 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 6315 } 6316 6317 static void getTokens(ASTUnit *CXXUnit, SourceRange Range, 6318 SmallVectorImpl<CXToken> &CXTokens) { 6319 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 6320 std::pair<FileID, unsigned> BeginLocInfo 6321 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin()); 6322 std::pair<FileID, unsigned> EndLocInfo 6323 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd()); 6324 6325 // Cannot tokenize across files. 6326 if (BeginLocInfo.first != EndLocInfo.first) 6327 return; 6328 6329 // Create a lexer 6330 bool Invalid = false; 6331 StringRef Buffer 6332 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 6333 if (Invalid) 6334 return; 6335 6336 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 6337 CXXUnit->getASTContext().getLangOpts(), 6338 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); 6339 Lex.SetCommentRetentionState(true); 6340 6341 // Lex tokens until we hit the end of the range. 6342 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 6343 Token Tok; 6344 bool previousWasAt = false; 6345 do { 6346 // Lex the next token 6347 Lex.LexFromRawLexer(Tok); 6348 if (Tok.is(tok::eof)) 6349 break; 6350 6351 // Initialize the CXToken. 6352 CXToken CXTok; 6353 6354 // - Common fields 6355 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 6356 CXTok.int_data[2] = Tok.getLength(); 6357 CXTok.int_data[3] = 0; 6358 6359 // - Kind-specific fields 6360 if (Tok.isLiteral()) { 6361 CXTok.int_data[0] = CXToken_Literal; 6362 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData()); 6363 } else if (Tok.is(tok::raw_identifier)) { 6364 // Lookup the identifier to determine whether we have a keyword. 6365 IdentifierInfo *II 6366 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok); 6367 6368 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { 6369 CXTok.int_data[0] = CXToken_Keyword; 6370 } 6371 else { 6372 CXTok.int_data[0] = Tok.is(tok::identifier) 6373 ? CXToken_Identifier 6374 : CXToken_Keyword; 6375 } 6376 CXTok.ptr_data = II; 6377 } else if (Tok.is(tok::comment)) { 6378 CXTok.int_data[0] = CXToken_Comment; 6379 CXTok.ptr_data = nullptr; 6380 } else { 6381 CXTok.int_data[0] = CXToken_Punctuation; 6382 CXTok.ptr_data = nullptr; 6383 } 6384 CXTokens.push_back(CXTok); 6385 previousWasAt = Tok.is(tok::at); 6386 } while (Lex.getBufferLocation() < EffectiveBufferEnd); 6387 } 6388 6389 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, 6390 CXToken **Tokens, unsigned *NumTokens) { 6391 LOG_FUNC_SECTION { 6392 *Log << TU << ' ' << Range; 6393 } 6394 6395 if (Tokens) 6396 *Tokens = nullptr; 6397 if (NumTokens) 6398 *NumTokens = 0; 6399 6400 if (isNotUsableTU(TU)) { 6401 LOG_BAD_TU(TU); 6402 return; 6403 } 6404 6405 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6406 if (!CXXUnit || !Tokens || !NumTokens) 6407 return; 6408 6409 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 6410 6411 SourceRange R = cxloc::translateCXSourceRange(Range); 6412 if (R.isInvalid()) 6413 return; 6414 6415 SmallVector<CXToken, 32> CXTokens; 6416 getTokens(CXXUnit, R, CXTokens); 6417 6418 if (CXTokens.empty()) 6419 return; 6420 6421 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); 6422 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 6423 *NumTokens = CXTokens.size(); 6424 } 6425 6426 void clang_disposeTokens(CXTranslationUnit TU, 6427 CXToken *Tokens, unsigned NumTokens) { 6428 free(Tokens); 6429 } 6430 6431 //===----------------------------------------------------------------------===// 6432 // Token annotation APIs. 6433 //===----------------------------------------------------------------------===// 6434 6435 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 6436 CXCursor parent, 6437 CXClientData client_data); 6438 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, 6439 CXClientData client_data); 6440 6441 namespace { 6442 class AnnotateTokensWorker { 6443 CXToken *Tokens; 6444 CXCursor *Cursors; 6445 unsigned NumTokens; 6446 unsigned TokIdx; 6447 unsigned PreprocessingTokIdx; 6448 CursorVisitor AnnotateVis; 6449 SourceManager &SrcMgr; 6450 bool HasContextSensitiveKeywords; 6451 6452 struct PostChildrenInfo { 6453 CXCursor Cursor; 6454 SourceRange CursorRange; 6455 unsigned BeforeReachingCursorIdx; 6456 unsigned BeforeChildrenTokenIdx; 6457 }; 6458 SmallVector<PostChildrenInfo, 8> PostChildrenInfos; 6459 6460 CXToken &getTok(unsigned Idx) { 6461 assert(Idx < NumTokens); 6462 return Tokens[Idx]; 6463 } 6464 const CXToken &getTok(unsigned Idx) const { 6465 assert(Idx < NumTokens); 6466 return Tokens[Idx]; 6467 } 6468 bool MoreTokens() const { return TokIdx < NumTokens; } 6469 unsigned NextToken() const { return TokIdx; } 6470 void AdvanceToken() { ++TokIdx; } 6471 SourceLocation GetTokenLoc(unsigned tokI) { 6472 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]); 6473 } 6474 bool isFunctionMacroToken(unsigned tokI) const { 6475 return getTok(tokI).int_data[3] != 0; 6476 } 6477 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const { 6478 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]); 6479 } 6480 6481 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange); 6482 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult, 6483 SourceRange); 6484 6485 public: 6486 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens, 6487 CXTranslationUnit TU, SourceRange RegionOfInterest) 6488 : Tokens(tokens), Cursors(cursors), 6489 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0), 6490 AnnotateVis(TU, 6491 AnnotateTokensVisitor, this, 6492 /*VisitPreprocessorLast=*/true, 6493 /*VisitIncludedEntities=*/false, 6494 RegionOfInterest, 6495 /*VisitDeclsOnly=*/false, 6496 AnnotateTokensPostChildrenVisitor), 6497 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()), 6498 HasContextSensitiveKeywords(false) { } 6499 6500 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 6501 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 6502 bool postVisitChildren(CXCursor cursor); 6503 void AnnotateTokens(); 6504 6505 /// \brief Determine whether the annotator saw any cursors that have 6506 /// context-sensitive keywords. 6507 bool hasContextSensitiveKeywords() const { 6508 return HasContextSensitiveKeywords; 6509 } 6510 6511 ~AnnotateTokensWorker() { 6512 assert(PostChildrenInfos.empty()); 6513 } 6514 }; 6515 } 6516 6517 void AnnotateTokensWorker::AnnotateTokens() { 6518 // Walk the AST within the region of interest, annotating tokens 6519 // along the way. 6520 AnnotateVis.visitFileRegion(); 6521 } 6522 6523 static inline void updateCursorAnnotation(CXCursor &Cursor, 6524 const CXCursor &updateC) { 6525 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind)) 6526 return; 6527 Cursor = updateC; 6528 } 6529 6530 /// \brief It annotates and advances tokens with a cursor until the comparison 6531 //// between the cursor location and the source range is the same as 6532 /// \arg compResult. 6533 /// 6534 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached. 6535 /// Pass RangeOverlap to annotate tokens inside a range. 6536 void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC, 6537 RangeComparisonResult compResult, 6538 SourceRange range) { 6539 while (MoreTokens()) { 6540 const unsigned I = NextToken(); 6541 if (isFunctionMacroToken(I)) 6542 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range)) 6543 return; 6544 6545 SourceLocation TokLoc = GetTokenLoc(I); 6546 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { 6547 updateCursorAnnotation(Cursors[I], updateC); 6548 AdvanceToken(); 6549 continue; 6550 } 6551 break; 6552 } 6553 } 6554 6555 /// \brief Special annotation handling for macro argument tokens. 6556 /// \returns true if it advanced beyond all macro tokens, false otherwise. 6557 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens( 6558 CXCursor updateC, 6559 RangeComparisonResult compResult, 6560 SourceRange range) { 6561 assert(MoreTokens()); 6562 assert(isFunctionMacroToken(NextToken()) && 6563 "Should be called only for macro arg tokens"); 6564 6565 // This works differently than annotateAndAdvanceTokens; because expanded 6566 // macro arguments can have arbitrary translation-unit source order, we do not 6567 // advance the token index one by one until a token fails the range test. 6568 // We only advance once past all of the macro arg tokens if all of them 6569 // pass the range test. If one of them fails we keep the token index pointing 6570 // at the start of the macro arg tokens so that the failing token will be 6571 // annotated by a subsequent annotation try. 6572 6573 bool atLeastOneCompFail = false; 6574 6575 unsigned I = NextToken(); 6576 for (; I < NumTokens && isFunctionMacroToken(I); ++I) { 6577 SourceLocation TokLoc = getFunctionMacroTokenLoc(I); 6578 if (TokLoc.isFileID()) 6579 continue; // not macro arg token, it's parens or comma. 6580 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { 6581 if (clang_isInvalid(clang_getCursorKind(Cursors[I]))) 6582 Cursors[I] = updateC; 6583 } else 6584 atLeastOneCompFail = true; 6585 } 6586 6587 if (atLeastOneCompFail) 6588 return false; 6589 6590 TokIdx = I; // All of the tokens were handled, advance beyond all of them. 6591 return true; 6592 } 6593 6594 enum CXChildVisitResult 6595 AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) { 6596 SourceRange cursorRange = getRawCursorExtent(cursor); 6597 if (cursorRange.isInvalid()) 6598 return CXChildVisit_Recurse; 6599 6600 if (!HasContextSensitiveKeywords) { 6601 // Objective-C properties can have context-sensitive keywords. 6602 if (cursor.kind == CXCursor_ObjCPropertyDecl) { 6603 if (const ObjCPropertyDecl *Property 6604 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor))) 6605 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0; 6606 } 6607 // Objective-C methods can have context-sensitive keywords. 6608 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl || 6609 cursor.kind == CXCursor_ObjCClassMethodDecl) { 6610 if (const ObjCMethodDecl *Method 6611 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 6612 if (Method->getObjCDeclQualifier()) 6613 HasContextSensitiveKeywords = true; 6614 else { 6615 for (const auto *P : Method->parameters()) { 6616 if (P->getObjCDeclQualifier()) { 6617 HasContextSensitiveKeywords = true; 6618 break; 6619 } 6620 } 6621 } 6622 } 6623 } 6624 // C++ methods can have context-sensitive keywords. 6625 else if (cursor.kind == CXCursor_CXXMethod) { 6626 if (const CXXMethodDecl *Method 6627 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) { 6628 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>()) 6629 HasContextSensitiveKeywords = true; 6630 } 6631 } 6632 // C++ classes can have context-sensitive keywords. 6633 else if (cursor.kind == CXCursor_StructDecl || 6634 cursor.kind == CXCursor_ClassDecl || 6635 cursor.kind == CXCursor_ClassTemplate || 6636 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) { 6637 if (const Decl *D = getCursorDecl(cursor)) 6638 if (D->hasAttr<FinalAttr>()) 6639 HasContextSensitiveKeywords = true; 6640 } 6641 } 6642 6643 // Don't override a property annotation with its getter/setter method. 6644 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl && 6645 parent.kind == CXCursor_ObjCPropertyDecl) 6646 return CXChildVisit_Continue; 6647 6648 if (clang_isPreprocessing(cursor.kind)) { 6649 // Items in the preprocessing record are kept separate from items in 6650 // declarations, so we keep a separate token index. 6651 unsigned SavedTokIdx = TokIdx; 6652 TokIdx = PreprocessingTokIdx; 6653 6654 // Skip tokens up until we catch up to the beginning of the preprocessing 6655 // entry. 6656 while (MoreTokens()) { 6657 const unsigned I = NextToken(); 6658 SourceLocation TokLoc = GetTokenLoc(I); 6659 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 6660 case RangeBefore: 6661 AdvanceToken(); 6662 continue; 6663 case RangeAfter: 6664 case RangeOverlap: 6665 break; 6666 } 6667 break; 6668 } 6669 6670 // Look at all of the tokens within this range. 6671 while (MoreTokens()) { 6672 const unsigned I = NextToken(); 6673 SourceLocation TokLoc = GetTokenLoc(I); 6674 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 6675 case RangeBefore: 6676 llvm_unreachable("Infeasible"); 6677 case RangeAfter: 6678 break; 6679 case RangeOverlap: 6680 // For macro expansions, just note where the beginning of the macro 6681 // expansion occurs. 6682 if (cursor.kind == CXCursor_MacroExpansion) { 6683 if (TokLoc == cursorRange.getBegin()) 6684 Cursors[I] = cursor; 6685 AdvanceToken(); 6686 break; 6687 } 6688 // We may have already annotated macro names inside macro definitions. 6689 if (Cursors[I].kind != CXCursor_MacroExpansion) 6690 Cursors[I] = cursor; 6691 AdvanceToken(); 6692 continue; 6693 } 6694 break; 6695 } 6696 6697 // Save the preprocessing token index; restore the non-preprocessing 6698 // token index. 6699 PreprocessingTokIdx = TokIdx; 6700 TokIdx = SavedTokIdx; 6701 return CXChildVisit_Recurse; 6702 } 6703 6704 if (cursorRange.isInvalid()) 6705 return CXChildVisit_Continue; 6706 6707 unsigned BeforeReachingCursorIdx = NextToken(); 6708 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 6709 const enum CXCursorKind K = clang_getCursorKind(parent); 6710 const CXCursor updateC = 6711 (clang_isInvalid(K) || K == CXCursor_TranslationUnit || 6712 // Attributes are annotated out-of-order, skip tokens until we reach it. 6713 clang_isAttribute(cursor.kind)) 6714 ? clang_getNullCursor() : parent; 6715 6716 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange); 6717 6718 // Avoid having the cursor of an expression "overwrite" the annotation of the 6719 // variable declaration that it belongs to. 6720 // This can happen for C++ constructor expressions whose range generally 6721 // include the variable declaration, e.g.: 6722 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor. 6723 if (clang_isExpression(cursorK) && MoreTokens()) { 6724 const Expr *E = getCursorExpr(cursor); 6725 if (const Decl *D = getCursorParentDecl(cursor)) { 6726 const unsigned I = NextToken(); 6727 if (E->getLocStart().isValid() && D->getLocation().isValid() && 6728 E->getLocStart() == D->getLocation() && 6729 E->getLocStart() == GetTokenLoc(I)) { 6730 updateCursorAnnotation(Cursors[I], updateC); 6731 AdvanceToken(); 6732 } 6733 } 6734 } 6735 6736 // Before recursing into the children keep some state that we are going 6737 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some 6738 // extra work after the child nodes are visited. 6739 // Note that we don't call VisitChildren here to avoid traversing statements 6740 // code-recursively which can blow the stack. 6741 6742 PostChildrenInfo Info; 6743 Info.Cursor = cursor; 6744 Info.CursorRange = cursorRange; 6745 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx; 6746 Info.BeforeChildrenTokenIdx = NextToken(); 6747 PostChildrenInfos.push_back(Info); 6748 6749 return CXChildVisit_Recurse; 6750 } 6751 6752 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) { 6753 if (PostChildrenInfos.empty()) 6754 return false; 6755 const PostChildrenInfo &Info = PostChildrenInfos.back(); 6756 if (!clang_equalCursors(Info.Cursor, cursor)) 6757 return false; 6758 6759 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx; 6760 const unsigned AfterChildren = NextToken(); 6761 SourceRange cursorRange = Info.CursorRange; 6762 6763 // Scan the tokens that are at the end of the cursor, but are not captured 6764 // but the child cursors. 6765 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange); 6766 6767 // Scan the tokens that are at the beginning of the cursor, but are not 6768 // capture by the child cursors. 6769 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 6770 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 6771 break; 6772 6773 Cursors[I] = cursor; 6774 } 6775 6776 // Attributes are annotated out-of-order, rewind TokIdx to when we first 6777 // encountered the attribute cursor. 6778 if (clang_isAttribute(cursor.kind)) 6779 TokIdx = Info.BeforeReachingCursorIdx; 6780 6781 PostChildrenInfos.pop_back(); 6782 return false; 6783 } 6784 6785 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 6786 CXCursor parent, 6787 CXClientData client_data) { 6788 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent); 6789 } 6790 6791 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, 6792 CXClientData client_data) { 6793 return static_cast<AnnotateTokensWorker*>(client_data)-> 6794 postVisitChildren(cursor); 6795 } 6796 6797 namespace { 6798 6799 /// \brief Uses the macro expansions in the preprocessing record to find 6800 /// and mark tokens that are macro arguments. This info is used by the 6801 /// AnnotateTokensWorker. 6802 class MarkMacroArgTokensVisitor { 6803 SourceManager &SM; 6804 CXToken *Tokens; 6805 unsigned NumTokens; 6806 unsigned CurIdx; 6807 6808 public: 6809 MarkMacroArgTokensVisitor(SourceManager &SM, 6810 CXToken *tokens, unsigned numTokens) 6811 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { } 6812 6813 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) { 6814 if (cursor.kind != CXCursor_MacroExpansion) 6815 return CXChildVisit_Continue; 6816 6817 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange(); 6818 if (macroRange.getBegin() == macroRange.getEnd()) 6819 return CXChildVisit_Continue; // it's not a function macro. 6820 6821 for (; CurIdx < NumTokens; ++CurIdx) { 6822 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx), 6823 macroRange.getBegin())) 6824 break; 6825 } 6826 6827 if (CurIdx == NumTokens) 6828 return CXChildVisit_Break; 6829 6830 for (; CurIdx < NumTokens; ++CurIdx) { 6831 SourceLocation tokLoc = getTokenLoc(CurIdx); 6832 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd())) 6833 break; 6834 6835 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc)); 6836 } 6837 6838 if (CurIdx == NumTokens) 6839 return CXChildVisit_Break; 6840 6841 return CXChildVisit_Continue; 6842 } 6843 6844 private: 6845 CXToken &getTok(unsigned Idx) { 6846 assert(Idx < NumTokens); 6847 return Tokens[Idx]; 6848 } 6849 const CXToken &getTok(unsigned Idx) const { 6850 assert(Idx < NumTokens); 6851 return Tokens[Idx]; 6852 } 6853 6854 SourceLocation getTokenLoc(unsigned tokI) { 6855 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]); 6856 } 6857 6858 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) { 6859 // The third field is reserved and currently not used. Use it here 6860 // to mark macro arg expanded tokens with their expanded locations. 6861 getTok(tokI).int_data[3] = loc.getRawEncoding(); 6862 } 6863 }; 6864 6865 } // end anonymous namespace 6866 6867 static CXChildVisitResult 6868 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent, 6869 CXClientData client_data) { 6870 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor, 6871 parent); 6872 } 6873 6874 /// \brief Used by \c annotatePreprocessorTokens. 6875 /// \returns true if lexing was finished, false otherwise. 6876 static bool lexNext(Lexer &Lex, Token &Tok, 6877 unsigned &NextIdx, unsigned NumTokens) { 6878 if (NextIdx >= NumTokens) 6879 return true; 6880 6881 ++NextIdx; 6882 Lex.LexFromRawLexer(Tok); 6883 return Tok.is(tok::eof); 6884 } 6885 6886 static void annotatePreprocessorTokens(CXTranslationUnit TU, 6887 SourceRange RegionOfInterest, 6888 CXCursor *Cursors, 6889 CXToken *Tokens, 6890 unsigned NumTokens) { 6891 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6892 6893 Preprocessor &PP = CXXUnit->getPreprocessor(); 6894 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 6895 std::pair<FileID, unsigned> BeginLocInfo 6896 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin()); 6897 std::pair<FileID, unsigned> EndLocInfo 6898 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd()); 6899 6900 if (BeginLocInfo.first != EndLocInfo.first) 6901 return; 6902 6903 StringRef Buffer; 6904 bool Invalid = false; 6905 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 6906 if (Buffer.empty() || Invalid) 6907 return; 6908 6909 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 6910 CXXUnit->getASTContext().getLangOpts(), 6911 Buffer.begin(), Buffer.data() + BeginLocInfo.second, 6912 Buffer.end()); 6913 Lex.SetCommentRetentionState(true); 6914 6915 unsigned NextIdx = 0; 6916 // Lex tokens in raw mode until we hit the end of the range, to avoid 6917 // entering #includes or expanding macros. 6918 while (true) { 6919 Token Tok; 6920 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 6921 break; 6922 unsigned TokIdx = NextIdx-1; 6923 assert(Tok.getLocation() == 6924 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1])); 6925 6926 reprocess: 6927 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 6928 // We have found a preprocessing directive. Annotate the tokens 6929 // appropriately. 6930 // 6931 // FIXME: Some simple tests here could identify macro definitions and 6932 // #undefs, to provide specific cursor kinds for those. 6933 6934 SourceLocation BeginLoc = Tok.getLocation(); 6935 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 6936 break; 6937 6938 MacroInfo *MI = nullptr; 6939 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") { 6940 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 6941 break; 6942 6943 if (Tok.is(tok::raw_identifier)) { 6944 IdentifierInfo &II = 6945 PP.getIdentifierTable().get(Tok.getRawIdentifier()); 6946 SourceLocation MappedTokLoc = 6947 CXXUnit->mapLocationToPreamble(Tok.getLocation()); 6948 MI = getMacroInfo(II, MappedTokLoc, TU); 6949 } 6950 } 6951 6952 bool finished = false; 6953 do { 6954 if (lexNext(Lex, Tok, NextIdx, NumTokens)) { 6955 finished = true; 6956 break; 6957 } 6958 // If we are in a macro definition, check if the token was ever a 6959 // macro name and annotate it if that's the case. 6960 if (MI) { 6961 SourceLocation SaveLoc = Tok.getLocation(); 6962 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc)); 6963 MacroDefinitionRecord *MacroDef = 6964 checkForMacroInMacroDefinition(MI, Tok, TU); 6965 Tok.setLocation(SaveLoc); 6966 if (MacroDef) 6967 Cursors[NextIdx - 1] = 6968 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU); 6969 } 6970 } while (!Tok.isAtStartOfLine()); 6971 6972 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2; 6973 assert(TokIdx <= LastIdx); 6974 SourceLocation EndLoc = 6975 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]); 6976 CXCursor Cursor = 6977 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU); 6978 6979 for (; TokIdx <= LastIdx; ++TokIdx) 6980 updateCursorAnnotation(Cursors[TokIdx], Cursor); 6981 6982 if (finished) 6983 break; 6984 goto reprocess; 6985 } 6986 } 6987 } 6988 6989 // This gets run a separate thread to avoid stack blowout. 6990 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit, 6991 CXToken *Tokens, unsigned NumTokens, 6992 CXCursor *Cursors) { 6993 CIndexer *CXXIdx = TU->CIdx; 6994 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) 6995 setThreadBackgroundPriority(); 6996 6997 // Determine the region of interest, which contains all of the tokens. 6998 SourceRange RegionOfInterest; 6999 RegionOfInterest.setBegin( 7000 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0]))); 7001 RegionOfInterest.setEnd( 7002 cxloc::translateSourceLocation(clang_getTokenLocation(TU, 7003 Tokens[NumTokens-1]))); 7004 7005 // Relex the tokens within the source range to look for preprocessing 7006 // directives. 7007 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens); 7008 7009 // If begin location points inside a macro argument, set it to the expansion 7010 // location so we can have the full context when annotating semantically. 7011 { 7012 SourceManager &SM = CXXUnit->getSourceManager(); 7013 SourceLocation Loc = 7014 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin()); 7015 if (Loc.isMacroID()) 7016 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc)); 7017 } 7018 7019 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) { 7020 // Search and mark tokens that are macro argument expansions. 7021 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(), 7022 Tokens, NumTokens); 7023 CursorVisitor MacroArgMarker(TU, 7024 MarkMacroArgTokensVisitorDelegate, &Visitor, 7025 /*VisitPreprocessorLast=*/true, 7026 /*VisitIncludedEntities=*/false, 7027 RegionOfInterest); 7028 MacroArgMarker.visitPreprocessedEntitiesInRegion(); 7029 } 7030 7031 // Annotate all of the source locations in the region of interest that map to 7032 // a specific cursor. 7033 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest); 7034 7035 // FIXME: We use a ridiculous stack size here because the data-recursion 7036 // algorithm uses a large stack frame than the non-data recursive version, 7037 // and AnnotationTokensWorker currently transforms the data-recursion 7038 // algorithm back into a traditional recursion by explicitly calling 7039 // VisitChildren(). We will need to remove this explicit recursive call. 7040 W.AnnotateTokens(); 7041 7042 // If we ran into any entities that involve context-sensitive keywords, 7043 // take another pass through the tokens to mark them as such. 7044 if (W.hasContextSensitiveKeywords()) { 7045 for (unsigned I = 0; I != NumTokens; ++I) { 7046 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier) 7047 continue; 7048 7049 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) { 7050 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 7051 if (const ObjCPropertyDecl *Property 7052 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) { 7053 if (Property->getPropertyAttributesAsWritten() != 0 && 7054 llvm::StringSwitch<bool>(II->getName()) 7055 .Case("readonly", true) 7056 .Case("assign", true) 7057 .Case("unsafe_unretained", true) 7058 .Case("readwrite", true) 7059 .Case("retain", true) 7060 .Case("copy", true) 7061 .Case("nonatomic", true) 7062 .Case("atomic", true) 7063 .Case("getter", true) 7064 .Case("setter", true) 7065 .Case("strong", true) 7066 .Case("weak", true) 7067 .Case("class", true) 7068 .Default(false)) 7069 Tokens[I].int_data[0] = CXToken_Keyword; 7070 } 7071 continue; 7072 } 7073 7074 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl || 7075 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) { 7076 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 7077 if (llvm::StringSwitch<bool>(II->getName()) 7078 .Case("in", true) 7079 .Case("out", true) 7080 .Case("inout", true) 7081 .Case("oneway", true) 7082 .Case("bycopy", true) 7083 .Case("byref", true) 7084 .Default(false)) 7085 Tokens[I].int_data[0] = CXToken_Keyword; 7086 continue; 7087 } 7088 7089 if (Cursors[I].kind == CXCursor_CXXFinalAttr || 7090 Cursors[I].kind == CXCursor_CXXOverrideAttr) { 7091 Tokens[I].int_data[0] = CXToken_Keyword; 7092 continue; 7093 } 7094 } 7095 } 7096 } 7097 7098 void clang_annotateTokens(CXTranslationUnit TU, 7099 CXToken *Tokens, unsigned NumTokens, 7100 CXCursor *Cursors) { 7101 if (isNotUsableTU(TU)) { 7102 LOG_BAD_TU(TU); 7103 return; 7104 } 7105 if (NumTokens == 0 || !Tokens || !Cursors) { 7106 LOG_FUNC_SECTION { *Log << "<null input>"; } 7107 return; 7108 } 7109 7110 LOG_FUNC_SECTION { 7111 *Log << TU << ' '; 7112 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]); 7113 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]); 7114 *Log << clang_getRange(bloc, eloc); 7115 } 7116 7117 // Any token we don't specifically annotate will have a NULL cursor. 7118 CXCursor C = clang_getNullCursor(); 7119 for (unsigned I = 0; I != NumTokens; ++I) 7120 Cursors[I] = C; 7121 7122 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 7123 if (!CXXUnit) 7124 return; 7125 7126 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 7127 7128 auto AnnotateTokensImpl = [=]() { 7129 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors); 7130 }; 7131 llvm::CrashRecoveryContext CRC; 7132 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) { 7133 fprintf(stderr, "libclang: crash detected while annotating tokens\n"); 7134 } 7135 } 7136 7137 //===----------------------------------------------------------------------===// 7138 // Operations for querying linkage of a cursor. 7139 //===----------------------------------------------------------------------===// 7140 7141 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 7142 if (!clang_isDeclaration(cursor.kind)) 7143 return CXLinkage_Invalid; 7144 7145 const Decl *D = cxcursor::getCursorDecl(cursor); 7146 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 7147 switch (ND->getLinkageInternal()) { 7148 case NoLinkage: 7149 case VisibleNoLinkage: return CXLinkage_NoLinkage; 7150 case ModuleInternalLinkage: 7151 case InternalLinkage: return CXLinkage_Internal; 7152 case UniqueExternalLinkage: return CXLinkage_UniqueExternal; 7153 case ModuleLinkage: 7154 case ExternalLinkage: return CXLinkage_External; 7155 }; 7156 7157 return CXLinkage_Invalid; 7158 } 7159 7160 //===----------------------------------------------------------------------===// 7161 // Operations for querying visibility of a cursor. 7162 //===----------------------------------------------------------------------===// 7163 7164 CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) { 7165 if (!clang_isDeclaration(cursor.kind)) 7166 return CXVisibility_Invalid; 7167 7168 const Decl *D = cxcursor::getCursorDecl(cursor); 7169 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 7170 switch (ND->getVisibility()) { 7171 case HiddenVisibility: return CXVisibility_Hidden; 7172 case ProtectedVisibility: return CXVisibility_Protected; 7173 case DefaultVisibility: return CXVisibility_Default; 7174 }; 7175 7176 return CXVisibility_Invalid; 7177 } 7178 7179 //===----------------------------------------------------------------------===// 7180 // Operations for querying language of a cursor. 7181 //===----------------------------------------------------------------------===// 7182 7183 static CXLanguageKind getDeclLanguage(const Decl *D) { 7184 if (!D) 7185 return CXLanguage_C; 7186 7187 switch (D->getKind()) { 7188 default: 7189 break; 7190 case Decl::ImplicitParam: 7191 case Decl::ObjCAtDefsField: 7192 case Decl::ObjCCategory: 7193 case Decl::ObjCCategoryImpl: 7194 case Decl::ObjCCompatibleAlias: 7195 case Decl::ObjCImplementation: 7196 case Decl::ObjCInterface: 7197 case Decl::ObjCIvar: 7198 case Decl::ObjCMethod: 7199 case Decl::ObjCProperty: 7200 case Decl::ObjCPropertyImpl: 7201 case Decl::ObjCProtocol: 7202 case Decl::ObjCTypeParam: 7203 return CXLanguage_ObjC; 7204 case Decl::CXXConstructor: 7205 case Decl::CXXConversion: 7206 case Decl::CXXDestructor: 7207 case Decl::CXXMethod: 7208 case Decl::CXXRecord: 7209 case Decl::ClassTemplate: 7210 case Decl::ClassTemplatePartialSpecialization: 7211 case Decl::ClassTemplateSpecialization: 7212 case Decl::Friend: 7213 case Decl::FriendTemplate: 7214 case Decl::FunctionTemplate: 7215 case Decl::LinkageSpec: 7216 case Decl::Namespace: 7217 case Decl::NamespaceAlias: 7218 case Decl::NonTypeTemplateParm: 7219 case Decl::StaticAssert: 7220 case Decl::TemplateTemplateParm: 7221 case Decl::TemplateTypeParm: 7222 case Decl::UnresolvedUsingTypename: 7223 case Decl::UnresolvedUsingValue: 7224 case Decl::Using: 7225 case Decl::UsingDirective: 7226 case Decl::UsingShadow: 7227 return CXLanguage_CPlusPlus; 7228 } 7229 7230 return CXLanguage_C; 7231 } 7232 7233 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) { 7234 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()) 7235 return CXAvailability_NotAvailable; 7236 7237 switch (D->getAvailability()) { 7238 case AR_Available: 7239 case AR_NotYetIntroduced: 7240 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D)) 7241 return getCursorAvailabilityForDecl( 7242 cast<Decl>(EnumConst->getDeclContext())); 7243 return CXAvailability_Available; 7244 7245 case AR_Deprecated: 7246 return CXAvailability_Deprecated; 7247 7248 case AR_Unavailable: 7249 return CXAvailability_NotAvailable; 7250 } 7251 7252 llvm_unreachable("Unknown availability kind!"); 7253 } 7254 7255 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 7256 if (clang_isDeclaration(cursor.kind)) 7257 if (const Decl *D = cxcursor::getCursorDecl(cursor)) 7258 return getCursorAvailabilityForDecl(D); 7259 7260 return CXAvailability_Available; 7261 } 7262 7263 static CXVersion convertVersion(VersionTuple In) { 7264 CXVersion Out = { -1, -1, -1 }; 7265 if (In.empty()) 7266 return Out; 7267 7268 Out.Major = In.getMajor(); 7269 7270 Optional<unsigned> Minor = In.getMinor(); 7271 if (Minor.hasValue()) 7272 Out.Minor = *Minor; 7273 else 7274 return Out; 7275 7276 Optional<unsigned> Subminor = In.getSubminor(); 7277 if (Subminor.hasValue()) 7278 Out.Subminor = *Subminor; 7279 7280 return Out; 7281 } 7282 7283 static void getCursorPlatformAvailabilityForDecl( 7284 const Decl *D, int *always_deprecated, CXString *deprecated_message, 7285 int *always_unavailable, CXString *unavailable_message, 7286 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) { 7287 bool HadAvailAttr = false; 7288 for (auto A : D->attrs()) { 7289 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) { 7290 HadAvailAttr = true; 7291 if (always_deprecated) 7292 *always_deprecated = 1; 7293 if (deprecated_message) { 7294 clang_disposeString(*deprecated_message); 7295 *deprecated_message = cxstring::createDup(Deprecated->getMessage()); 7296 } 7297 continue; 7298 } 7299 7300 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) { 7301 HadAvailAttr = true; 7302 if (always_unavailable) 7303 *always_unavailable = 1; 7304 if (unavailable_message) { 7305 clang_disposeString(*unavailable_message); 7306 *unavailable_message = cxstring::createDup(Unavailable->getMessage()); 7307 } 7308 continue; 7309 } 7310 7311 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) { 7312 AvailabilityAttrs.push_back(Avail); 7313 HadAvailAttr = true; 7314 } 7315 } 7316 7317 if (!HadAvailAttr) 7318 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D)) 7319 return getCursorPlatformAvailabilityForDecl( 7320 cast<Decl>(EnumConst->getDeclContext()), always_deprecated, 7321 deprecated_message, always_unavailable, unavailable_message, 7322 AvailabilityAttrs); 7323 7324 if (AvailabilityAttrs.empty()) 7325 return; 7326 7327 std::sort(AvailabilityAttrs.begin(), AvailabilityAttrs.end(), 7328 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) { 7329 return LHS->getPlatform()->getName() < 7330 RHS->getPlatform()->getName(); 7331 }); 7332 ASTContext &Ctx = D->getASTContext(); 7333 auto It = std::unique( 7334 AvailabilityAttrs.begin(), AvailabilityAttrs.end(), 7335 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) { 7336 if (LHS->getPlatform() != RHS->getPlatform()) 7337 return false; 7338 7339 if (LHS->getIntroduced() == RHS->getIntroduced() && 7340 LHS->getDeprecated() == RHS->getDeprecated() && 7341 LHS->getObsoleted() == RHS->getObsoleted() && 7342 LHS->getMessage() == RHS->getMessage() && 7343 LHS->getReplacement() == RHS->getReplacement()) 7344 return true; 7345 7346 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) || 7347 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) || 7348 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty())) 7349 return false; 7350 7351 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) 7352 LHS->setIntroduced(Ctx, RHS->getIntroduced()); 7353 7354 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) { 7355 LHS->setDeprecated(Ctx, RHS->getDeprecated()); 7356 if (LHS->getMessage().empty()) 7357 LHS->setMessage(Ctx, RHS->getMessage()); 7358 if (LHS->getReplacement().empty()) 7359 LHS->setReplacement(Ctx, RHS->getReplacement()); 7360 } 7361 7362 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) { 7363 LHS->setObsoleted(Ctx, RHS->getObsoleted()); 7364 if (LHS->getMessage().empty()) 7365 LHS->setMessage(Ctx, RHS->getMessage()); 7366 if (LHS->getReplacement().empty()) 7367 LHS->setReplacement(Ctx, RHS->getReplacement()); 7368 } 7369 7370 return true; 7371 }); 7372 AvailabilityAttrs.erase(It, AvailabilityAttrs.end()); 7373 } 7374 7375 int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated, 7376 CXString *deprecated_message, 7377 int *always_unavailable, 7378 CXString *unavailable_message, 7379 CXPlatformAvailability *availability, 7380 int availability_size) { 7381 if (always_deprecated) 7382 *always_deprecated = 0; 7383 if (deprecated_message) 7384 *deprecated_message = cxstring::createEmpty(); 7385 if (always_unavailable) 7386 *always_unavailable = 0; 7387 if (unavailable_message) 7388 *unavailable_message = cxstring::createEmpty(); 7389 7390 if (!clang_isDeclaration(cursor.kind)) 7391 return 0; 7392 7393 const Decl *D = cxcursor::getCursorDecl(cursor); 7394 if (!D) 7395 return 0; 7396 7397 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs; 7398 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message, 7399 always_unavailable, unavailable_message, 7400 AvailabilityAttrs); 7401 for (const auto &Avail : 7402 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs) 7403 .take_front(availability_size))) { 7404 availability[Avail.index()].Platform = 7405 cxstring::createDup(Avail.value()->getPlatform()->getName()); 7406 availability[Avail.index()].Introduced = 7407 convertVersion(Avail.value()->getIntroduced()); 7408 availability[Avail.index()].Deprecated = 7409 convertVersion(Avail.value()->getDeprecated()); 7410 availability[Avail.index()].Obsoleted = 7411 convertVersion(Avail.value()->getObsoleted()); 7412 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable(); 7413 availability[Avail.index()].Message = 7414 cxstring::createDup(Avail.value()->getMessage()); 7415 } 7416 7417 return AvailabilityAttrs.size(); 7418 } 7419 7420 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) { 7421 clang_disposeString(availability->Platform); 7422 clang_disposeString(availability->Message); 7423 } 7424 7425 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 7426 if (clang_isDeclaration(cursor.kind)) 7427 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 7428 7429 return CXLanguage_Invalid; 7430 } 7431 7432 CXTLSKind clang_getCursorTLSKind(CXCursor cursor) { 7433 const Decl *D = cxcursor::getCursorDecl(cursor); 7434 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 7435 switch (VD->getTLSKind()) { 7436 case VarDecl::TLS_None: 7437 return CXTLS_None; 7438 case VarDecl::TLS_Dynamic: 7439 return CXTLS_Dynamic; 7440 case VarDecl::TLS_Static: 7441 return CXTLS_Static; 7442 } 7443 } 7444 7445 return CXTLS_None; 7446 } 7447 7448 /// \brief If the given cursor is the "templated" declaration 7449 /// descibing a class or function template, return the class or 7450 /// function template. 7451 static const Decl *maybeGetTemplateCursor(const Decl *D) { 7452 if (!D) 7453 return nullptr; 7454 7455 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 7456 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate()) 7457 return FunTmpl; 7458 7459 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 7460 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate()) 7461 return ClassTmpl; 7462 7463 return D; 7464 } 7465 7466 7467 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) { 7468 StorageClass sc = SC_None; 7469 const Decl *D = getCursorDecl(C); 7470 if (D) { 7471 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7472 sc = FD->getStorageClass(); 7473 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 7474 sc = VD->getStorageClass(); 7475 } else { 7476 return CX_SC_Invalid; 7477 } 7478 } else { 7479 return CX_SC_Invalid; 7480 } 7481 switch (sc) { 7482 case SC_None: 7483 return CX_SC_None; 7484 case SC_Extern: 7485 return CX_SC_Extern; 7486 case SC_Static: 7487 return CX_SC_Static; 7488 case SC_PrivateExtern: 7489 return CX_SC_PrivateExtern; 7490 case SC_Auto: 7491 return CX_SC_Auto; 7492 case SC_Register: 7493 return CX_SC_Register; 7494 } 7495 llvm_unreachable("Unhandled storage class!"); 7496 } 7497 7498 CXCursor clang_getCursorSemanticParent(CXCursor cursor) { 7499 if (clang_isDeclaration(cursor.kind)) { 7500 if (const Decl *D = getCursorDecl(cursor)) { 7501 const DeclContext *DC = D->getDeclContext(); 7502 if (!DC) 7503 return clang_getNullCursor(); 7504 7505 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 7506 getCursorTU(cursor)); 7507 } 7508 } 7509 7510 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { 7511 if (const Decl *D = getCursorDecl(cursor)) 7512 return MakeCXCursor(D, getCursorTU(cursor)); 7513 } 7514 7515 return clang_getNullCursor(); 7516 } 7517 7518 CXCursor clang_getCursorLexicalParent(CXCursor cursor) { 7519 if (clang_isDeclaration(cursor.kind)) { 7520 if (const Decl *D = getCursorDecl(cursor)) { 7521 const DeclContext *DC = D->getLexicalDeclContext(); 7522 if (!DC) 7523 return clang_getNullCursor(); 7524 7525 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 7526 getCursorTU(cursor)); 7527 } 7528 } 7529 7530 // FIXME: Note that we can't easily compute the lexical context of a 7531 // statement or expression, so we return nothing. 7532 return clang_getNullCursor(); 7533 } 7534 7535 CXFile clang_getIncludedFile(CXCursor cursor) { 7536 if (cursor.kind != CXCursor_InclusionDirective) 7537 return nullptr; 7538 7539 const InclusionDirective *ID = getCursorInclusionDirective(cursor); 7540 return const_cast<FileEntry *>(ID->getFile()); 7541 } 7542 7543 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) { 7544 if (C.kind != CXCursor_ObjCPropertyDecl) 7545 return CXObjCPropertyAttr_noattr; 7546 7547 unsigned Result = CXObjCPropertyAttr_noattr; 7548 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C)); 7549 ObjCPropertyDecl::PropertyAttributeKind Attr = 7550 PD->getPropertyAttributesAsWritten(); 7551 7552 #define SET_CXOBJCPROP_ATTR(A) \ 7553 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \ 7554 Result |= CXObjCPropertyAttr_##A 7555 SET_CXOBJCPROP_ATTR(readonly); 7556 SET_CXOBJCPROP_ATTR(getter); 7557 SET_CXOBJCPROP_ATTR(assign); 7558 SET_CXOBJCPROP_ATTR(readwrite); 7559 SET_CXOBJCPROP_ATTR(retain); 7560 SET_CXOBJCPROP_ATTR(copy); 7561 SET_CXOBJCPROP_ATTR(nonatomic); 7562 SET_CXOBJCPROP_ATTR(setter); 7563 SET_CXOBJCPROP_ATTR(atomic); 7564 SET_CXOBJCPROP_ATTR(weak); 7565 SET_CXOBJCPROP_ATTR(strong); 7566 SET_CXOBJCPROP_ATTR(unsafe_unretained); 7567 SET_CXOBJCPROP_ATTR(class); 7568 #undef SET_CXOBJCPROP_ATTR 7569 7570 return Result; 7571 } 7572 7573 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) { 7574 if (!clang_isDeclaration(C.kind)) 7575 return CXObjCDeclQualifier_None; 7576 7577 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None; 7578 const Decl *D = getCursorDecl(C); 7579 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 7580 QT = MD->getObjCDeclQualifier(); 7581 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D)) 7582 QT = PD->getObjCDeclQualifier(); 7583 if (QT == Decl::OBJC_TQ_None) 7584 return CXObjCDeclQualifier_None; 7585 7586 unsigned Result = CXObjCDeclQualifier_None; 7587 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In; 7588 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout; 7589 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out; 7590 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy; 7591 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref; 7592 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway; 7593 7594 return Result; 7595 } 7596 7597 unsigned clang_Cursor_isObjCOptional(CXCursor C) { 7598 if (!clang_isDeclaration(C.kind)) 7599 return 0; 7600 7601 const Decl *D = getCursorDecl(C); 7602 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) 7603 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional; 7604 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 7605 return MD->getImplementationControl() == ObjCMethodDecl::Optional; 7606 7607 return 0; 7608 } 7609 7610 unsigned clang_Cursor_isVariadic(CXCursor C) { 7611 if (!clang_isDeclaration(C.kind)) 7612 return 0; 7613 7614 const Decl *D = getCursorDecl(C); 7615 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 7616 return FD->isVariadic(); 7617 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 7618 return MD->isVariadic(); 7619 7620 return 0; 7621 } 7622 7623 unsigned clang_Cursor_isExternalSymbol(CXCursor C, 7624 CXString *language, CXString *definedIn, 7625 unsigned *isGenerated) { 7626 if (!clang_isDeclaration(C.kind)) 7627 return 0; 7628 7629 const Decl *D = getCursorDecl(C); 7630 7631 if (auto *attr = D->getExternalSourceSymbolAttr()) { 7632 if (language) 7633 *language = cxstring::createDup(attr->getLanguage()); 7634 if (definedIn) 7635 *definedIn = cxstring::createDup(attr->getDefinedIn()); 7636 if (isGenerated) 7637 *isGenerated = attr->getGeneratedDeclaration(); 7638 return 1; 7639 } 7640 return 0; 7641 } 7642 7643 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) { 7644 if (!clang_isDeclaration(C.kind)) 7645 return clang_getNullRange(); 7646 7647 const Decl *D = getCursorDecl(C); 7648 ASTContext &Context = getCursorContext(C); 7649 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 7650 if (!RC) 7651 return clang_getNullRange(); 7652 7653 return cxloc::translateSourceRange(Context, RC->getSourceRange()); 7654 } 7655 7656 CXString clang_Cursor_getRawCommentText(CXCursor C) { 7657 if (!clang_isDeclaration(C.kind)) 7658 return cxstring::createNull(); 7659 7660 const Decl *D = getCursorDecl(C); 7661 ASTContext &Context = getCursorContext(C); 7662 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 7663 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) : 7664 StringRef(); 7665 7666 // Don't duplicate the string because RawText points directly into source 7667 // code. 7668 return cxstring::createRef(RawText); 7669 } 7670 7671 CXString clang_Cursor_getBriefCommentText(CXCursor C) { 7672 if (!clang_isDeclaration(C.kind)) 7673 return cxstring::createNull(); 7674 7675 const Decl *D = getCursorDecl(C); 7676 const ASTContext &Context = getCursorContext(C); 7677 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 7678 7679 if (RC) { 7680 StringRef BriefText = RC->getBriefText(Context); 7681 7682 // Don't duplicate the string because RawComment ensures that this memory 7683 // will not go away. 7684 return cxstring::createRef(BriefText); 7685 } 7686 7687 return cxstring::createNull(); 7688 } 7689 7690 CXModule clang_Cursor_getModule(CXCursor C) { 7691 if (C.kind == CXCursor_ModuleImportDecl) { 7692 if (const ImportDecl *ImportD = 7693 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) 7694 return ImportD->getImportedModule(); 7695 } 7696 7697 return nullptr; 7698 } 7699 7700 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) { 7701 if (isNotUsableTU(TU)) { 7702 LOG_BAD_TU(TU); 7703 return nullptr; 7704 } 7705 if (!File) 7706 return nullptr; 7707 FileEntry *FE = static_cast<FileEntry *>(File); 7708 7709 ASTUnit &Unit = *cxtu::getASTUnit(TU); 7710 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo(); 7711 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE); 7712 7713 return Header.getModule(); 7714 } 7715 7716 CXFile clang_Module_getASTFile(CXModule CXMod) { 7717 if (!CXMod) 7718 return nullptr; 7719 Module *Mod = static_cast<Module*>(CXMod); 7720 return const_cast<FileEntry *>(Mod->getASTFile()); 7721 } 7722 7723 CXModule clang_Module_getParent(CXModule CXMod) { 7724 if (!CXMod) 7725 return nullptr; 7726 Module *Mod = static_cast<Module*>(CXMod); 7727 return Mod->Parent; 7728 } 7729 7730 CXString clang_Module_getName(CXModule CXMod) { 7731 if (!CXMod) 7732 return cxstring::createEmpty(); 7733 Module *Mod = static_cast<Module*>(CXMod); 7734 return cxstring::createDup(Mod->Name); 7735 } 7736 7737 CXString clang_Module_getFullName(CXModule CXMod) { 7738 if (!CXMod) 7739 return cxstring::createEmpty(); 7740 Module *Mod = static_cast<Module*>(CXMod); 7741 return cxstring::createDup(Mod->getFullModuleName()); 7742 } 7743 7744 int clang_Module_isSystem(CXModule CXMod) { 7745 if (!CXMod) 7746 return 0; 7747 Module *Mod = static_cast<Module*>(CXMod); 7748 return Mod->IsSystem; 7749 } 7750 7751 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU, 7752 CXModule CXMod) { 7753 if (isNotUsableTU(TU)) { 7754 LOG_BAD_TU(TU); 7755 return 0; 7756 } 7757 if (!CXMod) 7758 return 0; 7759 Module *Mod = static_cast<Module*>(CXMod); 7760 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager(); 7761 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr); 7762 return TopHeaders.size(); 7763 } 7764 7765 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU, 7766 CXModule CXMod, unsigned Index) { 7767 if (isNotUsableTU(TU)) { 7768 LOG_BAD_TU(TU); 7769 return nullptr; 7770 } 7771 if (!CXMod) 7772 return nullptr; 7773 Module *Mod = static_cast<Module*>(CXMod); 7774 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager(); 7775 7776 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr); 7777 if (Index < TopHeaders.size()) 7778 return const_cast<FileEntry *>(TopHeaders[Index]); 7779 7780 return nullptr; 7781 } 7782 7783 //===----------------------------------------------------------------------===// 7784 // C++ AST instrospection. 7785 //===----------------------------------------------------------------------===// 7786 7787 unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) { 7788 if (!clang_isDeclaration(C.kind)) 7789 return 0; 7790 7791 const Decl *D = cxcursor::getCursorDecl(C); 7792 const CXXConstructorDecl *Constructor = 7793 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 7794 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0; 7795 } 7796 7797 unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) { 7798 if (!clang_isDeclaration(C.kind)) 7799 return 0; 7800 7801 const Decl *D = cxcursor::getCursorDecl(C); 7802 const CXXConstructorDecl *Constructor = 7803 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 7804 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0; 7805 } 7806 7807 unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) { 7808 if (!clang_isDeclaration(C.kind)) 7809 return 0; 7810 7811 const Decl *D = cxcursor::getCursorDecl(C); 7812 const CXXConstructorDecl *Constructor = 7813 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 7814 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0; 7815 } 7816 7817 unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) { 7818 if (!clang_isDeclaration(C.kind)) 7819 return 0; 7820 7821 const Decl *D = cxcursor::getCursorDecl(C); 7822 const CXXConstructorDecl *Constructor = 7823 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 7824 // Passing 'false' excludes constructors marked 'explicit'. 7825 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0; 7826 } 7827 7828 unsigned clang_CXXField_isMutable(CXCursor C) { 7829 if (!clang_isDeclaration(C.kind)) 7830 return 0; 7831 7832 if (const auto D = cxcursor::getCursorDecl(C)) 7833 if (const auto FD = dyn_cast_or_null<FieldDecl>(D)) 7834 return FD->isMutable() ? 1 : 0; 7835 return 0; 7836 } 7837 7838 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) { 7839 if (!clang_isDeclaration(C.kind)) 7840 return 0; 7841 7842 const Decl *D = cxcursor::getCursorDecl(C); 7843 const CXXMethodDecl *Method = 7844 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 7845 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0; 7846 } 7847 7848 unsigned clang_CXXMethod_isConst(CXCursor C) { 7849 if (!clang_isDeclaration(C.kind)) 7850 return 0; 7851 7852 const Decl *D = cxcursor::getCursorDecl(C); 7853 const CXXMethodDecl *Method = 7854 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 7855 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0; 7856 } 7857 7858 unsigned clang_CXXMethod_isDefaulted(CXCursor C) { 7859 if (!clang_isDeclaration(C.kind)) 7860 return 0; 7861 7862 const Decl *D = cxcursor::getCursorDecl(C); 7863 const CXXMethodDecl *Method = 7864 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 7865 return (Method && Method->isDefaulted()) ? 1 : 0; 7866 } 7867 7868 unsigned clang_CXXMethod_isStatic(CXCursor C) { 7869 if (!clang_isDeclaration(C.kind)) 7870 return 0; 7871 7872 const Decl *D = cxcursor::getCursorDecl(C); 7873 const CXXMethodDecl *Method = 7874 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 7875 return (Method && Method->isStatic()) ? 1 : 0; 7876 } 7877 7878 unsigned clang_CXXMethod_isVirtual(CXCursor C) { 7879 if (!clang_isDeclaration(C.kind)) 7880 return 0; 7881 7882 const Decl *D = cxcursor::getCursorDecl(C); 7883 const CXXMethodDecl *Method = 7884 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 7885 return (Method && Method->isVirtual()) ? 1 : 0; 7886 } 7887 7888 unsigned clang_EnumDecl_isScoped(CXCursor C) { 7889 if (!clang_isDeclaration(C.kind)) 7890 return 0; 7891 7892 const Decl *D = cxcursor::getCursorDecl(C); 7893 auto *Enum = dyn_cast_or_null<EnumDecl>(D); 7894 return (Enum && Enum->isScoped()) ? 1 : 0; 7895 } 7896 7897 //===----------------------------------------------------------------------===// 7898 // Attribute introspection. 7899 //===----------------------------------------------------------------------===// 7900 7901 CXType clang_getIBOutletCollectionType(CXCursor C) { 7902 if (C.kind != CXCursor_IBOutletCollectionAttr) 7903 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C)); 7904 7905 const IBOutletCollectionAttr *A = 7906 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 7907 7908 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C)); 7909 } 7910 7911 //===----------------------------------------------------------------------===// 7912 // Inspecting memory usage. 7913 //===----------------------------------------------------------------------===// 7914 7915 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries; 7916 7917 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries, 7918 enum CXTUResourceUsageKind k, 7919 unsigned long amount) { 7920 CXTUResourceUsageEntry entry = { k, amount }; 7921 entries.push_back(entry); 7922 } 7923 7924 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) { 7925 const char *str = ""; 7926 switch (kind) { 7927 case CXTUResourceUsage_AST: 7928 str = "ASTContext: expressions, declarations, and types"; 7929 break; 7930 case CXTUResourceUsage_Identifiers: 7931 str = "ASTContext: identifiers"; 7932 break; 7933 case CXTUResourceUsage_Selectors: 7934 str = "ASTContext: selectors"; 7935 break; 7936 case CXTUResourceUsage_GlobalCompletionResults: 7937 str = "Code completion: cached global results"; 7938 break; 7939 case CXTUResourceUsage_SourceManagerContentCache: 7940 str = "SourceManager: content cache allocator"; 7941 break; 7942 case CXTUResourceUsage_AST_SideTables: 7943 str = "ASTContext: side tables"; 7944 break; 7945 case CXTUResourceUsage_SourceManager_Membuffer_Malloc: 7946 str = "SourceManager: malloc'ed memory buffers"; 7947 break; 7948 case CXTUResourceUsage_SourceManager_Membuffer_MMap: 7949 str = "SourceManager: mmap'ed memory buffers"; 7950 break; 7951 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc: 7952 str = "ExternalASTSource: malloc'ed memory buffers"; 7953 break; 7954 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap: 7955 str = "ExternalASTSource: mmap'ed memory buffers"; 7956 break; 7957 case CXTUResourceUsage_Preprocessor: 7958 str = "Preprocessor: malloc'ed memory"; 7959 break; 7960 case CXTUResourceUsage_PreprocessingRecord: 7961 str = "Preprocessor: PreprocessingRecord"; 7962 break; 7963 case CXTUResourceUsage_SourceManager_DataStructures: 7964 str = "SourceManager: data structures and tables"; 7965 break; 7966 case CXTUResourceUsage_Preprocessor_HeaderSearch: 7967 str = "Preprocessor: header search tables"; 7968 break; 7969 } 7970 return str; 7971 } 7972 7973 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) { 7974 if (isNotUsableTU(TU)) { 7975 LOG_BAD_TU(TU); 7976 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr }; 7977 return usage; 7978 } 7979 7980 ASTUnit *astUnit = cxtu::getASTUnit(TU); 7981 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries()); 7982 ASTContext &astContext = astUnit->getASTContext(); 7983 7984 // How much memory is used by AST nodes and types? 7985 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST, 7986 (unsigned long) astContext.getASTAllocatedMemory()); 7987 7988 // How much memory is used by identifiers? 7989 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers, 7990 (unsigned long) astContext.Idents.getAllocator().getTotalMemory()); 7991 7992 // How much memory is used for selectors? 7993 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors, 7994 (unsigned long) astContext.Selectors.getTotalMemory()); 7995 7996 // How much memory is used by ASTContext's side tables? 7997 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables, 7998 (unsigned long) astContext.getSideTableAllocatedMemory()); 7999 8000 // How much memory is used for caching global code completion results? 8001 unsigned long completionBytes = 0; 8002 if (GlobalCodeCompletionAllocator *completionAllocator = 8003 astUnit->getCachedCompletionAllocator().get()) { 8004 completionBytes = completionAllocator->getTotalMemory(); 8005 } 8006 createCXTUResourceUsageEntry(*entries, 8007 CXTUResourceUsage_GlobalCompletionResults, 8008 completionBytes); 8009 8010 // How much memory is being used by SourceManager's content cache? 8011 createCXTUResourceUsageEntry(*entries, 8012 CXTUResourceUsage_SourceManagerContentCache, 8013 (unsigned long) astContext.getSourceManager().getContentCacheSize()); 8014 8015 // How much memory is being used by the MemoryBuffer's in SourceManager? 8016 const SourceManager::MemoryBufferSizes &srcBufs = 8017 astUnit->getSourceManager().getMemoryBufferSizes(); 8018 8019 createCXTUResourceUsageEntry(*entries, 8020 CXTUResourceUsage_SourceManager_Membuffer_Malloc, 8021 (unsigned long) srcBufs.malloc_bytes); 8022 createCXTUResourceUsageEntry(*entries, 8023 CXTUResourceUsage_SourceManager_Membuffer_MMap, 8024 (unsigned long) srcBufs.mmap_bytes); 8025 createCXTUResourceUsageEntry(*entries, 8026 CXTUResourceUsage_SourceManager_DataStructures, 8027 (unsigned long) astContext.getSourceManager() 8028 .getDataStructureSizes()); 8029 8030 // How much memory is being used by the ExternalASTSource? 8031 if (ExternalASTSource *esrc = astContext.getExternalSource()) { 8032 const ExternalASTSource::MemoryBufferSizes &sizes = 8033 esrc->getMemoryBufferSizes(); 8034 8035 createCXTUResourceUsageEntry(*entries, 8036 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc, 8037 (unsigned long) sizes.malloc_bytes); 8038 createCXTUResourceUsageEntry(*entries, 8039 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap, 8040 (unsigned long) sizes.mmap_bytes); 8041 } 8042 8043 // How much memory is being used by the Preprocessor? 8044 Preprocessor &pp = astUnit->getPreprocessor(); 8045 createCXTUResourceUsageEntry(*entries, 8046 CXTUResourceUsage_Preprocessor, 8047 pp.getTotalMemory()); 8048 8049 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) { 8050 createCXTUResourceUsageEntry(*entries, 8051 CXTUResourceUsage_PreprocessingRecord, 8052 pRec->getTotalMemory()); 8053 } 8054 8055 createCXTUResourceUsageEntry(*entries, 8056 CXTUResourceUsage_Preprocessor_HeaderSearch, 8057 pp.getHeaderSearchInfo().getTotalMemory()); 8058 8059 CXTUResourceUsage usage = { (void*) entries.get(), 8060 (unsigned) entries->size(), 8061 !entries->empty() ? &(*entries)[0] : nullptr }; 8062 (void)entries.release(); 8063 return usage; 8064 } 8065 8066 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) { 8067 if (usage.data) 8068 delete (MemUsageEntries*) usage.data; 8069 } 8070 8071 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) { 8072 CXSourceRangeList *skipped = new CXSourceRangeList; 8073 skipped->count = 0; 8074 skipped->ranges = nullptr; 8075 8076 if (isNotUsableTU(TU)) { 8077 LOG_BAD_TU(TU); 8078 return skipped; 8079 } 8080 8081 if (!file) 8082 return skipped; 8083 8084 ASTUnit *astUnit = cxtu::getASTUnit(TU); 8085 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord(); 8086 if (!ppRec) 8087 return skipped; 8088 8089 ASTContext &Ctx = astUnit->getASTContext(); 8090 SourceManager &sm = Ctx.getSourceManager(); 8091 FileEntry *fileEntry = static_cast<FileEntry *>(file); 8092 FileID wantedFileID = sm.translateFile(fileEntry); 8093 8094 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges(); 8095 std::vector<SourceRange> wantedRanges; 8096 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end(); 8097 i != ei; ++i) { 8098 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID) 8099 wantedRanges.push_back(*i); 8100 } 8101 8102 skipped->count = wantedRanges.size(); 8103 skipped->ranges = new CXSourceRange[skipped->count]; 8104 for (unsigned i = 0, ei = skipped->count; i != ei; ++i) 8105 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]); 8106 8107 return skipped; 8108 } 8109 8110 CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) { 8111 CXSourceRangeList *skipped = new CXSourceRangeList; 8112 skipped->count = 0; 8113 skipped->ranges = nullptr; 8114 8115 if (isNotUsableTU(TU)) { 8116 LOG_BAD_TU(TU); 8117 return skipped; 8118 } 8119 8120 ASTUnit *astUnit = cxtu::getASTUnit(TU); 8121 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord(); 8122 if (!ppRec) 8123 return skipped; 8124 8125 ASTContext &Ctx = astUnit->getASTContext(); 8126 8127 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges(); 8128 8129 skipped->count = SkippedRanges.size(); 8130 skipped->ranges = new CXSourceRange[skipped->count]; 8131 for (unsigned i = 0, ei = skipped->count; i != ei; ++i) 8132 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]); 8133 8134 return skipped; 8135 } 8136 8137 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) { 8138 if (ranges) { 8139 delete[] ranges->ranges; 8140 delete ranges; 8141 } 8142 } 8143 8144 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) { 8145 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU); 8146 for (unsigned I = 0; I != Usage.numEntries; ++I) 8147 fprintf(stderr, " %s: %lu\n", 8148 clang_getTUResourceUsageName(Usage.entries[I].kind), 8149 Usage.entries[I].amount); 8150 8151 clang_disposeCXTUResourceUsage(Usage); 8152 } 8153 8154 //===----------------------------------------------------------------------===// 8155 // Misc. utility functions. 8156 //===----------------------------------------------------------------------===// 8157 8158 /// Default to using an 8 MB stack size on "safety" threads. 8159 static unsigned SafetyStackThreadSize = 8 << 20; 8160 8161 namespace clang { 8162 8163 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn, 8164 unsigned Size) { 8165 if (!Size) 8166 Size = GetSafetyThreadStackSize(); 8167 if (Size) 8168 return CRC.RunSafelyOnThread(Fn, Size); 8169 return CRC.RunSafely(Fn); 8170 } 8171 8172 unsigned GetSafetyThreadStackSize() { 8173 return SafetyStackThreadSize; 8174 } 8175 8176 void SetSafetyThreadStackSize(unsigned Value) { 8177 SafetyStackThreadSize = Value; 8178 } 8179 8180 } 8181 8182 void clang::setThreadBackgroundPriority() { 8183 if (getenv("LIBCLANG_BGPRIO_DISABLE")) 8184 return; 8185 8186 #ifdef USE_DARWIN_THREADS 8187 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG); 8188 #endif 8189 } 8190 8191 void cxindex::printDiagsToStderr(ASTUnit *Unit) { 8192 if (!Unit) 8193 return; 8194 8195 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 8196 DEnd = Unit->stored_diag_end(); 8197 D != DEnd; ++D) { 8198 CXStoredDiagnostic Diag(*D, Unit->getLangOpts()); 8199 CXString Msg = clang_formatDiagnostic(&Diag, 8200 clang_defaultDiagnosticDisplayOptions()); 8201 fprintf(stderr, "%s\n", clang_getCString(Msg)); 8202 clang_disposeString(Msg); 8203 } 8204 #ifdef LLVM_ON_WIN32 8205 // On Windows, force a flush, since there may be multiple copies of 8206 // stderr and stdout in the file system, all with different buffers 8207 // but writing to the same device. 8208 fflush(stderr); 8209 #endif 8210 } 8211 8212 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II, 8213 SourceLocation MacroDefLoc, 8214 CXTranslationUnit TU){ 8215 if (MacroDefLoc.isInvalid() || !TU) 8216 return nullptr; 8217 if (!II.hadMacroDefinition()) 8218 return nullptr; 8219 8220 ASTUnit *Unit = cxtu::getASTUnit(TU); 8221 Preprocessor &PP = Unit->getPreprocessor(); 8222 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II); 8223 if (MD) { 8224 for (MacroDirective::DefInfo 8225 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) { 8226 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc()) 8227 return Def.getMacroInfo(); 8228 } 8229 } 8230 8231 return nullptr; 8232 } 8233 8234 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef, 8235 CXTranslationUnit TU) { 8236 if (!MacroDef || !TU) 8237 return nullptr; 8238 const IdentifierInfo *II = MacroDef->getName(); 8239 if (!II) 8240 return nullptr; 8241 8242 return getMacroInfo(*II, MacroDef->getLocation(), TU); 8243 } 8244 8245 MacroDefinitionRecord * 8246 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok, 8247 CXTranslationUnit TU) { 8248 if (!MI || !TU) 8249 return nullptr; 8250 if (Tok.isNot(tok::raw_identifier)) 8251 return nullptr; 8252 8253 if (MI->getNumTokens() == 0) 8254 return nullptr; 8255 SourceRange DefRange(MI->getReplacementToken(0).getLocation(), 8256 MI->getDefinitionEndLoc()); 8257 ASTUnit *Unit = cxtu::getASTUnit(TU); 8258 8259 // Check that the token is inside the definition and not its argument list. 8260 SourceManager &SM = Unit->getSourceManager(); 8261 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin())) 8262 return nullptr; 8263 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation())) 8264 return nullptr; 8265 8266 Preprocessor &PP = Unit->getPreprocessor(); 8267 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 8268 if (!PPRec) 8269 return nullptr; 8270 8271 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier()); 8272 if (!II.hadMacroDefinition()) 8273 return nullptr; 8274 8275 // Check that the identifier is not one of the macro arguments. 8276 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end()) 8277 return nullptr; 8278 8279 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II); 8280 if (!InnerMD) 8281 return nullptr; 8282 8283 return PPRec->findMacroDefinition(InnerMD->getMacroInfo()); 8284 } 8285 8286 MacroDefinitionRecord * 8287 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc, 8288 CXTranslationUnit TU) { 8289 if (Loc.isInvalid() || !MI || !TU) 8290 return nullptr; 8291 8292 if (MI->getNumTokens() == 0) 8293 return nullptr; 8294 ASTUnit *Unit = cxtu::getASTUnit(TU); 8295 Preprocessor &PP = Unit->getPreprocessor(); 8296 if (!PP.getPreprocessingRecord()) 8297 return nullptr; 8298 Loc = Unit->getSourceManager().getSpellingLoc(Loc); 8299 Token Tok; 8300 if (PP.getRawToken(Loc, Tok)) 8301 return nullptr; 8302 8303 return checkForMacroInMacroDefinition(MI, Tok, TU); 8304 } 8305 8306 CXString clang_getClangVersion() { 8307 return cxstring::createDup(getClangFullVersion()); 8308 } 8309 8310 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) { 8311 if (TU) { 8312 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) { 8313 LogOS << '<' << Unit->getMainFileName() << '>'; 8314 if (Unit->isMainFileAST()) 8315 LogOS << " (" << Unit->getASTFileName() << ')'; 8316 return *this; 8317 } 8318 } else { 8319 LogOS << "<NULL TU>"; 8320 } 8321 return *this; 8322 } 8323 8324 Logger &cxindex::Logger::operator<<(const FileEntry *FE) { 8325 *this << FE->getName(); 8326 return *this; 8327 } 8328 8329 Logger &cxindex::Logger::operator<<(CXCursor cursor) { 8330 CXString cursorName = clang_getCursorDisplayName(cursor); 8331 *this << cursorName << "@" << clang_getCursorLocation(cursor); 8332 clang_disposeString(cursorName); 8333 return *this; 8334 } 8335 8336 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) { 8337 CXFile File; 8338 unsigned Line, Column; 8339 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr); 8340 CXString FileName = clang_getFileName(File); 8341 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column); 8342 clang_disposeString(FileName); 8343 return *this; 8344 } 8345 8346 Logger &cxindex::Logger::operator<<(CXSourceRange range) { 8347 CXSourceLocation BLoc = clang_getRangeStart(range); 8348 CXSourceLocation ELoc = clang_getRangeEnd(range); 8349 8350 CXFile BFile; 8351 unsigned BLine, BColumn; 8352 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr); 8353 8354 CXFile EFile; 8355 unsigned ELine, EColumn; 8356 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr); 8357 8358 CXString BFileName = clang_getFileName(BFile); 8359 if (BFile == EFile) { 8360 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName), 8361 BLine, BColumn, ELine, EColumn); 8362 } else { 8363 CXString EFileName = clang_getFileName(EFile); 8364 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName), 8365 BLine, BColumn) 8366 << llvm::format("%s:%d:%d]", clang_getCString(EFileName), 8367 ELine, EColumn); 8368 clang_disposeString(EFileName); 8369 } 8370 clang_disposeString(BFileName); 8371 return *this; 8372 } 8373 8374 Logger &cxindex::Logger::operator<<(CXString Str) { 8375 *this << clang_getCString(Str); 8376 return *this; 8377 } 8378 8379 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) { 8380 LogOS << Fmt; 8381 return *this; 8382 } 8383 8384 static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex; 8385 8386 cxindex::Logger::~Logger() { 8387 llvm::sys::ScopedLock L(*LoggingMutex); 8388 8389 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime(); 8390 8391 raw_ostream &OS = llvm::errs(); 8392 OS << "[libclang:" << Name << ':'; 8393 8394 #ifdef USE_DARWIN_THREADS 8395 // TODO: Portability. 8396 mach_port_t tid = pthread_mach_thread_np(pthread_self()); 8397 OS << tid << ':'; 8398 #endif 8399 8400 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime(); 8401 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime()); 8402 OS << Msg << '\n'; 8403 8404 if (Trace) { 8405 llvm::sys::PrintStackTrace(OS); 8406 OS << "--------------------------------------------------\n"; 8407 } 8408 } 8409 8410 #ifdef CLANG_TOOL_EXTRA_BUILD 8411 // This anchor is used to force the linker to link the clang-tidy plugin. 8412 extern volatile int ClangTidyPluginAnchorSource; 8413 static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination = 8414 ClangTidyPluginAnchorSource; 8415 8416 // This anchor is used to force the linker to link the clang-include-fixer 8417 // plugin. 8418 extern volatile int ClangIncludeFixerPluginAnchorSource; 8419 static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination = 8420 ClangIncludeFixerPluginAnchorSource; 8421 #endif 8422