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