Home | History | Annotate | Download | only in libclang
      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 "CIndexer.h"
     16 #include "CIndexDiagnostic.h"
     17 #include "CLog.h"
     18 #include "CXComment.h"
     19 #include "CXCursor.h"
     20 #include "CXSourceLocation.h"
     21 #include "CXString.h"
     22 #include "CXTranslationUnit.h"
     23 #include "CXType.h"
     24 #include "CursorVisitor.h"
     25 #include "SimpleFormatContext.h"
     26 #include "clang/AST/StmtVisitor.h"
     27 #include "clang/Basic/Diagnostic.h"
     28 #include "clang/Basic/Version.h"
     29 #include "clang/Frontend/ASTUnit.h"
     30 #include "clang/Frontend/CompilerInstance.h"
     31 #include "clang/Frontend/FrontendDiagnostic.h"
     32 #include "clang/Lex/HeaderSearch.h"
     33 #include "clang/Lex/Lexer.h"
     34 #include "clang/Lex/PreprocessingRecord.h"
     35 #include "clang/Lex/Preprocessor.h"
     36 #include "llvm/ADT/Optional.h"
     37 #include "llvm/ADT/STLExtras.h"
     38 #include "llvm/ADT/StringSwitch.h"
     39 #include "llvm/Config/config.h"
     40 #include "llvm/Support/Compiler.h"
     41 #include "llvm/Support/CrashRecoveryContext.h"
     42 #include "llvm/Support/Format.h"
     43 #include "llvm/Support/MemoryBuffer.h"
     44 #include "llvm/Support/Mutex.h"
     45 #include "llvm/Support/PrettyStackTrace.h"
     46 #include "llvm/Support/Program.h"
     47 #include "llvm/Support/SaveAndRestore.h"
     48 #include "llvm/Support/Signals.h"
     49 #include "llvm/Support/Threading.h"
     50 #include "llvm/Support/Timer.h"
     51 #include "llvm/Support/raw_ostream.h"
     52 
     53 #if HAVE_PTHREAD_H
     54 #include <pthread.h>
     55 #endif
     56 
     57 using namespace clang;
     58 using namespace clang::cxcursor;
     59 using namespace clang::cxtu;
     60 using namespace clang::cxindex;
     61 
     62 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) {
     63   if (!AU)
     64     return 0;
     65   CXTranslationUnit D = new CXTranslationUnitImpl();
     66   D->CIdx = CIdx;
     67   D->TheASTUnit = AU;
     68   D->StringPool = new cxstring::CXStringPool();
     69   D->Diagnostics = 0;
     70   D->OverridenCursorsPool = createOverridenCXCursorsPool();
     71   D->FormatContext = 0;
     72   D->FormatInMemoryUniqueId = 0;
     73   return D;
     74 }
     75 
     76 cxtu::CXTUOwner::~CXTUOwner() {
     77   if (TU)
     78     clang_disposeTranslationUnit(TU);
     79 }
     80 
     81 /// \brief Compare two source ranges to determine their relative position in
     82 /// the translation unit.
     83 static RangeComparisonResult RangeCompare(SourceManager &SM,
     84                                           SourceRange R1,
     85                                           SourceRange R2) {
     86   assert(R1.isValid() && "First range is invalid?");
     87   assert(R2.isValid() && "Second range is invalid?");
     88   if (R1.getEnd() != R2.getBegin() &&
     89       SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
     90     return RangeBefore;
     91   if (R2.getEnd() != R1.getBegin() &&
     92       SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
     93     return RangeAfter;
     94   return RangeOverlap;
     95 }
     96 
     97 /// \brief Determine if a source location falls within, before, or after a
     98 ///   a given source range.
     99 static RangeComparisonResult LocationCompare(SourceManager &SM,
    100                                              SourceLocation L, SourceRange R) {
    101   assert(R.isValid() && "First range is invalid?");
    102   assert(L.isValid() && "Second range is invalid?");
    103   if (L == R.getBegin() || L == R.getEnd())
    104     return RangeOverlap;
    105   if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
    106     return RangeBefore;
    107   if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
    108     return RangeAfter;
    109   return RangeOverlap;
    110 }
    111 
    112 /// \brief Translate a Clang source range into a CIndex source range.
    113 ///
    114 /// Clang internally represents ranges where the end location points to the
    115 /// start of the token at the end. However, for external clients it is more
    116 /// useful to have a CXSourceRange be a proper half-open interval. This routine
    117 /// does the appropriate translation.
    118 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
    119                                           const LangOptions &LangOpts,
    120                                           const CharSourceRange &R) {
    121   // We want the last character in this location, so we will adjust the
    122   // location accordingly.
    123   SourceLocation EndLoc = R.getEnd();
    124   if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
    125     EndLoc = SM.getExpansionRange(EndLoc).second;
    126   if (R.isTokenRange() && !EndLoc.isInvalid()) {
    127     unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
    128                                                 SM, LangOpts);
    129     EndLoc = EndLoc.getLocWithOffset(Length);
    130   }
    131 
    132   CXSourceRange Result = {
    133     { &SM, &LangOpts },
    134     R.getBegin().getRawEncoding(),
    135     EndLoc.getRawEncoding()
    136   };
    137   return Result;
    138 }
    139 
    140 //===----------------------------------------------------------------------===//
    141 // Cursor visitor.
    142 //===----------------------------------------------------------------------===//
    143 
    144 static SourceRange getRawCursorExtent(CXCursor C);
    145 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
    146 
    147 
    148 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
    149   return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
    150 }
    151 
    152 /// \brief Visit the given cursor and, if requested by the visitor,
    153 /// its children.
    154 ///
    155 /// \param Cursor the cursor to visit.
    156 ///
    157 /// \param CheckedRegionOfInterest if true, then the caller already checked
    158 /// that this cursor is within the region of interest.
    159 ///
    160 /// \returns true if the visitation should be aborted, false if it
    161 /// should continue.
    162 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
    163   if (clang_isInvalid(Cursor.kind))
    164     return false;
    165 
    166   if (clang_isDeclaration(Cursor.kind)) {
    167     const Decl *D = getCursorDecl(Cursor);
    168     if (!D) {
    169       assert(0 && "Invalid declaration cursor");
    170       return true; // abort.
    171     }
    172 
    173     // Ignore implicit declarations, unless it's an objc method because
    174     // currently we should report implicit methods for properties when indexing.
    175     if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
    176       return false;
    177   }
    178 
    179   // If we have a range of interest, and this cursor doesn't intersect with it,
    180   // we're done.
    181   if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
    182     SourceRange Range = getRawCursorExtent(Cursor);
    183     if (Range.isInvalid() || CompareRegionOfInterest(Range))
    184       return false;
    185   }
    186 
    187   switch (Visitor(Cursor, Parent, ClientData)) {
    188   case CXChildVisit_Break:
    189     return true;
    190 
    191   case CXChildVisit_Continue:
    192     return false;
    193 
    194   case CXChildVisit_Recurse: {
    195     bool ret = VisitChildren(Cursor);
    196     if (PostChildrenVisitor)
    197       if (PostChildrenVisitor(Cursor, ClientData))
    198         return true;
    199     return ret;
    200   }
    201   }
    202 
    203   llvm_unreachable("Invalid CXChildVisitResult!");
    204 }
    205 
    206 static bool visitPreprocessedEntitiesInRange(SourceRange R,
    207                                              PreprocessingRecord &PPRec,
    208                                              CursorVisitor &Visitor) {
    209   SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
    210   FileID FID;
    211 
    212   if (!Visitor.shouldVisitIncludedEntities()) {
    213     // If the begin/end of the range lie in the same FileID, do the optimization
    214     // where we skip preprocessed entities that do not come from the same FileID.
    215     FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
    216     if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
    217       FID = FileID();
    218   }
    219 
    220   std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
    221     Entities = PPRec.getPreprocessedEntitiesInRange(R);
    222   return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
    223                                            PPRec, FID);
    224 }
    225 
    226 bool CursorVisitor::visitFileRegion() {
    227   if (RegionOfInterest.isInvalid())
    228     return false;
    229 
    230   ASTUnit *Unit = cxtu::getASTUnit(TU);
    231   SourceManager &SM = Unit->getSourceManager();
    232 
    233   std::pair<FileID, unsigned>
    234     Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
    235     End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
    236 
    237   if (End.first != Begin.first) {
    238     // If the end does not reside in the same file, try to recover by
    239     // picking the end of the file of begin location.
    240     End.first = Begin.first;
    241     End.second = SM.getFileIDSize(Begin.first);
    242   }
    243 
    244   assert(Begin.first == End.first);
    245   if (Begin.second > End.second)
    246     return false;
    247 
    248   FileID File = Begin.first;
    249   unsigned Offset = Begin.second;
    250   unsigned Length = End.second - Begin.second;
    251 
    252   if (!VisitDeclsOnly && !VisitPreprocessorLast)
    253     if (visitPreprocessedEntitiesInRegion())
    254       return true; // visitation break.
    255 
    256   if (visitDeclsFromFileRegion(File, Offset, Length))
    257     return true; // visitation break.
    258 
    259   if (!VisitDeclsOnly && VisitPreprocessorLast)
    260     return visitPreprocessedEntitiesInRegion();
    261 
    262   return false;
    263 }
    264 
    265 static bool isInLexicalContext(Decl *D, DeclContext *DC) {
    266   if (!DC)
    267     return false;
    268 
    269   for (DeclContext *DeclDC = D->getLexicalDeclContext();
    270          DeclDC; DeclDC = DeclDC->getLexicalParent()) {
    271     if (DeclDC == DC)
    272       return true;
    273   }
    274   return false;
    275 }
    276 
    277 bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
    278                                              unsigned Offset, unsigned Length) {
    279   ASTUnit *Unit = cxtu::getASTUnit(TU);
    280   SourceManager &SM = Unit->getSourceManager();
    281   SourceRange Range = RegionOfInterest;
    282 
    283   SmallVector<Decl *, 16> Decls;
    284   Unit->findFileRegionDecls(File, Offset, Length, Decls);
    285 
    286   // If we didn't find any file level decls for the file, try looking at the
    287   // file that it was included from.
    288   while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
    289     bool Invalid = false;
    290     const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
    291     if (Invalid)
    292       return false;
    293 
    294     SourceLocation Outer;
    295     if (SLEntry.isFile())
    296       Outer = SLEntry.getFile().getIncludeLoc();
    297     else
    298       Outer = SLEntry.getExpansion().getExpansionLocStart();
    299     if (Outer.isInvalid())
    300       return false;
    301 
    302     llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
    303     Length = 0;
    304     Unit->findFileRegionDecls(File, Offset, Length, Decls);
    305   }
    306 
    307   assert(!Decls.empty());
    308 
    309   bool VisitedAtLeastOnce = false;
    310   DeclContext *CurDC = 0;
    311   SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
    312   for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
    313     Decl *D = *DIt;
    314     if (D->getSourceRange().isInvalid())
    315       continue;
    316 
    317     if (isInLexicalContext(D, CurDC))
    318       continue;
    319 
    320     CurDC = dyn_cast<DeclContext>(D);
    321 
    322     if (TagDecl *TD = dyn_cast<TagDecl>(D))
    323       if (!TD->isFreeStanding())
    324         continue;
    325 
    326     RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
    327     if (CompRes == RangeBefore)
    328       continue;
    329     if (CompRes == RangeAfter)
    330       break;
    331 
    332     assert(CompRes == RangeOverlap);
    333     VisitedAtLeastOnce = true;
    334 
    335     if (isa<ObjCContainerDecl>(D)) {
    336       FileDI_current = &DIt;
    337       FileDE_current = DE;
    338     } else {
    339       FileDI_current = 0;
    340     }
    341 
    342     if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
    343       return true; // visitation break.
    344   }
    345 
    346   if (VisitedAtLeastOnce)
    347     return false;
    348 
    349   // No Decls overlapped with the range. Move up the lexical context until there
    350   // is a context that contains the range or we reach the translation unit
    351   // level.
    352   DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
    353                                          : (*(DIt-1))->getLexicalDeclContext();
    354 
    355   while (DC && !DC->isTranslationUnit()) {
    356     Decl *D = cast<Decl>(DC);
    357     SourceRange CurDeclRange = D->getSourceRange();
    358     if (CurDeclRange.isInvalid())
    359       break;
    360 
    361     if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
    362       if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
    363         return true; // visitation break.
    364     }
    365 
    366     DC = D->getLexicalDeclContext();
    367   }
    368 
    369   return false;
    370 }
    371 
    372 bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
    373   if (!AU->getPreprocessor().getPreprocessingRecord())
    374     return false;
    375 
    376   PreprocessingRecord &PPRec
    377     = *AU->getPreprocessor().getPreprocessingRecord();
    378   SourceManager &SM = AU->getSourceManager();
    379 
    380   if (RegionOfInterest.isValid()) {
    381     SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
    382     SourceLocation B = MappedRange.getBegin();
    383     SourceLocation E = MappedRange.getEnd();
    384 
    385     if (AU->isInPreambleFileID(B)) {
    386       if (SM.isLoadedSourceLocation(E))
    387         return visitPreprocessedEntitiesInRange(SourceRange(B, E),
    388                                                  PPRec, *this);
    389 
    390       // Beginning of range lies in the preamble but it also extends beyond
    391       // it into the main file. Split the range into 2 parts, one covering
    392       // the preamble and another covering the main file. This allows subsequent
    393       // calls to visitPreprocessedEntitiesInRange to accept a source range that
    394       // lies in the same FileID, allowing it to skip preprocessed entities that
    395       // do not come from the same FileID.
    396       bool breaked =
    397         visitPreprocessedEntitiesInRange(
    398                                    SourceRange(B, AU->getEndOfPreambleFileID()),
    399                                           PPRec, *this);
    400       if (breaked) return true;
    401       return visitPreprocessedEntitiesInRange(
    402                                     SourceRange(AU->getStartOfMainFileID(), E),
    403                                         PPRec, *this);
    404     }
    405 
    406     return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
    407   }
    408 
    409   bool OnlyLocalDecls
    410     = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
    411 
    412   if (OnlyLocalDecls)
    413     return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
    414                                      PPRec);
    415 
    416   return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
    417 }
    418 
    419 template<typename InputIterator>
    420 bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
    421                                               InputIterator Last,
    422                                               PreprocessingRecord &PPRec,
    423                                               FileID FID) {
    424   for (; First != Last; ++First) {
    425     if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
    426       continue;
    427 
    428     PreprocessedEntity *PPE = *First;
    429     if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
    430       if (Visit(MakeMacroExpansionCursor(ME, TU)))
    431         return true;
    432 
    433       continue;
    434     }
    435 
    436     if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
    437       if (Visit(MakeMacroDefinitionCursor(MD, TU)))
    438         return true;
    439 
    440       continue;
    441     }
    442 
    443     if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
    444       if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
    445         return true;
    446 
    447       continue;
    448     }
    449   }
    450 
    451   return false;
    452 }
    453 
    454 /// \brief Visit the children of the given cursor.
    455 ///
    456 /// \returns true if the visitation should be aborted, false if it
    457 /// should continue.
    458 bool CursorVisitor::VisitChildren(CXCursor Cursor) {
    459   if (clang_isReference(Cursor.kind) &&
    460       Cursor.kind != CXCursor_CXXBaseSpecifier) {
    461     // By definition, references have no children.
    462     return false;
    463   }
    464 
    465   // Set the Parent field to Cursor, then back to its old value once we're
    466   // done.
    467   SetParentRAII SetParent(Parent, StmtParent, Cursor);
    468 
    469   if (clang_isDeclaration(Cursor.kind)) {
    470     Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
    471     if (!D)
    472       return false;
    473 
    474     return VisitAttributes(D) || Visit(D);
    475   }
    476 
    477   if (clang_isStatement(Cursor.kind)) {
    478     if (const Stmt *S = getCursorStmt(Cursor))
    479       return Visit(S);
    480 
    481     return false;
    482   }
    483 
    484   if (clang_isExpression(Cursor.kind)) {
    485     if (const Expr *E = getCursorExpr(Cursor))
    486       return Visit(E);
    487 
    488     return false;
    489   }
    490 
    491   if (clang_isTranslationUnit(Cursor.kind)) {
    492     CXTranslationUnit TU = getCursorTU(Cursor);
    493     ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
    494 
    495     int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
    496     for (unsigned I = 0; I != 2; ++I) {
    497       if (VisitOrder[I]) {
    498         if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
    499             RegionOfInterest.isInvalid()) {
    500           for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
    501                                         TLEnd = CXXUnit->top_level_end();
    502                TL != TLEnd; ++TL) {
    503             if (Visit(MakeCXCursor(*TL, TU, RegionOfInterest), true))
    504               return true;
    505           }
    506         } else if (VisitDeclContext(
    507                                 CXXUnit->getASTContext().getTranslationUnitDecl()))
    508           return true;
    509         continue;
    510       }
    511 
    512       // Walk the preprocessing record.
    513       if (CXXUnit->getPreprocessor().getPreprocessingRecord())
    514         visitPreprocessedEntitiesInRegion();
    515     }
    516 
    517     return false;
    518   }
    519 
    520   if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
    521     if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
    522       if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
    523         return Visit(BaseTSInfo->getTypeLoc());
    524       }
    525     }
    526   }
    527 
    528   if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
    529     const IBOutletCollectionAttr *A =
    530       cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
    531     if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
    532       return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
    533                                                     A->getInterfaceLoc(), TU));
    534   }
    535 
    536   // If pointing inside a macro definition, check if the token is an identifier
    537   // that was ever defined as a macro. In such a case, create a "pseudo" macro
    538   // expansion cursor for that token.
    539   SourceLocation BeginLoc = RegionOfInterest.getBegin();
    540   if (Cursor.kind == CXCursor_MacroDefinition &&
    541       BeginLoc == RegionOfInterest.getEnd()) {
    542     SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
    543     const MacroInfo *MI =
    544         getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
    545     if (MacroDefinition *MacroDef =
    546           checkForMacroInMacroDefinition(MI, Loc, TU))
    547       return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
    548   }
    549 
    550   // Nothing to visit at the moment.
    551   return false;
    552 }
    553 
    554 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
    555   if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
    556     if (Visit(TSInfo->getTypeLoc()))
    557         return true;
    558 
    559   if (Stmt *Body = B->getBody())
    560     return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
    561 
    562   return false;
    563 }
    564 
    565 Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
    566   if (RegionOfInterest.isValid()) {
    567     SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
    568     if (Range.isInvalid())
    569       return None;
    570 
    571     switch (CompareRegionOfInterest(Range)) {
    572     case RangeBefore:
    573       // This declaration comes before the region of interest; skip it.
    574       return None;
    575 
    576     case RangeAfter:
    577       // This declaration comes after the region of interest; we're done.
    578       return false;
    579 
    580     case RangeOverlap:
    581       // This declaration overlaps the region of interest; visit it.
    582       break;
    583     }
    584   }
    585   return true;
    586 }
    587 
    588 bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
    589   DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
    590 
    591   // FIXME: Eventually remove.  This part of a hack to support proper
    592   // iteration over all Decls contained lexically within an ObjC container.
    593   SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
    594   SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
    595 
    596   for ( ; I != E; ++I) {
    597     Decl *D = *I;
    598     if (D->getLexicalDeclContext() != DC)
    599       continue;
    600     CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
    601 
    602     // Ignore synthesized ivars here, otherwise if we have something like:
    603     //   @synthesize prop = _prop;
    604     // and '_prop' is not declared, we will encounter a '_prop' ivar before
    605     // encountering the 'prop' synthesize declaration and we will think that
    606     // we passed the region-of-interest.
    607     if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
    608       if (ivarD->getSynthesize())
    609         continue;
    610     }
    611 
    612     // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
    613     // declarations is a mismatch with the compiler semantics.
    614     if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
    615       ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
    616       if (!ID->isThisDeclarationADefinition())
    617         Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
    618 
    619     } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
    620       ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
    621       if (!PD->isThisDeclarationADefinition())
    622         Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
    623     }
    624 
    625     const Optional<bool> &V = shouldVisitCursor(Cursor);
    626     if (!V.hasValue())
    627       continue;
    628     if (!V.getValue())
    629       return false;
    630     if (Visit(Cursor, true))
    631       return true;
    632   }
    633   return false;
    634 }
    635 
    636 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
    637   llvm_unreachable("Translation units are visited directly by Visit()");
    638 }
    639 
    640 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
    641   if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
    642     return Visit(TSInfo->getTypeLoc());
    643 
    644   return false;
    645 }
    646 
    647 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
    648   if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
    649     return Visit(TSInfo->getTypeLoc());
    650 
    651   return false;
    652 }
    653 
    654 bool CursorVisitor::VisitTagDecl(TagDecl *D) {
    655   return VisitDeclContext(D);
    656 }
    657 
    658 bool CursorVisitor::VisitClassTemplateSpecializationDecl(
    659                                           ClassTemplateSpecializationDecl *D) {
    660   bool ShouldVisitBody = false;
    661   switch (D->getSpecializationKind()) {
    662   case TSK_Undeclared:
    663   case TSK_ImplicitInstantiation:
    664     // Nothing to visit
    665     return false;
    666 
    667   case TSK_ExplicitInstantiationDeclaration:
    668   case TSK_ExplicitInstantiationDefinition:
    669     break;
    670 
    671   case TSK_ExplicitSpecialization:
    672     ShouldVisitBody = true;
    673     break;
    674   }
    675 
    676   // Visit the template arguments used in the specialization.
    677   if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
    678     TypeLoc TL = SpecType->getTypeLoc();
    679     if (TemplateSpecializationTypeLoc TSTLoc =
    680             TL.getAs<TemplateSpecializationTypeLoc>()) {
    681       for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
    682         if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
    683           return true;
    684     }
    685   }
    686 
    687   if (ShouldVisitBody && VisitCXXRecordDecl(D))
    688     return true;
    689 
    690   return false;
    691 }
    692 
    693 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
    694                                    ClassTemplatePartialSpecializationDecl *D) {
    695   // FIXME: Visit the "outer" template parameter lists on the TagDecl
    696   // before visiting these template parameters.
    697   if (VisitTemplateParameters(D->getTemplateParameters()))
    698     return true;
    699 
    700   // Visit the partial specialization arguments.
    701   const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
    702   for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
    703     if (VisitTemplateArgumentLoc(TemplateArgs[I]))
    704       return true;
    705 
    706   return VisitCXXRecordDecl(D);
    707 }
    708 
    709 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
    710   // Visit the default argument.
    711   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
    712     if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
    713       if (Visit(DefArg->getTypeLoc()))
    714         return true;
    715 
    716   return false;
    717 }
    718 
    719 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
    720   if (Expr *Init = D->getInitExpr())
    721     return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
    722   return false;
    723 }
    724 
    725 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
    726   if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
    727     if (Visit(TSInfo->getTypeLoc()))
    728       return true;
    729 
    730   // Visit the nested-name-specifier, if present.
    731   if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
    732     if (VisitNestedNameSpecifierLoc(QualifierLoc))
    733       return true;
    734 
    735   return false;
    736 }
    737 
    738 /// \brief Compare two base or member initializers based on their source order.
    739 static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
    740   CXXCtorInitializer const * const *X
    741     = static_cast<CXXCtorInitializer const * const *>(Xp);
    742   CXXCtorInitializer const * const *Y
    743     = static_cast<CXXCtorInitializer const * const *>(Yp);
    744 
    745   if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
    746     return -1;
    747   else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
    748     return 1;
    749   else
    750     return 0;
    751 }
    752 
    753 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
    754   if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
    755     // Visit the function declaration's syntactic components in the order
    756     // written. This requires a bit of work.
    757     TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
    758     FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
    759 
    760     // If we have a function declared directly (without the use of a typedef),
    761     // visit just the return type. Otherwise, just visit the function's type
    762     // now.
    763     if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getResultLoc())) ||
    764         (!FTL && Visit(TL)))
    765       return true;
    766 
    767     // Visit the nested-name-specifier, if present.
    768     if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
    769       if (VisitNestedNameSpecifierLoc(QualifierLoc))
    770         return true;
    771 
    772     // Visit the declaration name.
    773     if (VisitDeclarationNameInfo(ND->getNameInfo()))
    774       return true;
    775 
    776     // FIXME: Visit explicitly-specified template arguments!
    777 
    778     // Visit the function parameters, if we have a function type.
    779     if (FTL && VisitFunctionTypeLoc(FTL, true))
    780       return true;
    781 
    782     // FIXME: Attributes?
    783   }
    784 
    785   if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
    786     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
    787       // Find the initializers that were written in the source.
    788       SmallVector<CXXCtorInitializer *, 4> WrittenInits;
    789       for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
    790                                           IEnd = Constructor->init_end();
    791            I != IEnd; ++I) {
    792         if (!(*I)->isWritten())
    793           continue;
    794 
    795         WrittenInits.push_back(*I);
    796       }
    797 
    798       // Sort the initializers in source order
    799       llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
    800                            &CompareCXXCtorInitializers);
    801 
    802       // Visit the initializers in source order
    803       for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
    804         CXXCtorInitializer *Init = WrittenInits[I];
    805         if (Init->isAnyMemberInitializer()) {
    806           if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
    807                                         Init->getMemberLocation(), TU)))
    808             return true;
    809         } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
    810           if (Visit(TInfo->getTypeLoc()))
    811             return true;
    812         }
    813 
    814         // Visit the initializer value.
    815         if (Expr *Initializer = Init->getInit())
    816           if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
    817             return true;
    818       }
    819     }
    820 
    821     if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
    822       return true;
    823   }
    824 
    825   return false;
    826 }
    827 
    828 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
    829   if (VisitDeclaratorDecl(D))
    830     return true;
    831 
    832   if (Expr *BitWidth = D->getBitWidth())
    833     return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
    834 
    835   return false;
    836 }
    837 
    838 bool CursorVisitor::VisitVarDecl(VarDecl *D) {
    839   if (VisitDeclaratorDecl(D))
    840     return true;
    841 
    842   if (Expr *Init = D->getInit())
    843     return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
    844 
    845   return false;
    846 }
    847 
    848 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
    849   if (VisitDeclaratorDecl(D))
    850     return true;
    851 
    852   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
    853     if (Expr *DefArg = D->getDefaultArgument())
    854       return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
    855 
    856   return false;
    857 }
    858 
    859 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
    860   // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
    861   // before visiting these template parameters.
    862   if (VisitTemplateParameters(D->getTemplateParameters()))
    863     return true;
    864 
    865   return VisitFunctionDecl(D->getTemplatedDecl());
    866 }
    867 
    868 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
    869   // FIXME: Visit the "outer" template parameter lists on the TagDecl
    870   // before visiting these template parameters.
    871   if (VisitTemplateParameters(D->getTemplateParameters()))
    872     return true;
    873 
    874   return VisitCXXRecordDecl(D->getTemplatedDecl());
    875 }
    876 
    877 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
    878   if (VisitTemplateParameters(D->getTemplateParameters()))
    879     return true;
    880 
    881   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
    882       VisitTemplateArgumentLoc(D->getDefaultArgument()))
    883     return true;
    884 
    885   return false;
    886 }
    887 
    888 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
    889   if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
    890     if (Visit(TSInfo->getTypeLoc()))
    891       return true;
    892 
    893   for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
    894        PEnd = ND->param_end();
    895        P != PEnd; ++P) {
    896     if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
    897       return true;
    898   }
    899 
    900   if (ND->isThisDeclarationADefinition() &&
    901       Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
    902     return true;
    903 
    904   return false;
    905 }
    906 
    907 template <typename DeclIt>
    908 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
    909                                       SourceManager &SM, SourceLocation EndLoc,
    910                                       SmallVectorImpl<Decl *> &Decls) {
    911   DeclIt next = *DI_current;
    912   while (++next != DE_current) {
    913     Decl *D_next = *next;
    914     if (!D_next)
    915       break;
    916     SourceLocation L = D_next->getLocStart();
    917     if (!L.isValid())
    918       break;
    919     if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
    920       *DI_current = next;
    921       Decls.push_back(D_next);
    922       continue;
    923     }
    924     break;
    925   }
    926 }
    927 
    928 namespace {
    929   struct ContainerDeclsSort {
    930     SourceManager &SM;
    931     ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
    932     bool operator()(Decl *A, Decl *B) {
    933       SourceLocation L_A = A->getLocStart();
    934       SourceLocation L_B = B->getLocStart();
    935       assert(L_A.isValid() && L_B.isValid());
    936       return SM.isBeforeInTranslationUnit(L_A, L_B);
    937     }
    938   };
    939 }
    940 
    941 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
    942   // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
    943   // an @implementation can lexically contain Decls that are not properly
    944   // nested in the AST.  When we identify such cases, we need to retrofit
    945   // this nesting here.
    946   if (!DI_current && !FileDI_current)
    947     return VisitDeclContext(D);
    948 
    949   // Scan the Decls that immediately come after the container
    950   // in the current DeclContext.  If any fall within the
    951   // container's lexical region, stash them into a vector
    952   // for later processing.
    953   SmallVector<Decl *, 24> DeclsInContainer;
    954   SourceLocation EndLoc = D->getSourceRange().getEnd();
    955   SourceManager &SM = AU->getSourceManager();
    956   if (EndLoc.isValid()) {
    957     if (DI_current) {
    958       addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
    959                                 DeclsInContainer);
    960     } else {
    961       addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
    962                                 DeclsInContainer);
    963     }
    964   }
    965 
    966   // The common case.
    967   if (DeclsInContainer.empty())
    968     return VisitDeclContext(D);
    969 
    970   // Get all the Decls in the DeclContext, and sort them with the
    971   // additional ones we've collected.  Then visit them.
    972   for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
    973        I!=E; ++I) {
    974     Decl *subDecl = *I;
    975     if (!subDecl || subDecl->getLexicalDeclContext() != D ||
    976         subDecl->getLocStart().isInvalid())
    977       continue;
    978     DeclsInContainer.push_back(subDecl);
    979   }
    980 
    981   // Now sort the Decls so that they appear in lexical order.
    982   std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
    983             ContainerDeclsSort(SM));
    984 
    985   // Now visit the decls.
    986   for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
    987          E = DeclsInContainer.end(); I != E; ++I) {
    988     CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
    989     const Optional<bool> &V = shouldVisitCursor(Cursor);
    990     if (!V.hasValue())
    991       continue;
    992     if (!V.getValue())
    993       return false;
    994     if (Visit(Cursor, true))
    995       return true;
    996   }
    997   return false;
    998 }
    999 
   1000 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
   1001   if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
   1002                                    TU)))
   1003     return true;
   1004 
   1005   ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
   1006   for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
   1007          E = ND->protocol_end(); I != E; ++I, ++PL)
   1008     if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
   1009       return true;
   1010 
   1011   return VisitObjCContainerDecl(ND);
   1012 }
   1013 
   1014 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
   1015   if (!PID->isThisDeclarationADefinition())
   1016     return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
   1017 
   1018   ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
   1019   for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
   1020        E = PID->protocol_end(); I != E; ++I, ++PL)
   1021     if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
   1022       return true;
   1023 
   1024   return VisitObjCContainerDecl(PID);
   1025 }
   1026 
   1027 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
   1028   if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
   1029     return true;
   1030 
   1031   // FIXME: This implements a workaround with @property declarations also being
   1032   // installed in the DeclContext for the @interface.  Eventually this code
   1033   // should be removed.
   1034   ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
   1035   if (!CDecl || !CDecl->IsClassExtension())
   1036     return false;
   1037 
   1038   ObjCInterfaceDecl *ID = CDecl->getClassInterface();
   1039   if (!ID)
   1040     return false;
   1041 
   1042   IdentifierInfo *PropertyId = PD->getIdentifier();
   1043   ObjCPropertyDecl *prevDecl =
   1044     ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
   1045 
   1046   if (!prevDecl)
   1047     return false;
   1048 
   1049   // Visit synthesized methods since they will be skipped when visiting
   1050   // the @interface.
   1051   if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
   1052     if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
   1053       if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
   1054         return true;
   1055 
   1056   if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
   1057     if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
   1058       if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
   1059         return true;
   1060 
   1061   return false;
   1062 }
   1063 
   1064 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
   1065   if (!D->isThisDeclarationADefinition()) {
   1066     // Forward declaration is treated like a reference.
   1067     return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
   1068   }
   1069 
   1070   // Issue callbacks for super class.
   1071   if (D->getSuperClass() &&
   1072       Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
   1073                                         D->getSuperClassLoc(),
   1074                                         TU)))
   1075     return true;
   1076 
   1077   ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
   1078   for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
   1079          E = D->protocol_end(); I != E; ++I, ++PL)
   1080     if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
   1081       return true;
   1082 
   1083   return VisitObjCContainerDecl(D);
   1084 }
   1085 
   1086 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
   1087   return VisitObjCContainerDecl(D);
   1088 }
   1089 
   1090 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
   1091   // 'ID' could be null when dealing with invalid code.
   1092   if (ObjCInterfaceDecl *ID = D->getClassInterface())
   1093     if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
   1094       return true;
   1095 
   1096   return VisitObjCImplDecl(D);
   1097 }
   1098 
   1099 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
   1100 #if 0
   1101   // Issue callbacks for super class.
   1102   // FIXME: No source location information!
   1103   if (D->getSuperClass() &&
   1104       Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
   1105                                         D->getSuperClassLoc(),
   1106                                         TU)))
   1107     return true;
   1108 #endif
   1109 
   1110   return VisitObjCImplDecl(D);
   1111 }
   1112 
   1113 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
   1114   if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
   1115     if (PD->isIvarNameSpecified())
   1116       return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
   1117 
   1118   return false;
   1119 }
   1120 
   1121 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
   1122   return VisitDeclContext(D);
   1123 }
   1124 
   1125 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
   1126   // Visit nested-name-specifier.
   1127   if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
   1128     if (VisitNestedNameSpecifierLoc(QualifierLoc))
   1129       return true;
   1130 
   1131   return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
   1132                                       D->getTargetNameLoc(), TU));
   1133 }
   1134 
   1135 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
   1136   // Visit nested-name-specifier.
   1137   if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
   1138     if (VisitNestedNameSpecifierLoc(QualifierLoc))
   1139       return true;
   1140   }
   1141 
   1142   if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
   1143     return true;
   1144 
   1145   return VisitDeclarationNameInfo(D->getNameInfo());
   1146 }
   1147 
   1148 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
   1149   // Visit nested-name-specifier.
   1150   if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
   1151     if (VisitNestedNameSpecifierLoc(QualifierLoc))
   1152       return true;
   1153 
   1154   return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
   1155                                       D->getIdentLocation(), TU));
   1156 }
   1157 
   1158 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
   1159   // Visit nested-name-specifier.
   1160   if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
   1161     if (VisitNestedNameSpecifierLoc(QualifierLoc))
   1162       return true;
   1163   }
   1164 
   1165   return VisitDeclarationNameInfo(D->getNameInfo());
   1166 }
   1167 
   1168 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
   1169                                                UnresolvedUsingTypenameDecl *D) {
   1170   // Visit nested-name-specifier.
   1171   if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
   1172     if (VisitNestedNameSpecifierLoc(QualifierLoc))
   1173       return true;
   1174 
   1175   return false;
   1176 }
   1177 
   1178 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
   1179   switch (Name.getName().getNameKind()) {
   1180   case clang::DeclarationName::Identifier:
   1181   case clang::DeclarationName::CXXLiteralOperatorName:
   1182   case clang::DeclarationName::CXXOperatorName:
   1183   case clang::DeclarationName::CXXUsingDirective:
   1184     return false;
   1185 
   1186   case clang::DeclarationName::CXXConstructorName:
   1187   case clang::DeclarationName::CXXDestructorName:
   1188   case clang::DeclarationName::CXXConversionFunctionName:
   1189     if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
   1190       return Visit(TSInfo->getTypeLoc());
   1191     return false;
   1192 
   1193   case clang::DeclarationName::ObjCZeroArgSelector:
   1194   case clang::DeclarationName::ObjCOneArgSelector:
   1195   case clang::DeclarationName::ObjCMultiArgSelector:
   1196     // FIXME: Per-identifier location info?
   1197     return false;
   1198   }
   1199 
   1200   llvm_unreachable("Invalid DeclarationName::Kind!");
   1201 }
   1202 
   1203 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
   1204                                              SourceRange Range) {
   1205   // FIXME: This whole routine is a hack to work around the lack of proper
   1206   // source information in nested-name-specifiers (PR5791). Since we do have
   1207   // a beginning source location, we can visit the first component of the
   1208   // nested-name-specifier, if it's a single-token component.
   1209   if (!NNS)
   1210     return false;
   1211 
   1212   // Get the first component in the nested-name-specifier.
   1213   while (NestedNameSpecifier *Prefix = NNS->getPrefix())
   1214     NNS = Prefix;
   1215 
   1216   switch (NNS->getKind()) {
   1217   case NestedNameSpecifier::Namespace:
   1218     return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
   1219                                         TU));
   1220 
   1221   case NestedNameSpecifier::NamespaceAlias:
   1222     return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
   1223                                         Range.getBegin(), TU));
   1224 
   1225   case NestedNameSpecifier::TypeSpec: {
   1226     // If the type has a form where we know that the beginning of the source
   1227     // range matches up with a reference cursor. Visit the appropriate reference
   1228     // cursor.
   1229     const Type *T = NNS->getAsType();
   1230     if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
   1231       return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
   1232     if (const TagType *Tag = dyn_cast<TagType>(T))
   1233       return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
   1234     if (const TemplateSpecializationType *TST
   1235                                       = dyn_cast<TemplateSpecializationType>(T))
   1236       return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
   1237     break;
   1238   }
   1239 
   1240   case NestedNameSpecifier::TypeSpecWithTemplate:
   1241   case NestedNameSpecifier::Global:
   1242   case NestedNameSpecifier::Identifier:
   1243     break;
   1244   }
   1245 
   1246   return false;
   1247 }
   1248 
   1249 bool
   1250 CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
   1251   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
   1252   for (; Qualifier; Qualifier = Qualifier.getPrefix())
   1253     Qualifiers.push_back(Qualifier);
   1254 
   1255   while (!Qualifiers.empty()) {
   1256     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
   1257     NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
   1258     switch (NNS->getKind()) {
   1259     case NestedNameSpecifier::Namespace:
   1260       if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
   1261                                        Q.getLocalBeginLoc(),
   1262                                        TU)))
   1263         return true;
   1264 
   1265       break;
   1266 
   1267     case NestedNameSpecifier::NamespaceAlias:
   1268       if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
   1269                                        Q.getLocalBeginLoc(),
   1270                                        TU)))
   1271         return true;
   1272 
   1273       break;
   1274 
   1275     case NestedNameSpecifier::TypeSpec:
   1276     case NestedNameSpecifier::TypeSpecWithTemplate:
   1277       if (Visit(Q.getTypeLoc()))
   1278         return true;
   1279 
   1280       break;
   1281 
   1282     case NestedNameSpecifier::Global:
   1283     case NestedNameSpecifier::Identifier:
   1284       break;
   1285     }
   1286   }
   1287 
   1288   return false;
   1289 }
   1290 
   1291 bool CursorVisitor::VisitTemplateParameters(
   1292                                           const TemplateParameterList *Params) {
   1293   if (!Params)
   1294     return false;
   1295 
   1296   for (TemplateParameterList::const_iterator P = Params->begin(),
   1297                                           PEnd = Params->end();
   1298        P != PEnd; ++P) {
   1299     if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
   1300       return true;
   1301   }
   1302 
   1303   return false;
   1304 }
   1305 
   1306 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
   1307   switch (Name.getKind()) {
   1308   case TemplateName::Template:
   1309     return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
   1310 
   1311   case TemplateName::OverloadedTemplate:
   1312     // Visit the overloaded template set.
   1313     if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
   1314       return true;
   1315 
   1316     return false;
   1317 
   1318   case TemplateName::DependentTemplate:
   1319     // FIXME: Visit nested-name-specifier.
   1320     return false;
   1321 
   1322   case TemplateName::QualifiedTemplate:
   1323     // FIXME: Visit nested-name-specifier.
   1324     return Visit(MakeCursorTemplateRef(
   1325                                   Name.getAsQualifiedTemplateName()->getDecl(),
   1326                                        Loc, TU));
   1327 
   1328   case TemplateName::SubstTemplateTemplateParm:
   1329     return Visit(MakeCursorTemplateRef(
   1330                          Name.getAsSubstTemplateTemplateParm()->getParameter(),
   1331                                        Loc, TU));
   1332 
   1333   case TemplateName::SubstTemplateTemplateParmPack:
   1334     return Visit(MakeCursorTemplateRef(
   1335                   Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
   1336                                        Loc, TU));
   1337   }
   1338 
   1339   llvm_unreachable("Invalid TemplateName::Kind!");
   1340 }
   1341 
   1342 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
   1343   switch (TAL.getArgument().getKind()) {
   1344   case TemplateArgument::Null:
   1345   case TemplateArgument::Integral:
   1346   case TemplateArgument::Pack:
   1347     return false;
   1348 
   1349   case TemplateArgument::Type:
   1350     if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
   1351       return Visit(TSInfo->getTypeLoc());
   1352     return false;
   1353 
   1354   case TemplateArgument::Declaration:
   1355     if (Expr *E = TAL.getSourceDeclExpression())
   1356       return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
   1357     return false;
   1358 
   1359   case TemplateArgument::NullPtr:
   1360     if (Expr *E = TAL.getSourceNullPtrExpression())
   1361       return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
   1362     return false;
   1363 
   1364   case TemplateArgument::Expression:
   1365     if (Expr *E = TAL.getSourceExpression())
   1366       return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
   1367     return false;
   1368 
   1369   case TemplateArgument::Template:
   1370   case TemplateArgument::TemplateExpansion:
   1371     if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
   1372       return true;
   1373 
   1374     return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
   1375                              TAL.getTemplateNameLoc());
   1376   }
   1377 
   1378   llvm_unreachable("Invalid TemplateArgument::Kind!");
   1379 }
   1380 
   1381 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
   1382   return VisitDeclContext(D);
   1383 }
   1384 
   1385 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
   1386   return Visit(TL.getUnqualifiedLoc());
   1387 }
   1388 
   1389 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
   1390   ASTContext &Context = AU->getASTContext();
   1391 
   1392   // Some builtin types (such as Objective-C's "id", "sel", and
   1393   // "Class") have associated declarations. Create cursors for those.
   1394   QualType VisitType;
   1395   switch (TL.getTypePtr()->getKind()) {
   1396 
   1397   case BuiltinType::Void:
   1398   case BuiltinType::NullPtr:
   1399   case BuiltinType::Dependent:
   1400   case BuiltinType::OCLImage1d:
   1401   case BuiltinType::OCLImage1dArray:
   1402   case BuiltinType::OCLImage1dBuffer:
   1403   case BuiltinType::OCLImage2d:
   1404   case BuiltinType::OCLImage2dArray:
   1405   case BuiltinType::OCLImage3d:
   1406   case BuiltinType::OCLSampler:
   1407   case BuiltinType::OCLEvent:
   1408 #define BUILTIN_TYPE(Id, SingletonId)
   1409 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
   1410 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
   1411 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
   1412 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
   1413 #include "clang/AST/BuiltinTypes.def"
   1414     break;
   1415 
   1416   case BuiltinType::ObjCId:
   1417     VisitType = Context.getObjCIdType();
   1418     break;
   1419 
   1420   case BuiltinType::ObjCClass:
   1421     VisitType = Context.getObjCClassType();
   1422     break;
   1423 
   1424   case BuiltinType::ObjCSel:
   1425     VisitType = Context.getObjCSelType();
   1426     break;
   1427   }
   1428 
   1429   if (!VisitType.isNull()) {
   1430     if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
   1431       return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
   1432                                      TU));
   1433   }
   1434 
   1435   return false;
   1436 }
   1437 
   1438 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
   1439   return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
   1440 }
   1441 
   1442 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
   1443   return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
   1444 }
   1445 
   1446 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
   1447   if (TL.isDefinition())
   1448     return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
   1449 
   1450   return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
   1451 }
   1452 
   1453 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
   1454   return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
   1455 }
   1456 
   1457 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
   1458   if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
   1459     return true;
   1460 
   1461   return false;
   1462 }
   1463 
   1464 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
   1465   if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
   1466     return true;
   1467 
   1468   for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
   1469     if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
   1470                                         TU)))
   1471       return true;
   1472   }
   1473 
   1474   return false;
   1475 }
   1476 
   1477 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
   1478   return Visit(TL.getPointeeLoc());
   1479 }
   1480 
   1481 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
   1482   return Visit(TL.getInnerLoc());
   1483 }
   1484 
   1485 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
   1486   return Visit(TL.getPointeeLoc());
   1487 }
   1488 
   1489 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
   1490   return Visit(TL.getPointeeLoc());
   1491 }
   1492 
   1493 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
   1494   return Visit(TL.getPointeeLoc());
   1495 }
   1496 
   1497 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
   1498   return Visit(TL.getPointeeLoc());
   1499 }
   1500 
   1501 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
   1502   return Visit(TL.getPointeeLoc());
   1503 }
   1504 
   1505 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
   1506   return Visit(TL.getModifiedLoc());
   1507 }
   1508 
   1509 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
   1510                                          bool SkipResultType) {
   1511   if (!SkipResultType && Visit(TL.getResultLoc()))
   1512     return true;
   1513 
   1514   for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
   1515     if (Decl *D = TL.getArg(I))
   1516       if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
   1517         return true;
   1518 
   1519   return false;
   1520 }
   1521 
   1522 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
   1523   if (Visit(TL.getElementLoc()))
   1524     return true;
   1525 
   1526   if (Expr *Size = TL.getSizeExpr())
   1527     return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
   1528 
   1529   return false;
   1530 }
   1531 
   1532 bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
   1533                                              TemplateSpecializationTypeLoc TL) {
   1534   // Visit the template name.
   1535   if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
   1536                         TL.getTemplateNameLoc()))
   1537     return true;
   1538 
   1539   // Visit the template arguments.
   1540   for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
   1541     if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
   1542       return true;
   1543 
   1544   return false;
   1545 }
   1546 
   1547 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
   1548   return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
   1549 }
   1550 
   1551 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
   1552   if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
   1553     return Visit(TSInfo->getTypeLoc());
   1554 
   1555   return false;
   1556 }
   1557 
   1558 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
   1559   if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
   1560     return Visit(TSInfo->getTypeLoc());
   1561 
   1562   return false;
   1563 }
   1564 
   1565 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
   1566   if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
   1567     return true;
   1568 
   1569   return false;
   1570 }
   1571 
   1572 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
   1573                                     DependentTemplateSpecializationTypeLoc TL) {
   1574   // Visit the nested-name-specifier, if there is one.
   1575   if (TL.getQualifierLoc() &&
   1576       VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
   1577     return true;
   1578 
   1579   // Visit the template arguments.
   1580   for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
   1581     if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
   1582       return true;
   1583 
   1584   return false;
   1585 }
   1586 
   1587 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
   1588   if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
   1589     return true;
   1590 
   1591   return Visit(TL.getNamedTypeLoc());
   1592 }
   1593 
   1594 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
   1595   return Visit(TL.getPatternLoc());
   1596 }
   1597 
   1598 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
   1599   if (Expr *E = TL.getUnderlyingExpr())
   1600     return Visit(MakeCXCursor(E, StmtParent, TU));
   1601 
   1602   return false;
   1603 }
   1604 
   1605 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
   1606   return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
   1607 }
   1608 
   1609 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
   1610   return Visit(TL.getValueLoc());
   1611 }
   1612 
   1613 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
   1614 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
   1615   return Visit##PARENT##Loc(TL); \
   1616 }
   1617 
   1618 DEFAULT_TYPELOC_IMPL(Complex, Type)
   1619 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
   1620 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
   1621 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
   1622 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
   1623 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
   1624 DEFAULT_TYPELOC_IMPL(Vector, Type)
   1625 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
   1626 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
   1627 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
   1628 DEFAULT_TYPELOC_IMPL(Record, TagType)
   1629 DEFAULT_TYPELOC_IMPL(Enum, TagType)
   1630 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
   1631 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
   1632 DEFAULT_TYPELOC_IMPL(Auto, Type)
   1633 
   1634 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
   1635   // Visit the nested-name-specifier, if present.
   1636   if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
   1637     if (VisitNestedNameSpecifierLoc(QualifierLoc))
   1638       return true;
   1639 
   1640   if (D->isCompleteDefinition()) {
   1641     for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
   1642          E = D->bases_end(); I != E; ++I) {
   1643       if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
   1644         return true;
   1645     }
   1646   }
   1647 
   1648   return VisitTagDecl(D);
   1649 }
   1650 
   1651 bool CursorVisitor::VisitAttributes(Decl *D) {
   1652   for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
   1653        i != e; ++i)
   1654     if (Visit(MakeCXCursor(*i, D, TU)))
   1655         return true;
   1656 
   1657   return false;
   1658 }
   1659 
   1660 //===----------------------------------------------------------------------===//
   1661 // Data-recursive visitor methods.
   1662 //===----------------------------------------------------------------------===//
   1663 
   1664 namespace {
   1665 #define DEF_JOB(NAME, DATA, KIND)\
   1666 class NAME : public VisitorJob {\
   1667 public:\
   1668   NAME(const DATA *d, CXCursor parent) : \
   1669       VisitorJob(parent, VisitorJob::KIND, d) {} \
   1670   static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
   1671   const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
   1672 };
   1673 
   1674 DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
   1675 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
   1676 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
   1677 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
   1678 DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
   1679         ExplicitTemplateArgsVisitKind)
   1680 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
   1681 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
   1682 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
   1683 #undef DEF_JOB
   1684 
   1685 class DeclVisit : public VisitorJob {
   1686 public:
   1687   DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
   1688     VisitorJob(parent, VisitorJob::DeclVisitKind,
   1689                D, isFirst ? (void*) 1 : (void*) 0) {}
   1690   static bool classof(const VisitorJob *VJ) {
   1691     return VJ->getKind() == DeclVisitKind;
   1692   }
   1693   const Decl *get() const { return static_cast<const Decl *>(data[0]); }
   1694   bool isFirst() const { return data[1] ? true : false; }
   1695 };
   1696 class TypeLocVisit : public VisitorJob {
   1697 public:
   1698   TypeLocVisit(TypeLoc tl, CXCursor parent) :
   1699     VisitorJob(parent, VisitorJob::TypeLocVisitKind,
   1700                tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
   1701 
   1702   static bool classof(const VisitorJob *VJ) {
   1703     return VJ->getKind() == TypeLocVisitKind;
   1704   }
   1705 
   1706   TypeLoc get() const {
   1707     QualType T = QualType::getFromOpaquePtr(data[0]);
   1708     return TypeLoc(T, const_cast<void *>(data[1]));
   1709   }
   1710 };
   1711 
   1712 class LabelRefVisit : public VisitorJob {
   1713 public:
   1714   LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
   1715     : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
   1716                  labelLoc.getPtrEncoding()) {}
   1717 
   1718   static bool classof(const VisitorJob *VJ) {
   1719     return VJ->getKind() == VisitorJob::LabelRefVisitKind;
   1720   }
   1721   const LabelDecl *get() const {
   1722     return static_cast<const LabelDecl *>(data[0]);
   1723   }
   1724   SourceLocation getLoc() const {
   1725     return SourceLocation::getFromPtrEncoding(data[1]); }
   1726 };
   1727 
   1728 class NestedNameSpecifierLocVisit : public VisitorJob {
   1729 public:
   1730   NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
   1731     : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
   1732                  Qualifier.getNestedNameSpecifier(),
   1733                  Qualifier.getOpaqueData()) { }
   1734 
   1735   static bool classof(const VisitorJob *VJ) {
   1736     return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
   1737   }
   1738 
   1739   NestedNameSpecifierLoc get() const {
   1740     return NestedNameSpecifierLoc(
   1741             const_cast<NestedNameSpecifier *>(
   1742               static_cast<const NestedNameSpecifier *>(data[0])),
   1743             const_cast<void *>(data[1]));
   1744   }
   1745 };
   1746 
   1747 class DeclarationNameInfoVisit : public VisitorJob {
   1748 public:
   1749   DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
   1750     : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
   1751   static bool classof(const VisitorJob *VJ) {
   1752     return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
   1753   }
   1754   DeclarationNameInfo get() const {
   1755     const Stmt *S = static_cast<const Stmt *>(data[0]);
   1756     switch (S->getStmtClass()) {
   1757     default:
   1758       llvm_unreachable("Unhandled Stmt");
   1759     case clang::Stmt::MSDependentExistsStmtClass:
   1760       return cast<MSDependentExistsStmt>(S)->getNameInfo();
   1761     case Stmt::CXXDependentScopeMemberExprClass:
   1762       return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
   1763     case Stmt::DependentScopeDeclRefExprClass:
   1764       return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
   1765     }
   1766   }
   1767 };
   1768 class MemberRefVisit : public VisitorJob {
   1769 public:
   1770   MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
   1771     : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
   1772                  L.getPtrEncoding()) {}
   1773   static bool classof(const VisitorJob *VJ) {
   1774     return VJ->getKind() == VisitorJob::MemberRefVisitKind;
   1775   }
   1776   const FieldDecl *get() const {
   1777     return static_cast<const FieldDecl *>(data[0]);
   1778   }
   1779   SourceLocation getLoc() const {
   1780     return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
   1781   }
   1782 };
   1783 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
   1784   VisitorWorkList &WL;
   1785   CXCursor Parent;
   1786 public:
   1787   EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
   1788     : WL(wl), Parent(parent) {}
   1789 
   1790   void VisitAddrLabelExpr(const AddrLabelExpr *E);
   1791   void VisitBlockExpr(const BlockExpr *B);
   1792   void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
   1793   void VisitCompoundStmt(const CompoundStmt *S);
   1794   void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
   1795   void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
   1796   void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
   1797   void VisitCXXNewExpr(const CXXNewExpr *E);
   1798   void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
   1799   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
   1800   void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
   1801   void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
   1802   void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
   1803   void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
   1804   void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
   1805   void VisitCXXCatchStmt(const CXXCatchStmt *S);
   1806   void VisitDeclRefExpr(const DeclRefExpr *D);
   1807   void VisitDeclStmt(const DeclStmt *S);
   1808   void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
   1809   void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
   1810   void VisitExplicitCastExpr(const ExplicitCastExpr *E);
   1811   void VisitForStmt(const ForStmt *FS);
   1812   void VisitGotoStmt(const GotoStmt *GS);
   1813   void VisitIfStmt(const IfStmt *If);
   1814   void VisitInitListExpr(const InitListExpr *IE);
   1815   void VisitMemberExpr(const MemberExpr *M);
   1816   void VisitOffsetOfExpr(const OffsetOfExpr *E);
   1817   void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
   1818   void VisitObjCMessageExpr(const ObjCMessageExpr *M);
   1819   void VisitOverloadExpr(const OverloadExpr *E);
   1820   void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
   1821   void VisitStmt(const Stmt *S);
   1822   void VisitSwitchStmt(const SwitchStmt *S);
   1823   void VisitWhileStmt(const WhileStmt *W);
   1824   void VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E);
   1825   void VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E);
   1826   void VisitTypeTraitExpr(const TypeTraitExpr *E);
   1827   void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
   1828   void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
   1829   void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
   1830   void VisitVAArgExpr(const VAArgExpr *E);
   1831   void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
   1832   void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
   1833   void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
   1834   void VisitLambdaExpr(const LambdaExpr *E);
   1835 
   1836 private:
   1837   void AddDeclarationNameInfo(const Stmt *S);
   1838   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
   1839   void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
   1840   void AddMemberRef(const FieldDecl *D, SourceLocation L);
   1841   void AddStmt(const Stmt *S);
   1842   void AddDecl(const Decl *D, bool isFirst = true);
   1843   void AddTypeLoc(TypeSourceInfo *TI);
   1844   void EnqueueChildren(const Stmt *S);
   1845 };
   1846 } // end anonyous namespace
   1847 
   1848 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
   1849   // 'S' should always be non-null, since it comes from the
   1850   // statement we are visiting.
   1851   WL.push_back(DeclarationNameInfoVisit(S, Parent));
   1852 }
   1853 
   1854 void
   1855 EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
   1856   if (Qualifier)
   1857     WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
   1858 }
   1859 
   1860 void EnqueueVisitor::AddStmt(const Stmt *S) {
   1861   if (S)
   1862     WL.push_back(StmtVisit(S, Parent));
   1863 }
   1864 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
   1865   if (D)
   1866     WL.push_back(DeclVisit(D, Parent, isFirst));
   1867 }
   1868 void EnqueueVisitor::
   1869   AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
   1870   if (A)
   1871     WL.push_back(ExplicitTemplateArgsVisit(A, Parent));
   1872 }
   1873 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
   1874   if (D)
   1875     WL.push_back(MemberRefVisit(D, L, Parent));
   1876 }
   1877 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
   1878   if (TI)
   1879     WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
   1880  }
   1881 void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
   1882   unsigned size = WL.size();
   1883   for (Stmt::const_child_range Child = S->children(); Child; ++Child) {
   1884     AddStmt(*Child);
   1885   }
   1886   if (size == WL.size())
   1887     return;
   1888   // Now reverse the entries we just added.  This will match the DFS
   1889   // ordering performed by the worklist.
   1890   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
   1891   std::reverse(I, E);
   1892 }
   1893 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
   1894   WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
   1895 }
   1896 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
   1897   AddDecl(B->getBlockDecl());
   1898 }
   1899 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
   1900   EnqueueChildren(E);
   1901   AddTypeLoc(E->getTypeSourceInfo());
   1902 }
   1903 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
   1904   for (CompoundStmt::const_reverse_body_iterator I = S->body_rbegin(),
   1905         E = S->body_rend(); I != E; ++I) {
   1906     AddStmt(*I);
   1907   }
   1908 }
   1909 void EnqueueVisitor::
   1910 VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
   1911   AddStmt(S->getSubStmt());
   1912   AddDeclarationNameInfo(S);
   1913   if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
   1914     AddNestedNameSpecifierLoc(QualifierLoc);
   1915 }
   1916 
   1917 void EnqueueVisitor::
   1918 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
   1919   AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
   1920   AddDeclarationNameInfo(E);
   1921   if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
   1922     AddNestedNameSpecifierLoc(QualifierLoc);
   1923   if (!E->isImplicitAccess())
   1924     AddStmt(E->getBase());
   1925 }
   1926 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
   1927   // Enqueue the initializer , if any.
   1928   AddStmt(E->getInitializer());
   1929   // Enqueue the array size, if any.
   1930   AddStmt(E->getArraySize());
   1931   // Enqueue the allocated type.
   1932   AddTypeLoc(E->getAllocatedTypeSourceInfo());
   1933   // Enqueue the placement arguments.
   1934   for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
   1935     AddStmt(E->getPlacementArg(I-1));
   1936 }
   1937 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
   1938   for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
   1939     AddStmt(CE->getArg(I-1));
   1940   AddStmt(CE->getCallee());
   1941   AddStmt(CE->getArg(0));
   1942 }
   1943 void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
   1944                                         const CXXPseudoDestructorExpr *E) {
   1945   // Visit the name of the type being destroyed.
   1946   AddTypeLoc(E->getDestroyedTypeInfo());
   1947   // Visit the scope type that looks disturbingly like the nested-name-specifier
   1948   // but isn't.
   1949   AddTypeLoc(E->getScopeTypeInfo());
   1950   // Visit the nested-name-specifier.
   1951   if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
   1952     AddNestedNameSpecifierLoc(QualifierLoc);
   1953   // Visit base expression.
   1954   AddStmt(E->getBase());
   1955 }
   1956 void EnqueueVisitor::VisitCXXScalarValueInitExpr(
   1957                                         const CXXScalarValueInitExpr *E) {
   1958   AddTypeLoc(E->getTypeSourceInfo());
   1959 }
   1960 void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
   1961                                         const CXXTemporaryObjectExpr *E) {
   1962   EnqueueChildren(E);
   1963   AddTypeLoc(E->getTypeSourceInfo());
   1964 }
   1965 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
   1966   EnqueueChildren(E);
   1967   if (E->isTypeOperand())
   1968     AddTypeLoc(E->getTypeOperandSourceInfo());
   1969 }
   1970 
   1971 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
   1972                                         const CXXUnresolvedConstructExpr *E) {
   1973   EnqueueChildren(E);
   1974   AddTypeLoc(E->getTypeSourceInfo());
   1975 }
   1976 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
   1977   EnqueueChildren(E);
   1978   if (E->isTypeOperand())
   1979     AddTypeLoc(E->getTypeOperandSourceInfo());
   1980 }
   1981 
   1982 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
   1983   EnqueueChildren(S);
   1984   AddDecl(S->getExceptionDecl());
   1985 }
   1986 
   1987 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
   1988   if (DR->hasExplicitTemplateArgs()) {
   1989     AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
   1990   }
   1991   WL.push_back(DeclRefExprParts(DR, Parent));
   1992 }
   1993 void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
   1994                                         const DependentScopeDeclRefExpr *E) {
   1995   AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
   1996   AddDeclarationNameInfo(E);
   1997   AddNestedNameSpecifierLoc(E->getQualifierLoc());
   1998 }
   1999 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
   2000   unsigned size = WL.size();
   2001   bool isFirst = true;
   2002   for (DeclStmt::const_decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
   2003        D != DEnd; ++D) {
   2004     AddDecl(*D, isFirst);
   2005     isFirst = false;
   2006   }
   2007   if (size == WL.size())
   2008     return;
   2009   // Now reverse the entries we just added.  This will match the DFS
   2010   // ordering performed by the worklist.
   2011   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
   2012   std::reverse(I, E);
   2013 }
   2014 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
   2015   AddStmt(E->getInit());
   2016   typedef DesignatedInitExpr::Designator Designator;
   2017   for (DesignatedInitExpr::const_reverse_designators_iterator
   2018          D = E->designators_rbegin(), DEnd = E->designators_rend();
   2019          D != DEnd; ++D) {
   2020     if (D->isFieldDesignator()) {
   2021       if (FieldDecl *Field = D->getField())
   2022         AddMemberRef(Field, D->getFieldLoc());
   2023       continue;
   2024     }
   2025     if (D->isArrayDesignator()) {
   2026       AddStmt(E->getArrayIndex(*D));
   2027       continue;
   2028     }
   2029     assert(D->isArrayRangeDesignator() && "Unknown designator kind");
   2030     AddStmt(E->getArrayRangeEnd(*D));
   2031     AddStmt(E->getArrayRangeStart(*D));
   2032   }
   2033 }
   2034 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
   2035   EnqueueChildren(E);
   2036   AddTypeLoc(E->getTypeInfoAsWritten());
   2037 }
   2038 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
   2039   AddStmt(FS->getBody());
   2040   AddStmt(FS->getInc());
   2041   AddStmt(FS->getCond());
   2042   AddDecl(FS->getConditionVariable());
   2043   AddStmt(FS->getInit());
   2044 }
   2045 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
   2046   WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
   2047 }
   2048 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
   2049   AddStmt(If->getElse());
   2050   AddStmt(If->getThen());
   2051   AddStmt(If->getCond());
   2052   AddDecl(If->getConditionVariable());
   2053 }
   2054 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
   2055   // We care about the syntactic form of the initializer list, only.
   2056   if (InitListExpr *Syntactic = IE->getSyntacticForm())
   2057     IE = Syntactic;
   2058   EnqueueChildren(IE);
   2059 }
   2060 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
   2061   WL.push_back(MemberExprParts(M, Parent));
   2062 
   2063   // If the base of the member access expression is an implicit 'this', don't
   2064   // visit it.
   2065   // FIXME: If we ever want to show these implicit accesses, this will be
   2066   // unfortunate. However, clang_getCursor() relies on this behavior.
   2067   if (!M->isImplicitAccess())
   2068     AddStmt(M->getBase());
   2069 }
   2070 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
   2071   AddTypeLoc(E->getEncodedTypeSourceInfo());
   2072 }
   2073 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
   2074   EnqueueChildren(M);
   2075   AddTypeLoc(M->getClassReceiverTypeInfo());
   2076 }
   2077 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
   2078   // Visit the components of the offsetof expression.
   2079   for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
   2080     typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
   2081     const OffsetOfNode &Node = E->getComponent(I-1);
   2082     switch (Node.getKind()) {
   2083     case OffsetOfNode::Array:
   2084       AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
   2085       break;
   2086     case OffsetOfNode::Field:
   2087       AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
   2088       break;
   2089     case OffsetOfNode::Identifier:
   2090     case OffsetOfNode::Base:
   2091       continue;
   2092     }
   2093   }
   2094   // Visit the type into which we're computing the offset.
   2095   AddTypeLoc(E->getTypeSourceInfo());
   2096 }
   2097 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
   2098   AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
   2099   WL.push_back(OverloadExprParts(E, Parent));
   2100 }
   2101 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
   2102                                         const UnaryExprOrTypeTraitExpr *E) {
   2103   EnqueueChildren(E);
   2104   if (E->isArgumentType())
   2105     AddTypeLoc(E->getArgumentTypeInfo());
   2106 }
   2107 void EnqueueVisitor::VisitStmt(const Stmt *S) {
   2108   EnqueueChildren(S);
   2109 }
   2110 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
   2111   AddStmt(S->getBody());
   2112   AddStmt(S->getCond());
   2113   AddDecl(S->getConditionVariable());
   2114 }
   2115 
   2116 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
   2117   AddStmt(W->getBody());
   2118   AddStmt(W->getCond());
   2119   AddDecl(W->getConditionVariable());
   2120 }
   2121 
   2122 void EnqueueVisitor::VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
   2123   AddTypeLoc(E->getQueriedTypeSourceInfo());
   2124 }
   2125 
   2126 void EnqueueVisitor::VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
   2127   AddTypeLoc(E->getRhsTypeSourceInfo());
   2128   AddTypeLoc(E->getLhsTypeSourceInfo());
   2129 }
   2130 
   2131 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
   2132   for (unsigned I = E->getNumArgs(); I > 0; --I)
   2133     AddTypeLoc(E->getArg(I-1));
   2134 }
   2135 
   2136 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
   2137   AddTypeLoc(E->getQueriedTypeSourceInfo());
   2138 }
   2139 
   2140 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
   2141   EnqueueChildren(E);
   2142 }
   2143 
   2144 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
   2145   VisitOverloadExpr(U);
   2146   if (!U->isImplicitAccess())
   2147     AddStmt(U->getBase());
   2148 }
   2149 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
   2150   AddStmt(E->getSubExpr());
   2151   AddTypeLoc(E->getWrittenTypeInfo());
   2152 }
   2153 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
   2154   WL.push_back(SizeOfPackExprParts(E, Parent));
   2155 }
   2156 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
   2157   // If the opaque value has a source expression, just transparently
   2158   // visit that.  This is useful for (e.g.) pseudo-object expressions.
   2159   if (Expr *SourceExpr = E->getSourceExpr())
   2160     return Visit(SourceExpr);
   2161 }
   2162 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
   2163   AddStmt(E->getBody());
   2164   WL.push_back(LambdaExprParts(E, Parent));
   2165 }
   2166 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
   2167   // Treat the expression like its syntactic form.
   2168   Visit(E->getSyntacticForm());
   2169 }
   2170 
   2171 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
   2172   EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
   2173 }
   2174 
   2175 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
   2176   if (RegionOfInterest.isValid()) {
   2177     SourceRange Range = getRawCursorExtent(C);
   2178     if (Range.isInvalid() || CompareRegionOfInterest(Range))
   2179       return false;
   2180   }
   2181   return true;
   2182 }
   2183 
   2184 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
   2185   while (!WL.empty()) {
   2186     // Dequeue the worklist item.
   2187     VisitorJob LI = WL.back();
   2188     WL.pop_back();
   2189 
   2190     // Set the Parent field, then back to its old value once we're done.
   2191     SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
   2192 
   2193     switch (LI.getKind()) {
   2194       case VisitorJob::DeclVisitKind: {
   2195         const Decl *D = cast<DeclVisit>(&LI)->get();
   2196         if (!D)
   2197           continue;
   2198 
   2199         // For now, perform default visitation for Decls.
   2200         if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
   2201                                cast<DeclVisit>(&LI)->isFirst())))
   2202             return true;
   2203 
   2204         continue;
   2205       }
   2206       case VisitorJob::ExplicitTemplateArgsVisitKind: {
   2207         const ASTTemplateArgumentListInfo *ArgList =
   2208           cast<ExplicitTemplateArgsVisit>(&LI)->get();
   2209         for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
   2210                *ArgEnd = Arg + ArgList->NumTemplateArgs;
   2211                Arg != ArgEnd; ++Arg) {
   2212           if (VisitTemplateArgumentLoc(*Arg))
   2213             return true;
   2214         }
   2215         continue;
   2216       }
   2217       case VisitorJob::TypeLocVisitKind: {
   2218         // Perform default visitation for TypeLocs.
   2219         if (Visit(cast<TypeLocVisit>(&LI)->get()))
   2220           return true;
   2221         continue;
   2222       }
   2223       case VisitorJob::LabelRefVisitKind: {
   2224         const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
   2225         if (LabelStmt *stmt = LS->getStmt()) {
   2226           if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
   2227                                        TU))) {
   2228             return true;
   2229           }
   2230         }
   2231         continue;
   2232       }
   2233 
   2234       case VisitorJob::NestedNameSpecifierLocVisitKind: {
   2235         NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
   2236         if (VisitNestedNameSpecifierLoc(V->get()))
   2237           return true;
   2238         continue;
   2239       }
   2240 
   2241       case VisitorJob::DeclarationNameInfoVisitKind: {
   2242         if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
   2243                                      ->get()))
   2244           return true;
   2245         continue;
   2246       }
   2247       case VisitorJob::MemberRefVisitKind: {
   2248         MemberRefVisit *V = cast<MemberRefVisit>(&LI);
   2249         if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
   2250           return true;
   2251         continue;
   2252       }
   2253       case VisitorJob::StmtVisitKind: {
   2254         const Stmt *S = cast<StmtVisit>(&LI)->get();
   2255         if (!S)
   2256           continue;
   2257 
   2258         // Update the current cursor.
   2259         CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
   2260         if (!IsInRegionOfInterest(Cursor))
   2261           continue;
   2262         switch (Visitor(Cursor, Parent, ClientData)) {
   2263           case CXChildVisit_Break: return true;
   2264           case CXChildVisit_Continue: break;
   2265           case CXChildVisit_Recurse:
   2266             if (PostChildrenVisitor)
   2267               WL.push_back(PostChildrenVisit(0, Cursor));
   2268             EnqueueWorkList(WL, S);
   2269             break;
   2270         }
   2271         continue;
   2272       }
   2273       case VisitorJob::MemberExprPartsKind: {
   2274         // Handle the other pieces in the MemberExpr besides the base.
   2275         const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
   2276 
   2277         // Visit the nested-name-specifier
   2278         if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
   2279           if (VisitNestedNameSpecifierLoc(QualifierLoc))
   2280             return true;
   2281 
   2282         // Visit the declaration name.
   2283         if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
   2284           return true;
   2285 
   2286         // Visit the explicitly-specified template arguments, if any.
   2287         if (M->hasExplicitTemplateArgs()) {
   2288           for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
   2289                *ArgEnd = Arg + M->getNumTemplateArgs();
   2290                Arg != ArgEnd; ++Arg) {
   2291             if (VisitTemplateArgumentLoc(*Arg))
   2292               return true;
   2293           }
   2294         }
   2295         continue;
   2296       }
   2297       case VisitorJob::DeclRefExprPartsKind: {
   2298         const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
   2299         // Visit nested-name-specifier, if present.
   2300         if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
   2301           if (VisitNestedNameSpecifierLoc(QualifierLoc))
   2302             return true;
   2303         // Visit declaration name.
   2304         if (VisitDeclarationNameInfo(DR->getNameInfo()))
   2305           return true;
   2306         continue;
   2307       }
   2308       case VisitorJob::OverloadExprPartsKind: {
   2309         const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
   2310         // Visit the nested-name-specifier.
   2311         if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
   2312           if (VisitNestedNameSpecifierLoc(QualifierLoc))
   2313             return true;
   2314         // Visit the declaration name.
   2315         if (VisitDeclarationNameInfo(O->getNameInfo()))
   2316           return true;
   2317         // Visit the overloaded declaration reference.
   2318         if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
   2319           return true;
   2320         continue;
   2321       }
   2322       case VisitorJob::SizeOfPackExprPartsKind: {
   2323         const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
   2324         NamedDecl *Pack = E->getPack();
   2325         if (isa<TemplateTypeParmDecl>(Pack)) {
   2326           if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
   2327                                       E->getPackLoc(), TU)))
   2328             return true;
   2329 
   2330           continue;
   2331         }
   2332 
   2333         if (isa<TemplateTemplateParmDecl>(Pack)) {
   2334           if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
   2335                                           E->getPackLoc(), TU)))
   2336             return true;
   2337 
   2338           continue;
   2339         }
   2340 
   2341         // Non-type template parameter packs and function parameter packs are
   2342         // treated like DeclRefExpr cursors.
   2343         continue;
   2344       }
   2345 
   2346       case VisitorJob::LambdaExprPartsKind: {
   2347         // Visit captures.
   2348         const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
   2349         for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
   2350                                        CEnd = E->explicit_capture_end();
   2351              C != CEnd; ++C) {
   2352           if (C->capturesThis())
   2353             continue;
   2354 
   2355           if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
   2356                                           C->getLocation(),
   2357                                           TU)))
   2358             return true;
   2359         }
   2360 
   2361         // Visit parameters and return type, if present.
   2362         if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
   2363           TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
   2364           if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
   2365             // Visit the whole type.
   2366             if (Visit(TL))
   2367               return true;
   2368           } else if (FunctionProtoTypeLoc Proto =
   2369                          TL.getAs<FunctionProtoTypeLoc>()) {
   2370             if (E->hasExplicitParameters()) {
   2371               // Visit parameters.
   2372               for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
   2373                 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
   2374                   return true;
   2375             } else {
   2376               // Visit result type.
   2377               if (Visit(Proto.getResultLoc()))
   2378                 return true;
   2379             }
   2380           }
   2381         }
   2382         break;
   2383       }
   2384 
   2385       case VisitorJob::PostChildrenVisitKind:
   2386         if (PostChildrenVisitor(Parent, ClientData))
   2387           return true;
   2388         break;
   2389     }
   2390   }
   2391   return false;
   2392 }
   2393 
   2394 bool CursorVisitor::Visit(const Stmt *S) {
   2395   VisitorWorkList *WL = 0;
   2396   if (!WorkListFreeList.empty()) {
   2397     WL = WorkListFreeList.back();
   2398     WL->clear();
   2399     WorkListFreeList.pop_back();
   2400   }
   2401   else {
   2402     WL = new VisitorWorkList();
   2403     WorkListCache.push_back(WL);
   2404   }
   2405   EnqueueWorkList(*WL, S);
   2406   bool result = RunVisitorWorkList(*WL);
   2407   WorkListFreeList.push_back(WL);
   2408   return result;
   2409 }
   2410 
   2411 namespace {
   2412 typedef SmallVector<SourceRange, 4> RefNamePieces;
   2413 RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
   2414                           const DeclarationNameInfo &NI,
   2415                           const SourceRange &QLoc,
   2416                           const ASTTemplateArgumentListInfo *TemplateArgs = 0){
   2417   const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
   2418   const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
   2419   const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
   2420 
   2421   const DeclarationName::NameKind Kind = NI.getName().getNameKind();
   2422 
   2423   RefNamePieces Pieces;
   2424 
   2425   if (WantQualifier && QLoc.isValid())
   2426     Pieces.push_back(QLoc);
   2427 
   2428   if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
   2429     Pieces.push_back(NI.getLoc());
   2430 
   2431   if (WantTemplateArgs && TemplateArgs)
   2432     Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
   2433                                  TemplateArgs->RAngleLoc));
   2434 
   2435   if (Kind == DeclarationName::CXXOperatorName) {
   2436     Pieces.push_back(SourceLocation::getFromRawEncoding(
   2437                        NI.getInfo().CXXOperatorName.BeginOpNameLoc));
   2438     Pieces.push_back(SourceLocation::getFromRawEncoding(
   2439                        NI.getInfo().CXXOperatorName.EndOpNameLoc));
   2440   }
   2441 
   2442   if (WantSinglePiece) {
   2443     SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
   2444     Pieces.clear();
   2445     Pieces.push_back(R);
   2446   }
   2447 
   2448   return Pieces;
   2449 }
   2450 }
   2451 
   2452 //===----------------------------------------------------------------------===//
   2453 // Misc. API hooks.
   2454 //===----------------------------------------------------------------------===//
   2455 
   2456 static llvm::sys::Mutex EnableMultithreadingMutex;
   2457 static bool EnabledMultithreading;
   2458 
   2459 static void fatal_error_handler(void *user_data, const std::string& reason) {
   2460   // Write the result out to stderr avoiding errs() because raw_ostreams can
   2461   // call report_fatal_error.
   2462   fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
   2463   ::abort();
   2464 }
   2465 
   2466 extern "C" {
   2467 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
   2468                           int displayDiagnostics) {
   2469   // Disable pretty stack trace functionality, which will otherwise be a very
   2470   // poor citizen of the world and set up all sorts of signal handlers.
   2471   llvm::DisablePrettyStackTrace = true;
   2472 
   2473   // We use crash recovery to make some of our APIs more reliable, implicitly
   2474   // enable it.
   2475   llvm::CrashRecoveryContext::Enable();
   2476 
   2477   // Enable support for multithreading in LLVM.
   2478   {
   2479     llvm::sys::ScopedLock L(EnableMultithreadingMutex);
   2480     if (!EnabledMultithreading) {
   2481       llvm::install_fatal_error_handler(fatal_error_handler, 0);
   2482       llvm::llvm_start_multithreaded();
   2483       EnabledMultithreading = true;
   2484     }
   2485   }
   2486 
   2487   CIndexer *CIdxr = new CIndexer();
   2488   if (excludeDeclarationsFromPCH)
   2489     CIdxr->setOnlyLocalDecls();
   2490   if (displayDiagnostics)
   2491     CIdxr->setDisplayDiagnostics();
   2492 
   2493   if (getenv("LIBCLANG_BGPRIO_INDEX"))
   2494     CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
   2495                                CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
   2496   if (getenv("LIBCLANG_BGPRIO_EDIT"))
   2497     CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
   2498                                CXGlobalOpt_ThreadBackgroundPriorityForEditing);
   2499 
   2500   return CIdxr;
   2501 }
   2502 
   2503 void clang_disposeIndex(CXIndex CIdx) {
   2504   if (CIdx)
   2505     delete static_cast<CIndexer *>(CIdx);
   2506 }
   2507 
   2508 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
   2509   if (CIdx)
   2510     static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
   2511 }
   2512 
   2513 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
   2514   if (CIdx)
   2515     return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
   2516   return 0;
   2517 }
   2518 
   2519 void clang_toggleCrashRecovery(unsigned isEnabled) {
   2520   if (isEnabled)
   2521     llvm::CrashRecoveryContext::Enable();
   2522   else
   2523     llvm::CrashRecoveryContext::Disable();
   2524 }
   2525 
   2526 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
   2527                                               const char *ast_filename) {
   2528   if (!CIdx)
   2529     return 0;
   2530 
   2531   CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
   2532   FileSystemOptions FileSystemOpts;
   2533 
   2534   IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
   2535   ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
   2536                                   CXXIdx->getOnlyLocalDecls(),
   2537                                   0, 0,
   2538                                   /*CaptureDiagnostics=*/true,
   2539                                   /*AllowPCHWithCompilerErrors=*/true,
   2540                                   /*UserFilesAreVolatile=*/true);
   2541   return MakeCXTranslationUnit(CXXIdx, TU);
   2542 }
   2543 
   2544 unsigned clang_defaultEditingTranslationUnitOptions() {
   2545   return CXTranslationUnit_PrecompiledPreamble |
   2546          CXTranslationUnit_CacheCompletionResults;
   2547 }
   2548 
   2549 CXTranslationUnit
   2550 clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
   2551                                           const char *source_filename,
   2552                                           int num_command_line_args,
   2553                                           const char * const *command_line_args,
   2554                                           unsigned num_unsaved_files,
   2555                                           struct CXUnsavedFile *unsaved_files) {
   2556   unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
   2557   return clang_parseTranslationUnit(CIdx, source_filename,
   2558                                     command_line_args, num_command_line_args,
   2559                                     unsaved_files, num_unsaved_files,
   2560                                     Options);
   2561 }
   2562 
   2563 struct ParseTranslationUnitInfo {
   2564   CXIndex CIdx;
   2565   const char *source_filename;
   2566   const char *const *command_line_args;
   2567   int num_command_line_args;
   2568   struct CXUnsavedFile *unsaved_files;
   2569   unsigned num_unsaved_files;
   2570   unsigned options;
   2571   CXTranslationUnit result;
   2572 };
   2573 static void clang_parseTranslationUnit_Impl(void *UserData) {
   2574   ParseTranslationUnitInfo *PTUI =
   2575     static_cast<ParseTranslationUnitInfo*>(UserData);
   2576   CXIndex CIdx = PTUI->CIdx;
   2577   const char *source_filename = PTUI->source_filename;
   2578   const char * const *command_line_args = PTUI->command_line_args;
   2579   int num_command_line_args = PTUI->num_command_line_args;
   2580   struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
   2581   unsigned num_unsaved_files = PTUI->num_unsaved_files;
   2582   unsigned options = PTUI->options;
   2583   PTUI->result = 0;
   2584 
   2585   if (!CIdx)
   2586     return;
   2587 
   2588   CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
   2589 
   2590   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
   2591     setThreadBackgroundPriority();
   2592 
   2593   bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
   2594   // FIXME: Add a flag for modules.
   2595   TranslationUnitKind TUKind
   2596     = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
   2597   bool CacheCodeCompetionResults
   2598     = options & CXTranslationUnit_CacheCompletionResults;
   2599   bool IncludeBriefCommentsInCodeCompletion
   2600     = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
   2601   bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
   2602   bool ForSerialization = options & CXTranslationUnit_ForSerialization;
   2603 
   2604   // Configure the diagnostics.
   2605   IntrusiveRefCntPtr<DiagnosticsEngine>
   2606     Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
   2607 
   2608   // Recover resources if we crash before exiting this function.
   2609   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
   2610     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
   2611     DiagCleanup(Diags.getPtr());
   2612 
   2613   OwningPtr<std::vector<ASTUnit::RemappedFile> >
   2614     RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
   2615 
   2616   // Recover resources if we crash before exiting this function.
   2617   llvm::CrashRecoveryContextCleanupRegistrar<
   2618     std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
   2619 
   2620   for (unsigned I = 0; I != num_unsaved_files; ++I) {
   2621     StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
   2622     const llvm::MemoryBuffer *Buffer
   2623       = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
   2624     RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
   2625                                             Buffer));
   2626   }
   2627 
   2628   OwningPtr<std::vector<const char *> >
   2629     Args(new std::vector<const char*>());
   2630 
   2631   // Recover resources if we crash before exiting this method.
   2632   llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
   2633     ArgsCleanup(Args.get());
   2634 
   2635   // Since the Clang C library is primarily used by batch tools dealing with
   2636   // (often very broken) source code, where spell-checking can have a
   2637   // significant negative impact on performance (particularly when
   2638   // precompiled headers are involved), we disable it by default.
   2639   // Only do this if we haven't found a spell-checking-related argument.
   2640   bool FoundSpellCheckingArgument = false;
   2641   for (int I = 0; I != num_command_line_args; ++I) {
   2642     if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
   2643         strcmp(command_line_args[I], "-fspell-checking") == 0) {
   2644       FoundSpellCheckingArgument = true;
   2645       break;
   2646     }
   2647   }
   2648   if (!FoundSpellCheckingArgument)
   2649     Args->push_back("-fno-spell-checking");
   2650 
   2651   Args->insert(Args->end(), command_line_args,
   2652                command_line_args + num_command_line_args);
   2653 
   2654   // The 'source_filename' argument is optional.  If the caller does not
   2655   // specify it then it is assumed that the source file is specified
   2656   // in the actual argument list.
   2657   // Put the source file after command_line_args otherwise if '-x' flag is
   2658   // present it will be unused.
   2659   if (source_filename)
   2660     Args->push_back(source_filename);
   2661 
   2662   // Do we need the detailed preprocessing record?
   2663   if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
   2664     Args->push_back("-Xclang");
   2665     Args->push_back("-detailed-preprocessing-record");
   2666   }
   2667 
   2668   unsigned NumErrors = Diags->getClient()->getNumErrors();
   2669   OwningPtr<ASTUnit> ErrUnit;
   2670   OwningPtr<ASTUnit> Unit(
   2671     ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
   2672                                  /* vector::data() not portable */,
   2673                                  Args->size() ? (&(*Args)[0] + Args->size()) :0,
   2674                                  Diags,
   2675                                  CXXIdx->getClangResourcesPath(),
   2676                                  CXXIdx->getOnlyLocalDecls(),
   2677                                  /*CaptureDiagnostics=*/true,
   2678                                  RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
   2679                                  RemappedFiles->size(),
   2680                                  /*RemappedFilesKeepOriginalName=*/true,
   2681                                  PrecompilePreamble,
   2682                                  TUKind,
   2683                                  CacheCodeCompetionResults,
   2684                                  IncludeBriefCommentsInCodeCompletion,
   2685                                  /*AllowPCHWithCompilerErrors=*/true,
   2686                                  SkipFunctionBodies,
   2687                                  /*UserFilesAreVolatile=*/true,
   2688                                  ForSerialization,
   2689                                  &ErrUnit));
   2690 
   2691   if (NumErrors != Diags->getClient()->getNumErrors()) {
   2692     // Make sure to check that 'Unit' is non-NULL.
   2693     if (CXXIdx->getDisplayDiagnostics())
   2694       printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
   2695   }
   2696 
   2697   PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
   2698 }
   2699 CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
   2700                                              const char *source_filename,
   2701                                          const char * const *command_line_args,
   2702                                              int num_command_line_args,
   2703                                             struct CXUnsavedFile *unsaved_files,
   2704                                              unsigned num_unsaved_files,
   2705                                              unsigned options) {
   2706   LOG_FUNC_SECTION {
   2707     *Log << source_filename << ": ";
   2708     for (int i = 0; i != num_command_line_args; ++i)
   2709       *Log << command_line_args[i] << " ";
   2710   }
   2711 
   2712   ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
   2713                                     num_command_line_args, unsaved_files,
   2714                                     num_unsaved_files, options, 0 };
   2715   llvm::CrashRecoveryContext CRC;
   2716 
   2717   if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
   2718     fprintf(stderr, "libclang: crash detected during parsing: {\n");
   2719     fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
   2720     fprintf(stderr, "  'command_line_args' : [");
   2721     for (int i = 0; i != num_command_line_args; ++i) {
   2722       if (i)
   2723         fprintf(stderr, ", ");
   2724       fprintf(stderr, "'%s'", command_line_args[i]);
   2725     }
   2726     fprintf(stderr, "],\n");
   2727     fprintf(stderr, "  'unsaved_files' : [");
   2728     for (unsigned i = 0; i != num_unsaved_files; ++i) {
   2729       if (i)
   2730         fprintf(stderr, ", ");
   2731       fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
   2732               unsaved_files[i].Length);
   2733     }
   2734     fprintf(stderr, "],\n");
   2735     fprintf(stderr, "  'options' : %d,\n", options);
   2736     fprintf(stderr, "}\n");
   2737 
   2738     return 0;
   2739   } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
   2740     PrintLibclangResourceUsage(PTUI.result);
   2741   }
   2742 
   2743   return PTUI.result;
   2744 }
   2745 
   2746 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
   2747   return CXSaveTranslationUnit_None;
   2748 }
   2749 
   2750 namespace {
   2751 
   2752 struct SaveTranslationUnitInfo {
   2753   CXTranslationUnit TU;
   2754   const char *FileName;
   2755   unsigned options;
   2756   CXSaveError result;
   2757 };
   2758 
   2759 }
   2760 
   2761 static void clang_saveTranslationUnit_Impl(void *UserData) {
   2762   SaveTranslationUnitInfo *STUI =
   2763     static_cast<SaveTranslationUnitInfo*>(UserData);
   2764 
   2765   CIndexer *CXXIdx = STUI->TU->CIdx;
   2766   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
   2767     setThreadBackgroundPriority();
   2768 
   2769   bool hadError = cxtu::getASTUnit(STUI->TU)->Save(STUI->FileName);
   2770   STUI->result = hadError ? CXSaveError_Unknown : CXSaveError_None;
   2771 }
   2772 
   2773 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
   2774                               unsigned options) {
   2775   LOG_FUNC_SECTION {
   2776     *Log << TU << ' ' << FileName;
   2777   }
   2778 
   2779   if (!TU)
   2780     return CXSaveError_InvalidTU;
   2781 
   2782   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
   2783   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
   2784   if (!CXXUnit->hasSema())
   2785     return CXSaveError_InvalidTU;
   2786 
   2787   SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
   2788 
   2789   if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
   2790       getenv("LIBCLANG_NOTHREADS")) {
   2791     clang_saveTranslationUnit_Impl(&STUI);
   2792 
   2793     if (getenv("LIBCLANG_RESOURCE_USAGE"))
   2794       PrintLibclangResourceUsage(TU);
   2795 
   2796     return STUI.result;
   2797   }
   2798 
   2799   // We have an AST that has invalid nodes due to compiler errors.
   2800   // Use a crash recovery thread for protection.
   2801 
   2802   llvm::CrashRecoveryContext CRC;
   2803 
   2804   if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
   2805     fprintf(stderr, "libclang: crash detected during AST saving: {\n");
   2806     fprintf(stderr, "  'filename' : '%s'\n", FileName);
   2807     fprintf(stderr, "  'options' : %d,\n", options);
   2808     fprintf(stderr, "}\n");
   2809 
   2810     return CXSaveError_Unknown;
   2811 
   2812   } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
   2813     PrintLibclangResourceUsage(TU);
   2814   }
   2815 
   2816   return STUI.result;
   2817 }
   2818 
   2819 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
   2820   if (CTUnit) {
   2821     // If the translation unit has been marked as unsafe to free, just discard
   2822     // it.
   2823     if (cxtu::getASTUnit(CTUnit)->isUnsafeToFree())
   2824       return;
   2825 
   2826     delete cxtu::getASTUnit(CTUnit);
   2827     delete CTUnit->StringPool;
   2828     delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
   2829     disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
   2830     delete CTUnit->FormatContext;
   2831     delete CTUnit;
   2832   }
   2833 }
   2834 
   2835 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
   2836   return CXReparse_None;
   2837 }
   2838 
   2839 struct ReparseTranslationUnitInfo {
   2840   CXTranslationUnit TU;
   2841   unsigned num_unsaved_files;
   2842   struct CXUnsavedFile *unsaved_files;
   2843   unsigned options;
   2844   int result;
   2845 };
   2846 
   2847 static void clang_reparseTranslationUnit_Impl(void *UserData) {
   2848   ReparseTranslationUnitInfo *RTUI =
   2849     static_cast<ReparseTranslationUnitInfo*>(UserData);
   2850   CXTranslationUnit TU = RTUI->TU;
   2851   if (!TU)
   2852     return;
   2853 
   2854   // Reset the associated diagnostics.
   2855   delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
   2856   TU->Diagnostics = 0;
   2857 
   2858   unsigned num_unsaved_files = RTUI->num_unsaved_files;
   2859   struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
   2860   unsigned options = RTUI->options;
   2861   (void) options;
   2862   RTUI->result = 1;
   2863 
   2864   CIndexer *CXXIdx = TU->CIdx;
   2865   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
   2866     setThreadBackgroundPriority();
   2867 
   2868   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
   2869   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
   2870 
   2871   OwningPtr<std::vector<ASTUnit::RemappedFile> >
   2872     RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
   2873 
   2874   // Recover resources if we crash before exiting this function.
   2875   llvm::CrashRecoveryContextCleanupRegistrar<
   2876     std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
   2877 
   2878   for (unsigned I = 0; I != num_unsaved_files; ++I) {
   2879     StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
   2880     const llvm::MemoryBuffer *Buffer
   2881       = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
   2882     RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
   2883                                             Buffer));
   2884   }
   2885 
   2886   if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
   2887                         RemappedFiles->size()))
   2888     RTUI->result = 0;
   2889 }
   2890 
   2891 int clang_reparseTranslationUnit(CXTranslationUnit TU,
   2892                                  unsigned num_unsaved_files,
   2893                                  struct CXUnsavedFile *unsaved_files,
   2894                                  unsigned options) {
   2895   LOG_FUNC_SECTION {
   2896     *Log << TU;
   2897   }
   2898 
   2899   ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
   2900                                       options, 0 };
   2901 
   2902   if (getenv("LIBCLANG_NOTHREADS")) {
   2903     clang_reparseTranslationUnit_Impl(&RTUI);
   2904     return RTUI.result;
   2905   }
   2906 
   2907   llvm::CrashRecoveryContext CRC;
   2908 
   2909   if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
   2910     fprintf(stderr, "libclang: crash detected during reparsing\n");
   2911     cxtu::getASTUnit(TU)->setUnsafeToFree(true);
   2912     return 1;
   2913   } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
   2914     PrintLibclangResourceUsage(TU);
   2915 
   2916   return RTUI.result;
   2917 }
   2918 
   2919 
   2920 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
   2921   if (!CTUnit)
   2922     return cxstring::createEmpty();
   2923 
   2924   ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
   2925   return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
   2926 }
   2927 
   2928 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
   2929   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
   2930   return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
   2931 }
   2932 
   2933 } // end: extern "C"
   2934 
   2935 //===----------------------------------------------------------------------===//
   2936 // CXFile Operations.
   2937 //===----------------------------------------------------------------------===//
   2938 
   2939 extern "C" {
   2940 CXString clang_getFileName(CXFile SFile) {
   2941   if (!SFile)
   2942     return cxstring::createNull();
   2943 
   2944   FileEntry *FEnt = static_cast<FileEntry *>(SFile);
   2945   return cxstring::createRef(FEnt->getName());
   2946 }
   2947 
   2948 time_t clang_getFileTime(CXFile SFile) {
   2949   if (!SFile)
   2950     return 0;
   2951 
   2952   FileEntry *FEnt = static_cast<FileEntry *>(SFile);
   2953   return FEnt->getModificationTime();
   2954 }
   2955 
   2956 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
   2957   if (!TU)
   2958     return 0;
   2959 
   2960   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
   2961 
   2962   FileManager &FMgr = CXXUnit->getFileManager();
   2963   return const_cast<FileEntry *>(FMgr.getFile(file_name));
   2964 }
   2965 
   2966 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, CXFile file) {
   2967   if (!TU || !file)
   2968     return 0;
   2969 
   2970   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
   2971   FileEntry *FEnt = static_cast<FileEntry *>(file);
   2972   return CXXUnit->getPreprocessor().getHeaderSearchInfo()
   2973                                           .isFileMultipleIncludeGuarded(FEnt);
   2974 }
   2975 
   2976 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
   2977   if (!file || !outID)
   2978     return 1;
   2979 
   2980 #ifdef LLVM_ON_WIN32
   2981   return 1; // inodes not supported on windows.
   2982 #else
   2983   FileEntry *FEnt = static_cast<FileEntry *>(file);
   2984   outID->data[0] = FEnt->getDevice();
   2985   outID->data[1] = FEnt->getInode();
   2986   outID->data[2] = FEnt->getModificationTime();
   2987   return 0;
   2988 #endif
   2989 }
   2990 
   2991 } // end: extern "C"
   2992 
   2993 //===----------------------------------------------------------------------===//
   2994 // CXCursor Operations.
   2995 //===----------------------------------------------------------------------===//
   2996 
   2997 static const Decl *getDeclFromExpr(const Stmt *E) {
   2998   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
   2999     return getDeclFromExpr(CE->getSubExpr());
   3000 
   3001   if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
   3002     return RefExpr->getDecl();
   3003   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
   3004     return ME->getMemberDecl();
   3005   if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
   3006     return RE->getDecl();
   3007   if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
   3008     if (PRE->isExplicitProperty())
   3009       return PRE->getExplicitProperty();
   3010     // It could be messaging both getter and setter as in:
   3011     // ++myobj.myprop;
   3012     // in which case prefer to associate the setter since it is less obvious
   3013     // from inspecting the source that the setter is going to get called.
   3014     if (PRE->isMessagingSetter())
   3015       return PRE->getImplicitPropertySetter();
   3016     return PRE->getImplicitPropertyGetter();
   3017   }
   3018   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
   3019     return getDeclFromExpr(POE->getSyntacticForm());
   3020   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
   3021     if (Expr *Src = OVE->getSourceExpr())
   3022       return getDeclFromExpr(Src);
   3023 
   3024   if (const CallExpr *CE = dyn_cast<CallExpr>(E))
   3025     return getDeclFromExpr(CE->getCallee());
   3026   if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
   3027     if (!CE->isElidable())
   3028     return CE->getConstructor();
   3029   if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
   3030     return OME->getMethodDecl();
   3031 
   3032   if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
   3033     return PE->getProtocol();
   3034   if (const SubstNonTypeTemplateParmPackExpr *NTTP
   3035                               = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
   3036     return NTTP->getParameterPack();
   3037   if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
   3038     if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
   3039         isa<ParmVarDecl>(SizeOfPack->getPack()))
   3040       return SizeOfPack->getPack();
   3041 
   3042   return 0;
   3043 }
   3044 
   3045 static SourceLocation getLocationFromExpr(const Expr *E) {
   3046   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
   3047     return getLocationFromExpr(CE->getSubExpr());
   3048 
   3049   if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
   3050     return /*FIXME:*/Msg->getLeftLoc();
   3051   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
   3052     return DRE->getLocation();
   3053   if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
   3054     return Member->getMemberLoc();
   3055   if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
   3056     return Ivar->getLocation();
   3057   if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
   3058     return SizeOfPack->getPackLoc();
   3059   if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
   3060     return PropRef->getLocation();
   3061 
   3062   return E->getLocStart();
   3063 }
   3064 
   3065 extern "C" {
   3066 
   3067 unsigned clang_visitChildren(CXCursor parent,
   3068                              CXCursorVisitor visitor,
   3069                              CXClientData client_data) {
   3070   CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
   3071                           /*VisitPreprocessorLast=*/false);
   3072   return CursorVis.VisitChildren(parent);
   3073 }
   3074 
   3075 #ifndef __has_feature
   3076 #define __has_feature(x) 0
   3077 #endif
   3078 #if __has_feature(blocks)
   3079 typedef enum CXChildVisitResult
   3080      (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
   3081 
   3082 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
   3083     CXClientData client_data) {
   3084   CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
   3085   return block(cursor, parent);
   3086 }
   3087 #else
   3088 // If we are compiled with a compiler that doesn't have native blocks support,
   3089 // define and call the block manually, so the
   3090 typedef struct _CXChildVisitResult
   3091 {
   3092 	void *isa;
   3093 	int flags;
   3094 	int reserved;
   3095 	enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
   3096                                          CXCursor);
   3097 } *CXCursorVisitorBlock;
   3098 
   3099 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
   3100     CXClientData client_data) {
   3101   CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
   3102   return block->invoke(block, cursor, parent);
   3103 }
   3104 #endif
   3105 
   3106 
   3107 unsigned clang_visitChildrenWithBlock(CXCursor parent,
   3108                                       CXCursorVisitorBlock block) {
   3109   return clang_visitChildren(parent, visitWithBlock, block);
   3110 }
   3111 
   3112 static CXString getDeclSpelling(const Decl *D) {
   3113   if (!D)
   3114     return cxstring::createEmpty();
   3115 
   3116   const NamedDecl *ND = dyn_cast<NamedDecl>(D);
   3117   if (!ND) {
   3118     if (const ObjCPropertyImplDecl *PropImpl =
   3119             dyn_cast<ObjCPropertyImplDecl>(D))
   3120       if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
   3121         return cxstring::createDup(Property->getIdentifier()->getName());
   3122 
   3123     if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
   3124       if (Module *Mod = ImportD->getImportedModule())
   3125         return cxstring::createDup(Mod->getFullModuleName());
   3126 
   3127     return cxstring::createEmpty();
   3128   }
   3129 
   3130   if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
   3131     return cxstring::createDup(OMD->getSelector().getAsString());
   3132 
   3133   if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
   3134     // No, this isn't the same as the code below. getIdentifier() is non-virtual
   3135     // and returns different names. NamedDecl returns the class name and
   3136     // ObjCCategoryImplDecl returns the category name.
   3137     return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
   3138 
   3139   if (isa<UsingDirectiveDecl>(D))
   3140     return cxstring::createEmpty();
   3141 
   3142   SmallString<1024> S;
   3143   llvm::raw_svector_ostream os(S);
   3144   ND->printName(os);
   3145 
   3146   return cxstring::createDup(os.str());
   3147 }
   3148 
   3149 CXString clang_getCursorSpelling(CXCursor C) {
   3150   if (clang_isTranslationUnit(C.kind))
   3151     return clang_getTranslationUnitSpelling(getCursorTU(C));
   3152 
   3153   if (clang_isReference(C.kind)) {
   3154     switch (C.kind) {
   3155     case CXCursor_ObjCSuperClassRef: {
   3156       const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
   3157       return cxstring::createRef(Super->getIdentifier()->getNameStart());
   3158     }
   3159     case CXCursor_ObjCClassRef: {
   3160       const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
   3161       return cxstring::createRef(Class->getIdentifier()->getNameStart());
   3162     }
   3163     case CXCursor_ObjCProtocolRef: {
   3164       const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
   3165       assert(OID && "getCursorSpelling(): Missing protocol decl");
   3166       return cxstring::createRef(OID->getIdentifier()->getNameStart());
   3167     }
   3168     case CXCursor_CXXBaseSpecifier: {
   3169       const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
   3170       return cxstring::createDup(B->getType().getAsString());
   3171     }
   3172     case CXCursor_TypeRef: {
   3173       const TypeDecl *Type = getCursorTypeRef(C).first;
   3174       assert(Type && "Missing type decl");
   3175 
   3176       return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
   3177                               getAsString());
   3178     }
   3179     case CXCursor_TemplateRef: {
   3180       const TemplateDecl *Template = getCursorTemplateRef(C).first;
   3181       assert(Template && "Missing template decl");
   3182 
   3183       return cxstring::createDup(Template->getNameAsString());
   3184     }
   3185 
   3186     case CXCursor_NamespaceRef: {
   3187       const NamedDecl *NS = getCursorNamespaceRef(C).first;
   3188       assert(NS && "Missing namespace decl");
   3189 
   3190       return cxstring::createDup(NS->getNameAsString());
   3191     }
   3192 
   3193     case CXCursor_MemberRef: {
   3194       const FieldDecl *Field = getCursorMemberRef(C).first;
   3195       assert(Field && "Missing member decl");
   3196 
   3197       return cxstring::createDup(Field->getNameAsString());
   3198     }
   3199 
   3200     case CXCursor_LabelRef: {
   3201       const LabelStmt *Label = getCursorLabelRef(C).first;
   3202       assert(Label && "Missing label");
   3203 
   3204       return cxstring::createRef(Label->getName());
   3205     }
   3206 
   3207     case CXCursor_OverloadedDeclRef: {
   3208       OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
   3209       if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
   3210         if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
   3211           return cxstring::createDup(ND->getNameAsString());
   3212         return cxstring::createEmpty();
   3213       }
   3214       if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
   3215         return cxstring::createDup(E->getName().getAsString());
   3216       OverloadedTemplateStorage *Ovl
   3217         = Storage.get<OverloadedTemplateStorage*>();
   3218       if (Ovl->size() == 0)
   3219         return cxstring::createEmpty();
   3220       return cxstring::createDup((*Ovl->begin())->getNameAsString());
   3221     }
   3222 
   3223     case CXCursor_VariableRef: {
   3224       const VarDecl *Var = getCursorVariableRef(C).first;
   3225       assert(Var && "Missing variable decl");
   3226 
   3227       return cxstring::createDup(Var->getNameAsString());
   3228     }
   3229 
   3230     default:
   3231       return cxstring::createRef("<not implemented>");
   3232     }
   3233   }
   3234 
   3235   if (clang_isExpression(C.kind)) {
   3236     const Decl *D = getDeclFromExpr(getCursorExpr(C));
   3237     if (D)
   3238       return getDeclSpelling(D);
   3239     return cxstring::createEmpty();
   3240   }
   3241 
   3242   if (clang_isStatement(C.kind)) {
   3243     const Stmt *S = getCursorStmt(C);
   3244     if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
   3245       return cxstring::createRef(Label->getName());
   3246 
   3247     return cxstring::createEmpty();
   3248   }
   3249 
   3250   if (C.kind == CXCursor_MacroExpansion)
   3251     return cxstring::createRef(getCursorMacroExpansion(C).getName()
   3252                                                            ->getNameStart());
   3253 
   3254   if (C.kind == CXCursor_MacroDefinition)
   3255     return cxstring::createRef(getCursorMacroDefinition(C)->getName()
   3256                                                            ->getNameStart());
   3257 
   3258   if (C.kind == CXCursor_InclusionDirective)
   3259     return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
   3260 
   3261   if (clang_isDeclaration(C.kind))
   3262     return getDeclSpelling(getCursorDecl(C));
   3263 
   3264   if (C.kind == CXCursor_AnnotateAttr) {
   3265     const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
   3266     return cxstring::createDup(AA->getAnnotation());
   3267   }
   3268 
   3269   if (C.kind == CXCursor_AsmLabelAttr) {
   3270     const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
   3271     return cxstring::createDup(AA->getLabel());
   3272   }
   3273 
   3274   return cxstring::createEmpty();
   3275 }
   3276 
   3277 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
   3278                                                 unsigned pieceIndex,
   3279                                                 unsigned options) {
   3280   if (clang_Cursor_isNull(C))
   3281     return clang_getNullRange();
   3282 
   3283   ASTContext &Ctx = getCursorContext(C);
   3284 
   3285   if (clang_isStatement(C.kind)) {
   3286     const Stmt *S = getCursorStmt(C);
   3287     if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
   3288       if (pieceIndex > 0)
   3289         return clang_getNullRange();
   3290       return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
   3291     }
   3292 
   3293     return clang_getNullRange();
   3294   }
   3295 
   3296   if (C.kind == CXCursor_ObjCMessageExpr) {
   3297     if (const ObjCMessageExpr *
   3298           ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
   3299       if (pieceIndex >= ME->getNumSelectorLocs())
   3300         return clang_getNullRange();
   3301       return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
   3302     }
   3303   }
   3304 
   3305   if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
   3306       C.kind == CXCursor_ObjCClassMethodDecl) {
   3307     if (const ObjCMethodDecl *
   3308           MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
   3309       if (pieceIndex >= MD->getNumSelectorLocs())
   3310         return clang_getNullRange();
   3311       return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
   3312     }
   3313   }
   3314 
   3315   if (C.kind == CXCursor_ObjCCategoryDecl ||
   3316       C.kind == CXCursor_ObjCCategoryImplDecl) {
   3317     if (pieceIndex > 0)
   3318       return clang_getNullRange();
   3319     if (const ObjCCategoryDecl *
   3320           CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
   3321       return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
   3322     if (const ObjCCategoryImplDecl *
   3323           CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
   3324       return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
   3325   }
   3326 
   3327   if (C.kind == CXCursor_ModuleImportDecl) {
   3328     if (pieceIndex > 0)
   3329       return clang_getNullRange();
   3330     if (const ImportDecl *ImportD =
   3331             dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
   3332       ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
   3333       if (!Locs.empty())
   3334         return cxloc::translateSourceRange(Ctx,
   3335                                          SourceRange(Locs.front(), Locs.back()));
   3336     }
   3337     return clang_getNullRange();
   3338   }
   3339 
   3340   // FIXME: A CXCursor_InclusionDirective should give the location of the
   3341   // filename, but we don't keep track of this.
   3342 
   3343   // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
   3344   // but we don't keep track of this.
   3345 
   3346   // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
   3347   // but we don't keep track of this.
   3348 
   3349   // Default handling, give the location of the cursor.
   3350 
   3351   if (pieceIndex > 0)
   3352     return clang_getNullRange();
   3353 
   3354   CXSourceLocation CXLoc = clang_getCursorLocation(C);
   3355   SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
   3356   return cxloc::translateSourceRange(Ctx, Loc);
   3357 }
   3358 
   3359 CXString clang_getCursorDisplayName(CXCursor C) {
   3360   if (!clang_isDeclaration(C.kind))
   3361     return clang_getCursorSpelling(C);
   3362 
   3363   const Decl *D = getCursorDecl(C);
   3364   if (!D)
   3365     return cxstring::createEmpty();
   3366 
   3367   PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
   3368   if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
   3369     D = FunTmpl->getTemplatedDecl();
   3370 
   3371   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
   3372     SmallString<64> Str;
   3373     llvm::raw_svector_ostream OS(Str);
   3374     OS << *Function;
   3375     if (Function->getPrimaryTemplate())
   3376       OS << "<>";
   3377     OS << "(";
   3378     for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
   3379       if (I)
   3380         OS << ", ";
   3381       OS << Function->getParamDecl(I)->getType().getAsString(Policy);
   3382     }
   3383 
   3384     if (Function->isVariadic()) {
   3385       if (Function->getNumParams())
   3386         OS << ", ";
   3387       OS << "...";
   3388     }
   3389     OS << ")";
   3390     return cxstring::createDup(OS.str());
   3391   }
   3392 
   3393   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
   3394     SmallString<64> Str;
   3395     llvm::raw_svector_ostream OS(Str);
   3396     OS << *ClassTemplate;
   3397     OS << "<";
   3398     TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
   3399     for (unsigned I = 0, N = Params->size(); I != N; ++I) {
   3400       if (I)
   3401         OS << ", ";
   3402 
   3403       NamedDecl *Param = Params->getParam(I);
   3404       if (Param->getIdentifier()) {
   3405         OS << Param->getIdentifier()->getName();
   3406         continue;
   3407       }
   3408 
   3409       // There is no parameter name, which makes this tricky. Try to come up
   3410       // with something useful that isn't too long.
   3411       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
   3412         OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
   3413       else if (NonTypeTemplateParmDecl *NTTP
   3414                                     = dyn_cast<NonTypeTemplateParmDecl>(Param))
   3415         OS << NTTP->getType().getAsString(Policy);
   3416       else
   3417         OS << "template<...> class";
   3418     }
   3419 
   3420     OS << ">";
   3421     return cxstring::createDup(OS.str());
   3422   }
   3423 
   3424   if (const ClassTemplateSpecializationDecl *ClassSpec
   3425                               = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
   3426     // If the type was explicitly written, use that.
   3427     if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
   3428       return cxstring::createDup(TSInfo->getType().getAsString(Policy));
   3429 
   3430     SmallString<128> Str;
   3431     llvm::raw_svector_ostream OS(Str);
   3432     OS << *ClassSpec;
   3433     TemplateSpecializationType::PrintTemplateArgumentList(OS,
   3434                                       ClassSpec->getTemplateArgs().data(),
   3435                                       ClassSpec->getTemplateArgs().size(),
   3436                                                                 Policy);
   3437     return cxstring::createDup(OS.str());
   3438   }
   3439 
   3440   return clang_getCursorSpelling(C);
   3441 }
   3442 
   3443 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
   3444   switch (Kind) {
   3445   case CXCursor_FunctionDecl:
   3446       return cxstring::createRef("FunctionDecl");
   3447   case CXCursor_TypedefDecl:
   3448       return cxstring::createRef("TypedefDecl");
   3449   case CXCursor_EnumDecl:
   3450       return cxstring::createRef("EnumDecl");
   3451   case CXCursor_EnumConstantDecl:
   3452       return cxstring::createRef("EnumConstantDecl");
   3453   case CXCursor_StructDecl:
   3454       return cxstring::createRef("StructDecl");
   3455   case CXCursor_UnionDecl:
   3456       return cxstring::createRef("UnionDecl");
   3457   case CXCursor_ClassDecl:
   3458       return cxstring::createRef("ClassDecl");
   3459   case CXCursor_FieldDecl:
   3460       return cxstring::createRef("FieldDecl");
   3461   case CXCursor_VarDecl:
   3462       return cxstring::createRef("VarDecl");
   3463   case CXCursor_ParmDecl:
   3464       return cxstring::createRef("ParmDecl");
   3465   case CXCursor_ObjCInterfaceDecl:
   3466       return cxstring::createRef("ObjCInterfaceDecl");
   3467   case CXCursor_ObjCCategoryDecl:
   3468       return cxstring::createRef("ObjCCategoryDecl");
   3469   case CXCursor_ObjCProtocolDecl:
   3470       return cxstring::createRef("ObjCProtocolDecl");
   3471   case CXCursor_ObjCPropertyDecl:
   3472       return cxstring::createRef("ObjCPropertyDecl");
   3473   case CXCursor_ObjCIvarDecl:
   3474       return cxstring::createRef("ObjCIvarDecl");
   3475   case CXCursor_ObjCInstanceMethodDecl:
   3476       return cxstring::createRef("ObjCInstanceMethodDecl");
   3477   case CXCursor_ObjCClassMethodDecl:
   3478       return cxstring::createRef("ObjCClassMethodDecl");
   3479   case CXCursor_ObjCImplementationDecl:
   3480       return cxstring::createRef("ObjCImplementationDecl");
   3481   case CXCursor_ObjCCategoryImplDecl:
   3482       return cxstring::createRef("ObjCCategoryImplDecl");
   3483   case CXCursor_CXXMethod:
   3484       return cxstring::createRef("CXXMethod");
   3485   case CXCursor_UnexposedDecl:
   3486       return cxstring::createRef("UnexposedDecl");
   3487   case CXCursor_ObjCSuperClassRef:
   3488       return cxstring::createRef("ObjCSuperClassRef");
   3489   case CXCursor_ObjCProtocolRef:
   3490       return cxstring::createRef("ObjCProtocolRef");
   3491   case CXCursor_ObjCClassRef:
   3492       return cxstring::createRef("ObjCClassRef");
   3493   case CXCursor_TypeRef:
   3494       return cxstring::createRef("TypeRef");
   3495   case CXCursor_TemplateRef:
   3496       return cxstring::createRef("TemplateRef");
   3497   case CXCursor_NamespaceRef:
   3498     return cxstring::createRef("NamespaceRef");
   3499   case CXCursor_MemberRef:
   3500     return cxstring::createRef("MemberRef");
   3501   case CXCursor_LabelRef:
   3502     return cxstring::createRef("LabelRef");
   3503   case CXCursor_OverloadedDeclRef:
   3504     return cxstring::createRef("OverloadedDeclRef");
   3505   case CXCursor_VariableRef:
   3506     return cxstring::createRef("VariableRef");
   3507   case CXCursor_IntegerLiteral:
   3508       return cxstring::createRef("IntegerLiteral");
   3509   case CXCursor_FloatingLiteral:
   3510       return cxstring::createRef("FloatingLiteral");
   3511   case CXCursor_ImaginaryLiteral:
   3512       return cxstring::createRef("ImaginaryLiteral");
   3513   case CXCursor_StringLiteral:
   3514       return cxstring::createRef("StringLiteral");
   3515   case CXCursor_CharacterLiteral:
   3516       return cxstring::createRef("CharacterLiteral");
   3517   case CXCursor_ParenExpr:
   3518       return cxstring::createRef("ParenExpr");
   3519   case CXCursor_UnaryOperator:
   3520       return cxstring::createRef("UnaryOperator");
   3521   case CXCursor_ArraySubscriptExpr:
   3522       return cxstring::createRef("ArraySubscriptExpr");
   3523   case CXCursor_BinaryOperator:
   3524       return cxstring::createRef("BinaryOperator");
   3525   case CXCursor_CompoundAssignOperator:
   3526       return cxstring::createRef("CompoundAssignOperator");
   3527   case CXCursor_ConditionalOperator:
   3528       return cxstring::createRef("ConditionalOperator");
   3529   case CXCursor_CStyleCastExpr:
   3530       return cxstring::createRef("CStyleCastExpr");
   3531   case CXCursor_CompoundLiteralExpr:
   3532       return cxstring::createRef("CompoundLiteralExpr");
   3533   case CXCursor_InitListExpr:
   3534       return cxstring::createRef("InitListExpr");
   3535   case CXCursor_AddrLabelExpr:
   3536       return cxstring::createRef("AddrLabelExpr");
   3537   case CXCursor_StmtExpr:
   3538       return cxstring::createRef("StmtExpr");
   3539   case CXCursor_GenericSelectionExpr:
   3540       return cxstring::createRef("GenericSelectionExpr");
   3541   case CXCursor_GNUNullExpr:
   3542       return cxstring::createRef("GNUNullExpr");
   3543   case CXCursor_CXXStaticCastExpr:
   3544       return cxstring::createRef("CXXStaticCastExpr");
   3545   case CXCursor_CXXDynamicCastExpr:
   3546       return cxstring::createRef("CXXDynamicCastExpr");
   3547   case CXCursor_CXXReinterpretCastExpr:
   3548       return cxstring::createRef("CXXReinterpretCastExpr");
   3549   case CXCursor_CXXConstCastExpr:
   3550       return cxstring::createRef("CXXConstCastExpr");
   3551   case CXCursor_CXXFunctionalCastExpr:
   3552       return cxstring::createRef("CXXFunctionalCastExpr");
   3553   case CXCursor_CXXTypeidExpr:
   3554       return cxstring::createRef("CXXTypeidExpr");
   3555   case CXCursor_CXXBoolLiteralExpr:
   3556       return cxstring::createRef("CXXBoolLiteralExpr");
   3557   case CXCursor_CXXNullPtrLiteralExpr:
   3558       return cxstring::createRef("CXXNullPtrLiteralExpr");
   3559   case CXCursor_CXXThisExpr:
   3560       return cxstring::createRef("CXXThisExpr");
   3561   case CXCursor_CXXThrowExpr:
   3562       return cxstring::createRef("CXXThrowExpr");
   3563   case CXCursor_CXXNewExpr:
   3564       return cxstring::createRef("CXXNewExpr");
   3565   case CXCursor_CXXDeleteExpr:
   3566       return cxstring::createRef("CXXDeleteExpr");
   3567   case CXCursor_UnaryExpr:
   3568       return cxstring::createRef("UnaryExpr");
   3569   case CXCursor_ObjCStringLiteral:
   3570       return cxstring::createRef("ObjCStringLiteral");
   3571   case CXCursor_ObjCBoolLiteralExpr:
   3572       return cxstring::createRef("ObjCBoolLiteralExpr");
   3573   case CXCursor_ObjCEncodeExpr:
   3574       return cxstring::createRef("ObjCEncodeExpr");
   3575   case CXCursor_ObjCSelectorExpr:
   3576       return cxstring::createRef("ObjCSelectorExpr");
   3577   case CXCursor_ObjCProtocolExpr:
   3578       return cxstring::createRef("ObjCProtocolExpr");
   3579   case CXCursor_ObjCBridgedCastExpr:
   3580       return cxstring::createRef("ObjCBridgedCastExpr");
   3581   case CXCursor_BlockExpr:
   3582       return cxstring::createRef("BlockExpr");
   3583   case CXCursor_PackExpansionExpr:
   3584       return cxstring::createRef("PackExpansionExpr");
   3585   case CXCursor_SizeOfPackExpr:
   3586       return cxstring::createRef("SizeOfPackExpr");
   3587   case CXCursor_LambdaExpr:
   3588     return cxstring::createRef("LambdaExpr");
   3589   case CXCursor_UnexposedExpr:
   3590       return cxstring::createRef("UnexposedExpr");
   3591   case CXCursor_DeclRefExpr:
   3592       return cxstring::createRef("DeclRefExpr");
   3593   case CXCursor_MemberRefExpr:
   3594       return cxstring::createRef("MemberRefExpr");
   3595   case CXCursor_CallExpr:
   3596       return cxstring::createRef("CallExpr");
   3597   case CXCursor_ObjCMessageExpr:
   3598       return cxstring::createRef("ObjCMessageExpr");
   3599   case CXCursor_UnexposedStmt:
   3600       return cxstring::createRef("UnexposedStmt");
   3601   case CXCursor_DeclStmt:
   3602       return cxstring::createRef("DeclStmt");
   3603   case CXCursor_LabelStmt:
   3604       return cxstring::createRef("LabelStmt");
   3605   case CXCursor_CompoundStmt:
   3606       return cxstring::createRef("CompoundStmt");
   3607   case CXCursor_CaseStmt:
   3608       return cxstring::createRef("CaseStmt");
   3609   case CXCursor_DefaultStmt:
   3610       return cxstring::createRef("DefaultStmt");
   3611   case CXCursor_IfStmt:
   3612       return cxstring::createRef("IfStmt");
   3613   case CXCursor_SwitchStmt:
   3614       return cxstring::createRef("SwitchStmt");
   3615   case CXCursor_WhileStmt:
   3616       return cxstring::createRef("WhileStmt");
   3617   case CXCursor_DoStmt:
   3618       return cxstring::createRef("DoStmt");
   3619   case CXCursor_ForStmt:
   3620       return cxstring::createRef("ForStmt");
   3621   case CXCursor_GotoStmt:
   3622       return cxstring::createRef("GotoStmt");
   3623   case CXCursor_IndirectGotoStmt:
   3624       return cxstring::createRef("IndirectGotoStmt");
   3625   case CXCursor_ContinueStmt:
   3626       return cxstring::createRef("ContinueStmt");
   3627   case CXCursor_BreakStmt:
   3628       return cxstring::createRef("BreakStmt");
   3629   case CXCursor_ReturnStmt:
   3630       return cxstring::createRef("ReturnStmt");
   3631   case CXCursor_GCCAsmStmt:
   3632       return cxstring::createRef("GCCAsmStmt");
   3633   case CXCursor_MSAsmStmt:
   3634       return cxstring::createRef("MSAsmStmt");
   3635   case CXCursor_ObjCAtTryStmt:
   3636       return cxstring::createRef("ObjCAtTryStmt");
   3637   case CXCursor_ObjCAtCatchStmt:
   3638       return cxstring::createRef("ObjCAtCatchStmt");
   3639   case CXCursor_ObjCAtFinallyStmt:
   3640       return cxstring::createRef("ObjCAtFinallyStmt");
   3641   case CXCursor_ObjCAtThrowStmt:
   3642       return cxstring::createRef("ObjCAtThrowStmt");
   3643   case CXCursor_ObjCAtSynchronizedStmt:
   3644       return cxstring::createRef("ObjCAtSynchronizedStmt");
   3645   case CXCursor_ObjCAutoreleasePoolStmt:
   3646       return cxstring::createRef("ObjCAutoreleasePoolStmt");
   3647   case CXCursor_ObjCForCollectionStmt:
   3648       return cxstring::createRef("ObjCForCollectionStmt");
   3649   case CXCursor_CXXCatchStmt:
   3650       return cxstring::createRef("CXXCatchStmt");
   3651   case CXCursor_CXXTryStmt:
   3652       return cxstring::createRef("CXXTryStmt");
   3653   case CXCursor_CXXForRangeStmt:
   3654       return cxstring::createRef("CXXForRangeStmt");
   3655   case CXCursor_SEHTryStmt:
   3656       return cxstring::createRef("SEHTryStmt");
   3657   case CXCursor_SEHExceptStmt:
   3658       return cxstring::createRef("SEHExceptStmt");
   3659   case CXCursor_SEHFinallyStmt:
   3660       return cxstring::createRef("SEHFinallyStmt");
   3661   case CXCursor_NullStmt:
   3662       return cxstring::createRef("NullStmt");
   3663   case CXCursor_InvalidFile:
   3664       return cxstring::createRef("InvalidFile");
   3665   case CXCursor_InvalidCode:
   3666     return cxstring::createRef("InvalidCode");
   3667   case CXCursor_NoDeclFound:
   3668       return cxstring::createRef("NoDeclFound");
   3669   case CXCursor_NotImplemented:
   3670       return cxstring::createRef("NotImplemented");
   3671   case CXCursor_TranslationUnit:
   3672       return cxstring::createRef("TranslationUnit");
   3673   case CXCursor_UnexposedAttr:
   3674       return cxstring::createRef("UnexposedAttr");
   3675   case CXCursor_IBActionAttr:
   3676       return cxstring::createRef("attribute(ibaction)");
   3677   case CXCursor_IBOutletAttr:
   3678      return cxstring::createRef("attribute(iboutlet)");
   3679   case CXCursor_IBOutletCollectionAttr:
   3680       return cxstring::createRef("attribute(iboutletcollection)");
   3681   case CXCursor_CXXFinalAttr:
   3682       return cxstring::createRef("attribute(final)");
   3683   case CXCursor_CXXOverrideAttr:
   3684       return cxstring::createRef("attribute(override)");
   3685   case CXCursor_AnnotateAttr:
   3686     return cxstring::createRef("attribute(annotate)");
   3687   case CXCursor_AsmLabelAttr:
   3688     return cxstring::createRef("asm label");
   3689   case CXCursor_PreprocessingDirective:
   3690     return cxstring::createRef("preprocessing directive");
   3691   case CXCursor_MacroDefinition:
   3692     return cxstring::createRef("macro definition");
   3693   case CXCursor_MacroExpansion:
   3694     return cxstring::createRef("macro expansion");
   3695   case CXCursor_InclusionDirective:
   3696     return cxstring::createRef("inclusion directive");
   3697   case CXCursor_Namespace:
   3698     return cxstring::createRef("Namespace");
   3699   case CXCursor_LinkageSpec:
   3700     return cxstring::createRef("LinkageSpec");
   3701   case CXCursor_CXXBaseSpecifier:
   3702     return cxstring::createRef("C++ base class specifier");
   3703   case CXCursor_Constructor:
   3704     return cxstring::createRef("CXXConstructor");
   3705   case CXCursor_Destructor:
   3706     return cxstring::createRef("CXXDestructor");
   3707   case CXCursor_ConversionFunction:
   3708     return cxstring::createRef("CXXConversion");
   3709   case CXCursor_TemplateTypeParameter:
   3710     return cxstring::createRef("TemplateTypeParameter");
   3711   case CXCursor_NonTypeTemplateParameter:
   3712     return cxstring::createRef("NonTypeTemplateParameter");
   3713   case CXCursor_TemplateTemplateParameter:
   3714     return cxstring::createRef("TemplateTemplateParameter");
   3715   case CXCursor_FunctionTemplate:
   3716     return cxstring::createRef("FunctionTemplate");
   3717   case CXCursor_ClassTemplate:
   3718     return cxstring::createRef("ClassTemplate");
   3719   case CXCursor_ClassTemplatePartialSpecialization:
   3720     return cxstring::createRef("ClassTemplatePartialSpecialization");
   3721   case CXCursor_NamespaceAlias:
   3722     return cxstring::createRef("NamespaceAlias");
   3723   case CXCursor_UsingDirective:
   3724     return cxstring::createRef("UsingDirective");
   3725   case CXCursor_UsingDeclaration:
   3726     return cxstring::createRef("UsingDeclaration");
   3727   case CXCursor_TypeAliasDecl:
   3728     return cxstring::createRef("TypeAliasDecl");
   3729   case CXCursor_ObjCSynthesizeDecl:
   3730     return cxstring::createRef("ObjCSynthesizeDecl");
   3731   case CXCursor_ObjCDynamicDecl:
   3732     return cxstring::createRef("ObjCDynamicDecl");
   3733   case CXCursor_CXXAccessSpecifier:
   3734     return cxstring::createRef("CXXAccessSpecifier");
   3735   case CXCursor_ModuleImportDecl:
   3736     return cxstring::createRef("ModuleImport");
   3737   }
   3738 
   3739   llvm_unreachable("Unhandled CXCursorKind");
   3740 }
   3741 
   3742 struct GetCursorData {
   3743   SourceLocation TokenBeginLoc;
   3744   bool PointsAtMacroArgExpansion;
   3745   bool VisitedObjCPropertyImplDecl;
   3746   SourceLocation VisitedDeclaratorDeclStartLoc;
   3747   CXCursor &BestCursor;
   3748 
   3749   GetCursorData(SourceManager &SM,
   3750                 SourceLocation tokenBegin, CXCursor &outputCursor)
   3751     : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
   3752     PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
   3753     VisitedObjCPropertyImplDecl = false;
   3754   }
   3755 };
   3756 
   3757 static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
   3758                                                 CXCursor parent,
   3759                                                 CXClientData client_data) {
   3760   GetCursorData *Data = static_cast<GetCursorData *>(client_data);
   3761   CXCursor *BestCursor = &Data->BestCursor;
   3762 
   3763   // If we point inside a macro argument we should provide info of what the
   3764   // token is so use the actual cursor, don't replace it with a macro expansion
   3765   // cursor.
   3766   if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
   3767     return CXChildVisit_Recurse;
   3768 
   3769   if (clang_isDeclaration(cursor.kind)) {
   3770     // Avoid having the implicit methods override the property decls.
   3771     if (const ObjCMethodDecl *MD
   3772           = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
   3773       if (MD->isImplicit())
   3774         return CXChildVisit_Break;
   3775 
   3776     } else if (const ObjCInterfaceDecl *ID
   3777                  = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
   3778       // Check that when we have multiple @class references in the same line,
   3779       // that later ones do not override the previous ones.
   3780       // If we have:
   3781       // @class Foo, Bar;
   3782       // source ranges for both start at '@', so 'Bar' will end up overriding
   3783       // 'Foo' even though the cursor location was at 'Foo'.
   3784       if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
   3785           BestCursor->kind == CXCursor_ObjCClassRef)
   3786         if (const ObjCInterfaceDecl *PrevID
   3787              = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
   3788          if (PrevID != ID &&
   3789              !PrevID->isThisDeclarationADefinition() &&
   3790              !ID->isThisDeclarationADefinition())
   3791            return CXChildVisit_Break;
   3792         }
   3793 
   3794     } else if (const DeclaratorDecl *DD
   3795                     = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
   3796       SourceLocation StartLoc = DD->getSourceRange().getBegin();
   3797       // Check that when we have multiple declarators in the same line,
   3798       // that later ones do not override the previous ones.
   3799       // If we have:
   3800       // int Foo, Bar;
   3801       // source ranges for both start at 'int', so 'Bar' will end up overriding
   3802       // 'Foo' even though the cursor location was at 'Foo'.
   3803       if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
   3804         return CXChildVisit_Break;
   3805       Data->VisitedDeclaratorDeclStartLoc = StartLoc;
   3806 
   3807     } else if (const ObjCPropertyImplDecl *PropImp
   3808               = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
   3809       (void)PropImp;
   3810       // Check that when we have multiple @synthesize in the same line,
   3811       // that later ones do not override the previous ones.
   3812       // If we have:
   3813       // @synthesize Foo, Bar;
   3814       // source ranges for both start at '@', so 'Bar' will end up overriding
   3815       // 'Foo' even though the cursor location was at 'Foo'.
   3816       if (Data->VisitedObjCPropertyImplDecl)
   3817         return CXChildVisit_Break;
   3818       Data->VisitedObjCPropertyImplDecl = true;
   3819     }
   3820   }
   3821 
   3822   if (clang_isExpression(cursor.kind) &&
   3823       clang_isDeclaration(BestCursor->kind)) {
   3824     if (const Decl *D = getCursorDecl(*BestCursor)) {
   3825       // Avoid having the cursor of an expression replace the declaration cursor
   3826       // when the expression source range overlaps the declaration range.
   3827       // This can happen for C++ constructor expressions whose range generally
   3828       // include the variable declaration, e.g.:
   3829       //  MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
   3830       if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
   3831           D->getLocation() == Data->TokenBeginLoc)
   3832         return CXChildVisit_Break;
   3833     }
   3834   }
   3835 
   3836   // If our current best cursor is the construction of a temporary object,
   3837   // don't replace that cursor with a type reference, because we want
   3838   // clang_getCursor() to point at the constructor.
   3839   if (clang_isExpression(BestCursor->kind) &&
   3840       isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
   3841       cursor.kind == CXCursor_TypeRef) {
   3842     // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
   3843     // as having the actual point on the type reference.
   3844     *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
   3845     return CXChildVisit_Recurse;
   3846   }
   3847 
   3848   *BestCursor = cursor;
   3849   return CXChildVisit_Recurse;
   3850 }
   3851 
   3852 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
   3853   if (!TU)
   3854     return clang_getNullCursor();
   3855 
   3856   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
   3857   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
   3858 
   3859   SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
   3860   CXCursor Result = cxcursor::getCursor(TU, SLoc);
   3861 
   3862   LOG_FUNC_SECTION {
   3863     CXFile SearchFile;
   3864     unsigned SearchLine, SearchColumn;
   3865     CXFile ResultFile;
   3866     unsigned ResultLine, ResultColumn;
   3867     CXString SearchFileName, ResultFileName, KindSpelling, USR;
   3868     const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
   3869     CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
   3870 
   3871     clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
   3872     clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
   3873                                &ResultColumn, 0);
   3874     SearchFileName = clang_getFileName(SearchFile);
   3875     ResultFileName = clang_getFileName(ResultFile);
   3876     KindSpelling = clang_getCursorKindSpelling(Result.kind);
   3877     USR = clang_getCursorUSR(Result);
   3878     *Log << llvm::format("(%s:%d:%d) = %s",
   3879                    clang_getCString(SearchFileName), SearchLine, SearchColumn,
   3880                    clang_getCString(KindSpelling))
   3881         << llvm::format("(%s:%d:%d):%s%s",
   3882                      clang_getCString(ResultFileName), ResultLine, ResultColumn,
   3883                      clang_getCString(USR), IsDef);
   3884     clang_disposeString(SearchFileName);
   3885     clang_disposeString(ResultFileName);
   3886     clang_disposeString(KindSpelling);
   3887     clang_disposeString(USR);
   3888 
   3889     CXCursor Definition = clang_getCursorDefinition(Result);
   3890     if (!clang_equalCursors(Definition, clang_getNullCursor())) {
   3891       CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
   3892       CXString DefinitionKindSpelling
   3893                                 = clang_getCursorKindSpelling(Definition.kind);
   3894       CXFile DefinitionFile;
   3895       unsigned DefinitionLine, DefinitionColumn;
   3896       clang_getFileLocation(DefinitionLoc, &DefinitionFile,
   3897                                  &DefinitionLine, &DefinitionColumn, 0);
   3898       CXString DefinitionFileName = clang_getFileName(DefinitionFile);
   3899       *Log << llvm::format("  -> %s(%s:%d:%d)",
   3900                      clang_getCString(DefinitionKindSpelling),
   3901                      clang_getCString(DefinitionFileName),
   3902                      DefinitionLine, DefinitionColumn);
   3903       clang_disposeString(DefinitionFileName);
   3904       clang_disposeString(DefinitionKindSpelling);
   3905     }
   3906   }
   3907 
   3908   return Result;
   3909 }
   3910 
   3911 CXCursor clang_getNullCursor(void) {
   3912   return MakeCXCursorInvalid(CXCursor_InvalidFile);
   3913 }
   3914 
   3915 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
   3916   // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
   3917   // can't set consistently. For example, when visiting a DeclStmt we will set
   3918   // it but we don't set it on the result of clang_getCursorDefinition for
   3919   // a reference of the same declaration.
   3920   // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
   3921   // when visiting a DeclStmt currently, the AST should be enhanced to be able
   3922   // to provide that kind of info.
   3923   if (clang_isDeclaration(X.kind))
   3924     X.data[1] = 0;
   3925   if (clang_isDeclaration(Y.kind))
   3926     Y.data[1] = 0;
   3927 
   3928   return X == Y;
   3929 }
   3930 
   3931 unsigned clang_hashCursor(CXCursor C) {
   3932   unsigned Index = 0;
   3933   if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
   3934     Index = 1;
   3935 
   3936   return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
   3937                                         std::make_pair(C.kind, C.data[Index]));
   3938 }
   3939 
   3940 unsigned clang_isInvalid(enum CXCursorKind K) {
   3941   return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
   3942 }
   3943 
   3944 unsigned clang_isDeclaration(enum CXCursorKind K) {
   3945   return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
   3946          (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
   3947 }
   3948 
   3949 unsigned clang_isReference(enum CXCursorKind K) {
   3950   return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
   3951 }
   3952 
   3953 unsigned clang_isExpression(enum CXCursorKind K) {
   3954   return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
   3955 }
   3956 
   3957 unsigned clang_isStatement(enum CXCursorKind K) {
   3958   return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
   3959 }
   3960 
   3961 unsigned clang_isAttribute(enum CXCursorKind K) {
   3962     return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
   3963 }
   3964 
   3965 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
   3966   return K == CXCursor_TranslationUnit;
   3967 }
   3968 
   3969 unsigned clang_isPreprocessing(enum CXCursorKind K) {
   3970   return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
   3971 }
   3972 
   3973 unsigned clang_isUnexposed(enum CXCursorKind K) {
   3974   switch (K) {
   3975     case CXCursor_UnexposedDecl:
   3976     case CXCursor_UnexposedExpr:
   3977     case CXCursor_UnexposedStmt:
   3978     case CXCursor_UnexposedAttr:
   3979       return true;
   3980     default:
   3981       return false;
   3982   }
   3983 }
   3984 
   3985 CXCursorKind clang_getCursorKind(CXCursor C) {
   3986   return C.kind;
   3987 }
   3988 
   3989 CXSourceLocation clang_getCursorLocation(CXCursor C) {
   3990   if (clang_isReference(C.kind)) {
   3991     switch (C.kind) {
   3992     case CXCursor_ObjCSuperClassRef: {
   3993       std::pair<const ObjCInterfaceDecl *, SourceLocation> P
   3994         = getCursorObjCSuperClassRef(C);
   3995       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
   3996     }
   3997 
   3998     case CXCursor_ObjCProtocolRef: {
   3999       std::pair<const ObjCProtocolDecl *, SourceLocation> P
   4000         = getCursorObjCProtocolRef(C);
   4001       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
   4002     }
   4003 
   4004     case CXCursor_ObjCClassRef: {
   4005       std::pair<const ObjCInterfaceDecl *, SourceLocation> P
   4006         = getCursorObjCClassRef(C);
   4007       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
   4008     }
   4009 
   4010     case CXCursor_TypeRef: {
   4011       std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
   4012       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
   4013     }
   4014 
   4015     case CXCursor_TemplateRef: {
   4016       std::pair<const TemplateDecl *, SourceLocation> P =
   4017           getCursorTemplateRef(C);
   4018       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
   4019     }
   4020 
   4021     case CXCursor_NamespaceRef: {
   4022       std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
   4023       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
   4024     }
   4025 
   4026     case CXCursor_MemberRef: {
   4027       std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
   4028       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
   4029     }
   4030 
   4031     case CXCursor_VariableRef: {
   4032       std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
   4033       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
   4034     }
   4035 
   4036     case CXCursor_CXXBaseSpecifier: {
   4037       const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
   4038       if (!BaseSpec)
   4039         return clang_getNullLocation();
   4040 
   4041       if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
   4042         return cxloc::translateSourceLocation(getCursorContext(C),
   4043                                             TSInfo->getTypeLoc().getBeginLoc());
   4044 
   4045       return cxloc::translateSourceLocation(getCursorContext(C),
   4046