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)
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)
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)
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)
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 VisitOMPMaskedTaskLoopSimdDirective(
2185       const OMPMaskedTaskLoopSimdDirective *D);
2186   void VisitOMPParallelMasterTaskLoopDirective(
2187       const OMPParallelMasterTaskLoopDirective *D);
2188   void VisitOMPParallelMasterTaskLoopSimdDirective(
2189       const OMPParallelMasterTaskLoopSimdDirective *D);
2190   void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
2191   void VisitOMPDistributeParallelForDirective(
2192       const OMPDistributeParallelForDirective *D);
2193   void VisitOMPDistributeParallelForSimdDirective(
2194       const OMPDistributeParallelForSimdDirective *D);
2195   void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
2196   void VisitOMPTargetParallelForSimdDirective(
2197       const OMPTargetParallelForSimdDirective *D);
2198   void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
2199   void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
2200   void VisitOMPTeamsDistributeSimdDirective(
2201       const OMPTeamsDistributeSimdDirective *D);
2202   void VisitOMPTeamsDistributeParallelForSimdDirective(
2203       const OMPTeamsDistributeParallelForSimdDirective *D);
2204   void VisitOMPTeamsDistributeParallelForDirective(
2205       const OMPTeamsDistributeParallelForDirective *D);
2206   void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
2207   void VisitOMPTargetTeamsDistributeDirective(
2208       const OMPTargetTeamsDistributeDirective *D);
2209   void VisitOMPTargetTeamsDistributeParallelForDirective(
2210       const OMPTargetTeamsDistributeParallelForDirective *D);
2211   void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2212       const OMPTargetTeamsDistributeParallelForSimdDirective *D);
2213   void VisitOMPTargetTeamsDistributeSimdDirective(
2214       const OMPTargetTeamsDistributeSimdDirective *D);
2215 
2216 private:
2217   void AddDeclarationNameInfo(const Stmt *S);
2218   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
2219   void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2220                                unsigned NumTemplateArgs);
2221   void AddMemberRef(const FieldDecl *D, SourceLocation L);
2222   void AddStmt(const Stmt *S);
2223   void AddDecl(const Decl *D, bool isFirst = true);
2224   void AddTypeLoc(TypeSourceInfo *TI);
2225   void EnqueueChildren(const Stmt *S);
2226   void EnqueueChildren(const OMPClause *S);
2227 };
2228 } // namespace
2229 
2230 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
2231   // 'S' should always be non-null, since it comes from the
2232   // statement we are visiting.
2233   WL.push_back(DeclarationNameInfoVisit(S, Parent));
2234 }
2235 
2236 void EnqueueVisitor::AddNestedNameSpecifierLoc(
2237     NestedNameSpecifierLoc Qualifier) {
2238   if (Qualifier)
2239     WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2240 }
2241 
2242 void EnqueueVisitor::AddStmt(const Stmt *S) {
2243   if (S)
2244     WL.push_back(StmtVisit(S, Parent));
2245 }
2246 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
2247   if (D)
2248     WL.push_back(DeclVisit(D, Parent, isFirst));
2249 }
2250 void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2251                                              unsigned NumTemplateArgs) {
2252   WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
2253 }
2254 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
2255   if (D)
2256     WL.push_back(MemberRefVisit(D, L, Parent));
2257 }
2258 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2259   if (TI)
2260     WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2261 }
2262 void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
2263   unsigned size = WL.size();
2264   for (const Stmt *SubStmt : S->children()) {
2265     AddStmt(SubStmt);
2266   }
2267   if (size == WL.size())
2268     return;
2269   // Now reverse the entries we just added.  This will match the DFS
2270   // ordering performed by the worklist.
2271   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2272   std::reverse(I, E);
2273 }
2274 namespace {
2275 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2276   EnqueueVisitor *Visitor;
2277   /// Process clauses with list of variables.
2278   template <typename T> void VisitOMPClauseList(T *Node);
2279 
2280 public:
2281   OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) {}
2282 #define GEN_CLANG_CLAUSE_CLASS
2283 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(const Class *C);
2284 #include "llvm/Frontend/OpenMP/OMP.inc"
2285   void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
2286   void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
2287 };
2288 
2289 void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2290     const OMPClauseWithPreInit *C) {
2291   Visitor->AddStmt(C->getPreInitStmt());
2292 }
2293 
2294 void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2295     const OMPClauseWithPostUpdate *C) {
2296   VisitOMPClauseWithPreInit(C);
2297   Visitor->AddStmt(C->getPostUpdateExpr());
2298 }
2299 
2300 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2301   VisitOMPClauseWithPreInit(C);
2302   Visitor->AddStmt(C->getCondition());
2303 }
2304 
2305 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2306   Visitor->AddStmt(C->getCondition());
2307 }
2308 
2309 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2310   VisitOMPClauseWithPreInit(C);
2311   Visitor->AddStmt(C->getNumThreads());
2312 }
2313 
2314 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2315   Visitor->AddStmt(C->getSafelen());
2316 }
2317 
2318 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2319   Visitor->AddStmt(C->getSimdlen());
2320 }
2321 
2322 void OMPClauseEnqueue::VisitOMPSizesClause(const OMPSizesClause *C) {
2323   for (auto E : C->getSizesRefs())
2324     Visitor->AddStmt(E);
2325 }
2326 
2327 void OMPClauseEnqueue::VisitOMPFullClause(const OMPFullClause *C) {}
2328 
2329 void OMPClauseEnqueue::VisitOMPPartialClause(const OMPPartialClause *C) {
2330   Visitor->AddStmt(C->getFactor());
2331 }
2332 
2333 void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2334   Visitor->AddStmt(C->getAllocator());
2335 }
2336 
2337 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2338   Visitor->AddStmt(C->getNumForLoops());
2339 }
2340 
2341 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) {}
2342 
2343 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) {}
2344 
2345 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2346   VisitOMPClauseWithPreInit(C);
2347   Visitor->AddStmt(C->getChunkSize());
2348 }
2349 
2350 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2351   Visitor->AddStmt(C->getNumForLoops());
2352 }
2353 
2354 void OMPClauseEnqueue::VisitOMPDetachClause(const OMPDetachClause *C) {
2355   Visitor->AddStmt(C->getEventHandler());
2356 }
2357 
2358 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2359 
2360 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2361 
2362 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2363 
2364 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2365 
2366 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2367 
2368 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2369 
2370 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2371 
2372 void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
2373 
2374 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2375 
2376 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
2377 
2378 void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {}
2379 
2380 void OMPClauseEnqueue::VisitOMPReleaseClause(const OMPReleaseClause *) {}
2381 
2382 void OMPClauseEnqueue::VisitOMPRelaxedClause(const OMPRelaxedClause *) {}
2383 
2384 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2385 
2386 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2387 
2388 void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2389 
2390 void OMPClauseEnqueue::VisitOMPInitClause(const OMPInitClause *C) {
2391   VisitOMPClauseList(C);
2392 }
2393 
2394 void OMPClauseEnqueue::VisitOMPUseClause(const OMPUseClause *C) {
2395   Visitor->AddStmt(C->getInteropVar());
2396 }
2397 
2398 void OMPClauseEnqueue::VisitOMPDestroyClause(const OMPDestroyClause *C) {
2399   if (C->getInteropVar())
2400     Visitor->AddStmt(C->getInteropVar());
2401 }
2402 
2403 void OMPClauseEnqueue::VisitOMPNovariantsClause(const OMPNovariantsClause *C) {
2404   Visitor->AddStmt(C->getCondition());
2405 }
2406 
2407 void OMPClauseEnqueue::VisitOMPNocontextClause(const OMPNocontextClause *C) {
2408   Visitor->AddStmt(C->getCondition());
2409 }
2410 
2411 void OMPClauseEnqueue::VisitOMPFilterClause(const OMPFilterClause *C) {
2412   VisitOMPClauseWithPreInit(C);
2413   Visitor->AddStmt(C->getThreadID());
2414 }
2415 
2416 void OMPClauseEnqueue::VisitOMPAlignClause(const OMPAlignClause *C) {
2417   Visitor->AddStmt(C->getAlignment());
2418 }
2419 
2420 void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2421     const OMPUnifiedAddressClause *) {}
2422 
2423 void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2424     const OMPUnifiedSharedMemoryClause *) {}
2425 
2426 void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2427     const OMPReverseOffloadClause *) {}
2428 
2429 void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2430     const OMPDynamicAllocatorsClause *) {}
2431 
2432 void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2433     const OMPAtomicDefaultMemOrderClause *) {}
2434 
2435 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2436   Visitor->AddStmt(C->getDevice());
2437 }
2438 
2439 void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2440   VisitOMPClauseWithPreInit(C);
2441   Visitor->AddStmt(C->getNumTeams());
2442 }
2443 
2444 void OMPClauseEnqueue::VisitOMPThreadLimitClause(
2445     const OMPThreadLimitClause *C) {
2446   VisitOMPClauseWithPreInit(C);
2447   Visitor->AddStmt(C->getThreadLimit());
2448 }
2449 
2450 void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2451   Visitor->AddStmt(C->getPriority());
2452 }
2453 
2454 void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2455   Visitor->AddStmt(C->getGrainsize());
2456 }
2457 
2458 void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2459   Visitor->AddStmt(C->getNumTasks());
2460 }
2461 
2462 void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2463   Visitor->AddStmt(C->getHint());
2464 }
2465 
2466 template <typename T> void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2467   for (const auto *I : Node->varlists()) {
2468     Visitor->AddStmt(I);
2469   }
2470 }
2471 
2472 void OMPClauseEnqueue::VisitOMPInclusiveClause(const OMPInclusiveClause *C) {
2473   VisitOMPClauseList(C);
2474 }
2475 void OMPClauseEnqueue::VisitOMPExclusiveClause(const OMPExclusiveClause *C) {
2476   VisitOMPClauseList(C);
2477 }
2478 void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2479   VisitOMPClauseList(C);
2480   Visitor->AddStmt(C->getAllocator());
2481 }
2482 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2483   VisitOMPClauseList(C);
2484   for (const auto *E : C->private_copies()) {
2485     Visitor->AddStmt(E);
2486   }
2487 }
2488 void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2489     const OMPFirstprivateClause *C) {
2490   VisitOMPClauseList(C);
2491   VisitOMPClauseWithPreInit(C);
2492   for (const auto *E : C->private_copies()) {
2493     Visitor->AddStmt(E);
2494   }
2495   for (const auto *E : C->inits()) {
2496     Visitor->AddStmt(E);
2497   }
2498 }
2499 void OMPClauseEnqueue::VisitOMPLastprivateClause(
2500     const OMPLastprivateClause *C) {
2501   VisitOMPClauseList(C);
2502   VisitOMPClauseWithPostUpdate(C);
2503   for (auto *E : C->private_copies()) {
2504     Visitor->AddStmt(E);
2505   }
2506   for (auto *E : C->source_exprs()) {
2507     Visitor->AddStmt(E);
2508   }
2509   for (auto *E : C->destination_exprs()) {
2510     Visitor->AddStmt(E);
2511   }
2512   for (auto *E : C->assignment_ops()) {
2513     Visitor->AddStmt(E);
2514   }
2515 }
2516 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2517   VisitOMPClauseList(C);
2518 }
2519 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2520   VisitOMPClauseList(C);
2521   VisitOMPClauseWithPostUpdate(C);
2522   for (auto *E : C->privates()) {
2523     Visitor->AddStmt(E);
2524   }
2525   for (auto *E : C->lhs_exprs()) {
2526     Visitor->AddStmt(E);
2527   }
2528   for (auto *E : C->rhs_exprs()) {
2529     Visitor->AddStmt(E);
2530   }
2531   for (auto *E : C->reduction_ops()) {
2532     Visitor->AddStmt(E);
2533   }
2534   if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
2535     for (auto *E : C->copy_ops()) {
2536       Visitor->AddStmt(E);
2537     }
2538     for (auto *E : C->copy_array_temps()) {
2539       Visitor->AddStmt(E);
2540     }
2541     for (auto *E : C->copy_array_elems()) {
2542       Visitor->AddStmt(E);
2543     }
2544   }
2545 }
2546 void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2547     const OMPTaskReductionClause *C) {
2548   VisitOMPClauseList(C);
2549   VisitOMPClauseWithPostUpdate(C);
2550   for (auto *E : C->privates()) {
2551     Visitor->AddStmt(E);
2552   }
2553   for (auto *E : C->lhs_exprs()) {
2554     Visitor->AddStmt(E);
2555   }
2556   for (auto *E : C->rhs_exprs()) {
2557     Visitor->AddStmt(E);
2558   }
2559   for (auto *E : C->reduction_ops()) {
2560     Visitor->AddStmt(E);
2561   }
2562 }
2563 void OMPClauseEnqueue::VisitOMPInReductionClause(
2564     const OMPInReductionClause *C) {
2565   VisitOMPClauseList(C);
2566   VisitOMPClauseWithPostUpdate(C);
2567   for (auto *E : C->privates()) {
2568     Visitor->AddStmt(E);
2569   }
2570   for (auto *E : C->lhs_exprs()) {
2571     Visitor->AddStmt(E);
2572   }
2573   for (auto *E : C->rhs_exprs()) {
2574     Visitor->AddStmt(E);
2575   }
2576   for (auto *E : C->reduction_ops()) {
2577     Visitor->AddStmt(E);
2578   }
2579   for (auto *E : C->taskgroup_descriptors())
2580     Visitor->AddStmt(E);
2581 }
2582 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2583   VisitOMPClauseList(C);
2584   VisitOMPClauseWithPostUpdate(C);
2585   for (const auto *E : C->privates()) {
2586     Visitor->AddStmt(E);
2587   }
2588   for (const auto *E : C->inits()) {
2589     Visitor->AddStmt(E);
2590   }
2591   for (const auto *E : C->updates()) {
2592     Visitor->AddStmt(E);
2593   }
2594   for (const auto *E : C->finals()) {
2595     Visitor->AddStmt(E);
2596   }
2597   Visitor->AddStmt(C->getStep());
2598   Visitor->AddStmt(C->getCalcStep());
2599 }
2600 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2601   VisitOMPClauseList(C);
2602   Visitor->AddStmt(C->getAlignment());
2603 }
2604 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2605   VisitOMPClauseList(C);
2606   for (auto *E : C->source_exprs()) {
2607     Visitor->AddStmt(E);
2608   }
2609   for (auto *E : C->destination_exprs()) {
2610     Visitor->AddStmt(E);
2611   }
2612   for (auto *E : C->assignment_ops()) {
2613     Visitor->AddStmt(E);
2614   }
2615 }
2616 void OMPClauseEnqueue::VisitOMPCopyprivateClause(
2617     const OMPCopyprivateClause *C) {
2618   VisitOMPClauseList(C);
2619   for (auto *E : C->source_exprs()) {
2620     Visitor->AddStmt(E);
2621   }
2622   for (auto *E : C->destination_exprs()) {
2623     Visitor->AddStmt(E);
2624   }
2625   for (auto *E : C->assignment_ops()) {
2626     Visitor->AddStmt(E);
2627   }
2628 }
2629 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2630   VisitOMPClauseList(C);
2631 }
2632 void OMPClauseEnqueue::VisitOMPDepobjClause(const OMPDepobjClause *C) {
2633   Visitor->AddStmt(C->getDepobj());
2634 }
2635 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2636   VisitOMPClauseList(C);
2637 }
2638 void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2639   VisitOMPClauseList(C);
2640 }
2641 void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2642     const OMPDistScheduleClause *C) {
2643   VisitOMPClauseWithPreInit(C);
2644   Visitor->AddStmt(C->getChunkSize());
2645 }
2646 void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2647     const OMPDefaultmapClause * /*C*/) {}
2648 void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2649   VisitOMPClauseList(C);
2650 }
2651 void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2652   VisitOMPClauseList(C);
2653 }
2654 void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(
2655     const OMPUseDevicePtrClause *C) {
2656   VisitOMPClauseList(C);
2657 }
2658 void OMPClauseEnqueue::VisitOMPUseDeviceAddrClause(
2659     const OMPUseDeviceAddrClause *C) {
2660   VisitOMPClauseList(C);
2661 }
2662 void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(
2663     const OMPIsDevicePtrClause *C) {
2664   VisitOMPClauseList(C);
2665 }
2666 void OMPClauseEnqueue::VisitOMPHasDeviceAddrClause(
2667     const OMPHasDeviceAddrClause *C) {
2668   VisitOMPClauseList(C);
2669 }
2670 void OMPClauseEnqueue::VisitOMPNontemporalClause(
2671     const OMPNontemporalClause *C) {
2672   VisitOMPClauseList(C);
2673   for (const auto *E : C->private_refs())
2674     Visitor->AddStmt(E);
2675 }
2676 void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
2677 void OMPClauseEnqueue::VisitOMPUsesAllocatorsClause(
2678     const OMPUsesAllocatorsClause *C) {
2679   for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
2680     const OMPUsesAllocatorsClause::Data &D = C->getAllocatorData(I);
2681     Visitor->AddStmt(D.Allocator);
2682     Visitor->AddStmt(D.AllocatorTraits);
2683   }
2684 }
2685 void OMPClauseEnqueue::VisitOMPAffinityClause(const OMPAffinityClause *C) {
2686   Visitor->AddStmt(C->getModifier());
2687   for (const Expr *E : C->varlists())
2688     Visitor->AddStmt(E);
2689 }
2690 void OMPClauseEnqueue::VisitOMPBindClause(const OMPBindClause *C) {}
2691 
2692 } // namespace
2693 
2694 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2695   unsigned size = WL.size();
2696   OMPClauseEnqueue Visitor(this);
2697   Visitor.Visit(S);
2698   if (size == WL.size())
2699     return;
2700   // Now reverse the entries we just added.  This will match the DFS
2701   // ordering performed by the worklist.
2702   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2703   std::reverse(I, E);
2704 }
2705 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2706   WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2707 }
2708 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2709   AddDecl(B->getBlockDecl());
2710 }
2711 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2712   EnqueueChildren(E);
2713   AddTypeLoc(E->getTypeSourceInfo());
2714 }
2715 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2716   for (auto &I : llvm::reverse(S->body()))
2717     AddStmt(I);
2718 }
2719 void EnqueueVisitor::VisitMSDependentExistsStmt(
2720     const MSDependentExistsStmt *S) {
2721   AddStmt(S->getSubStmt());
2722   AddDeclarationNameInfo(S);
2723   if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2724     AddNestedNameSpecifierLoc(QualifierLoc);
2725 }
2726 
2727 void EnqueueVisitor::VisitCXXDependentScopeMemberExpr(
2728     const CXXDependentScopeMemberExpr *E) {
2729   if (E->hasExplicitTemplateArgs())
2730     AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2731   AddDeclarationNameInfo(E);
2732   if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2733     AddNestedNameSpecifierLoc(QualifierLoc);
2734   if (!E->isImplicitAccess())
2735     AddStmt(E->getBase());
2736 }
2737 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2738   // Enqueue the initializer , if any.
2739   AddStmt(E->getInitializer());
2740   // Enqueue the array size, if any.
2741   AddStmt(E->getArraySize().value_or(nullptr));
2742   // Enqueue the allocated type.
2743   AddTypeLoc(E->getAllocatedTypeSourceInfo());
2744   // Enqueue the placement arguments.
2745   for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2746     AddStmt(E->getPlacementArg(I - 1));
2747 }
2748 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2749   for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2750     AddStmt(CE->getArg(I - 1));
2751   AddStmt(CE->getCallee());
2752   AddStmt(CE->getArg(0));
2753 }
2754 void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2755     const CXXPseudoDestructorExpr *E) {
2756   // Visit the name of the type being destroyed.
2757   AddTypeLoc(E->getDestroyedTypeInfo());
2758   // Visit the scope type that looks disturbingly like the nested-name-specifier
2759   // but isn't.
2760   AddTypeLoc(E->getScopeTypeInfo());
2761   // Visit the nested-name-specifier.
2762   if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2763     AddNestedNameSpecifierLoc(QualifierLoc);
2764   // Visit base expression.
2765   AddStmt(E->getBase());
2766 }
2767 void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2768     const CXXScalarValueInitExpr *E) {
2769   AddTypeLoc(E->getTypeSourceInfo());
2770 }
2771 void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2772     const CXXTemporaryObjectExpr *E) {
2773   EnqueueChildren(E);
2774   AddTypeLoc(E->getTypeSourceInfo());
2775 }
2776 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2777   EnqueueChildren(E);
2778   if (E->isTypeOperand())
2779     AddTypeLoc(E->getTypeOperandSourceInfo());
2780 }
2781 
2782 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2783     const CXXUnresolvedConstructExpr *E) {
2784   EnqueueChildren(E);
2785   AddTypeLoc(E->getTypeSourceInfo());
2786 }
2787 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2788   EnqueueChildren(E);
2789   if (E->isTypeOperand())
2790     AddTypeLoc(E->getTypeOperandSourceInfo());
2791 }
2792 
2793 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2794   EnqueueChildren(S);
2795   AddDecl(S->getExceptionDecl());
2796 }
2797 
2798 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2799   AddStmt(S->getBody());
2800   AddStmt(S->getRangeInit());
2801   AddDecl(S->getLoopVariable());
2802 }
2803 
2804 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2805   if (DR->hasExplicitTemplateArgs())
2806     AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
2807   WL.push_back(DeclRefExprParts(DR, Parent));
2808 }
2809 void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2810     const DependentScopeDeclRefExpr *E) {
2811   if (E->hasExplicitTemplateArgs())
2812     AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2813   AddDeclarationNameInfo(E);
2814   AddNestedNameSpecifierLoc(E->getQualifierLoc());
2815 }
2816 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2817   unsigned size = WL.size();
2818   bool isFirst = true;
2819   for (const auto *D : S->decls()) {
2820     AddDecl(D, isFirst);
2821     isFirst = false;
2822   }
2823   if (size == WL.size())
2824     return;
2825   // Now reverse the entries we just added.  This will match the DFS
2826   // ordering performed by the worklist.
2827   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2828   std::reverse(I, E);
2829 }
2830 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2831   AddStmt(E->getInit());
2832   for (const DesignatedInitExpr::Designator &D :
2833        llvm::reverse(E->designators())) {
2834     if (D.isFieldDesignator()) {
2835       if (FieldDecl *Field = D.getField())
2836         AddMemberRef(Field, D.getFieldLoc());
2837       continue;
2838     }
2839     if (D.isArrayDesignator()) {
2840       AddStmt(E->getArrayIndex(D));
2841       continue;
2842     }
2843     assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2844     AddStmt(E->getArrayRangeEnd(D));
2845     AddStmt(E->getArrayRangeStart(D));
2846   }
2847 }
2848 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2849   EnqueueChildren(E);
2850   AddTypeLoc(E->getTypeInfoAsWritten());
2851 }
2852 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2853   AddStmt(FS->getBody());
2854   AddStmt(FS->getInc());
2855   AddStmt(FS->getCond());
2856   AddDecl(FS->getConditionVariable());
2857   AddStmt(FS->getInit());
2858 }
2859 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2860   WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2861 }
2862 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2863   AddStmt(If->getElse());
2864   AddStmt(If->getThen());
2865   AddStmt(If->getCond());
2866   AddStmt(If->getInit());
2867   AddDecl(If->getConditionVariable());
2868 }
2869 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2870   // We care about the syntactic form of the initializer list, only.
2871   if (InitListExpr *Syntactic = IE->getSyntacticForm())
2872     IE = Syntactic;
2873   EnqueueChildren(IE);
2874 }
2875 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2876   WL.push_back(MemberExprParts(M, Parent));
2877 
2878   // If the base of the member access expression is an implicit 'this', don't
2879   // visit it.
2880   // FIXME: If we ever want to show these implicit accesses, this will be
2881   // unfortunate. However, clang_getCursor() relies on this behavior.
2882   if (M->isImplicitAccess())
2883     return;
2884 
2885   // Ignore base anonymous struct/union fields, otherwise they will shadow the
2886   // real field that we are interested in.
2887   if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2888     if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2889       if (FD->isAnonymousStructOrUnion()) {
2890         AddStmt(SubME->getBase());
2891         return;
2892       }
2893     }
2894   }
2895 
2896   AddStmt(M->getBase());
2897 }
2898 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2899   AddTypeLoc(E->getEncodedTypeSourceInfo());
2900 }
2901 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2902   EnqueueChildren(M);
2903   AddTypeLoc(M->getClassReceiverTypeInfo());
2904 }
2905 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2906   // Visit the components of the offsetof expression.
2907   for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2908     const OffsetOfNode &Node = E->getComponent(I - 1);
2909     switch (Node.getKind()) {
2910     case OffsetOfNode::Array:
2911       AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2912       break;
2913     case OffsetOfNode::Field:
2914       AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2915       break;
2916     case OffsetOfNode::Identifier:
2917     case OffsetOfNode::Base:
2918       continue;
2919     }
2920   }
2921   // Visit the type into which we're computing the offset.
2922   AddTypeLoc(E->getTypeSourceInfo());
2923 }
2924 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2925   if (E->hasExplicitTemplateArgs())
2926     AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2927   WL.push_back(OverloadExprParts(E, Parent));
2928 }
2929 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2930     const UnaryExprOrTypeTraitExpr *E) {
2931   EnqueueChildren(E);
2932   if (E->isArgumentType())
2933     AddTypeLoc(E->getArgumentTypeInfo());
2934 }
2935 void EnqueueVisitor::VisitStmt(const Stmt *S) { EnqueueChildren(S); }
2936 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2937   AddStmt(S->getBody());
2938   AddStmt(S->getCond());
2939   AddDecl(S->getConditionVariable());
2940 }
2941 
2942 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2943   AddStmt(W->getBody());
2944   AddStmt(W->getCond());
2945   AddDecl(W->getConditionVariable());
2946 }
2947 
2948 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2949   for (unsigned I = E->getNumArgs(); I > 0; --I)
2950     AddTypeLoc(E->getArg(I - 1));
2951 }
2952 
2953 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2954   AddTypeLoc(E->getQueriedTypeSourceInfo());
2955 }
2956 
2957 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2958   EnqueueChildren(E);
2959 }
2960 
2961 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2962   VisitOverloadExpr(U);
2963   if (!U->isImplicitAccess())
2964     AddStmt(U->getBase());
2965 }
2966 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2967   AddStmt(E->getSubExpr());
2968   AddTypeLoc(E->getWrittenTypeInfo());
2969 }
2970 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2971   WL.push_back(SizeOfPackExprParts(E, Parent));
2972 }
2973 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2974   // If the opaque value has a source expression, just transparently
2975   // visit that.  This is useful for (e.g.) pseudo-object expressions.
2976   if (Expr *SourceExpr = E->getSourceExpr())
2977     return Visit(SourceExpr);
2978 }
2979 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2980   AddStmt(E->getBody());
2981   WL.push_back(LambdaExprParts(E, Parent));
2982 }
2983 void EnqueueVisitor::VisitConceptSpecializationExpr(
2984     const ConceptSpecializationExpr *E) {
2985   WL.push_back(ConceptSpecializationExprVisit(E, Parent));
2986 }
2987 void EnqueueVisitor::VisitRequiresExpr(const RequiresExpr *E) {
2988   WL.push_back(RequiresExprVisit(E, Parent));
2989   for (ParmVarDecl *VD : E->getLocalParameters())
2990     AddDecl(VD);
2991 }
2992 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2993   // Treat the expression like its syntactic form.
2994   Visit(E->getSyntacticForm());
2995 }
2996 
2997 void EnqueueVisitor::VisitOMPExecutableDirective(
2998     const OMPExecutableDirective *D) {
2999   EnqueueChildren(D);
3000   for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
3001                                        E = D->clauses().end();
3002        I != E; ++I)
3003     EnqueueChildren(*I);
3004 }
3005 
3006 void EnqueueVisitor::VisitOMPLoopBasedDirective(
3007     const OMPLoopBasedDirective *D) {
3008   VisitOMPExecutableDirective(D);
3009 }
3010 
3011 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
3012   VisitOMPLoopBasedDirective(D);
3013 }
3014 
3015 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
3016   VisitOMPExecutableDirective(D);
3017 }
3018 
3019 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
3020   VisitOMPLoopDirective(D);
3021 }
3022 
3023 void EnqueueVisitor::VisitOMPLoopTransformationDirective(
3024     const OMPLoopTransformationDirective *D) {
3025   VisitOMPLoopBasedDirective(D);
3026 }
3027 
3028 void EnqueueVisitor::VisitOMPTileDirective(const OMPTileDirective *D) {
3029   VisitOMPLoopTransformationDirective(D);
3030 }
3031 
3032 void EnqueueVisitor::VisitOMPUnrollDirective(const OMPUnrollDirective *D) {
3033   VisitOMPLoopTransformationDirective(D);
3034 }
3035 
3036 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
3037   VisitOMPLoopDirective(D);
3038 }
3039 
3040 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
3041   VisitOMPLoopDirective(D);
3042 }
3043 
3044 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
3045   VisitOMPExecutableDirective(D);
3046 }
3047 
3048 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
3049   VisitOMPExecutableDirective(D);
3050 }
3051 
3052 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
3053   VisitOMPExecutableDirective(D);
3054 }
3055 
3056 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
3057   VisitOMPExecutableDirective(D);
3058 }
3059 
3060 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
3061   VisitOMPExecutableDirective(D);
3062   AddDeclarationNameInfo(D);
3063 }
3064 
3065 void EnqueueVisitor::VisitOMPParallelForDirective(
3066     const OMPParallelForDirective *D) {
3067   VisitOMPLoopDirective(D);
3068 }
3069 
3070 void EnqueueVisitor::VisitOMPParallelForSimdDirective(
3071     const OMPParallelForSimdDirective *D) {
3072   VisitOMPLoopDirective(D);
3073 }
3074 
3075 void EnqueueVisitor::VisitOMPParallelMasterDirective(
3076     const OMPParallelMasterDirective *D) {
3077   VisitOMPExecutableDirective(D);
3078 }
3079 
3080 void EnqueueVisitor::VisitOMPParallelMaskedDirective(
3081     const OMPParallelMaskedDirective *D) {
3082   VisitOMPExecutableDirective(D);
3083 }
3084 
3085 void EnqueueVisitor::VisitOMPParallelSectionsDirective(
3086     const OMPParallelSectionsDirective *D) {
3087   VisitOMPExecutableDirective(D);
3088 }
3089 
3090 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
3091   VisitOMPExecutableDirective(D);
3092 }
3093 
3094 void EnqueueVisitor::VisitOMPTaskyieldDirective(
3095     const OMPTaskyieldDirective *D) {
3096   VisitOMPExecutableDirective(D);
3097 }
3098 
3099 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
3100   VisitOMPExecutableDirective(D);
3101 }
3102 
3103 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
3104   VisitOMPExecutableDirective(D);
3105 }
3106 
3107 void EnqueueVisitor::VisitOMPTaskgroupDirective(
3108     const OMPTaskgroupDirective *D) {
3109   VisitOMPExecutableDirective(D);
3110   if (const Expr *E = D->getReductionRef())
3111     VisitStmt(E);
3112 }
3113 
3114 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
3115   VisitOMPExecutableDirective(D);
3116 }
3117 
3118 void EnqueueVisitor::VisitOMPDepobjDirective(const OMPDepobjDirective *D) {
3119   VisitOMPExecutableDirective(D);
3120 }
3121 
3122 void EnqueueVisitor::VisitOMPScanDirective(const OMPScanDirective *D) {
3123   VisitOMPExecutableDirective(D);
3124 }
3125 
3126 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
3127   VisitOMPExecutableDirective(D);
3128 }
3129 
3130 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
3131   VisitOMPExecutableDirective(D);
3132 }
3133 
3134 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
3135   VisitOMPExecutableDirective(D);
3136 }
3137 
3138 void EnqueueVisitor::VisitOMPTargetDataDirective(
3139     const OMPTargetDataDirective *D) {
3140   VisitOMPExecutableDirective(D);
3141 }
3142 
3143 void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
3144     const OMPTargetEnterDataDirective *D) {
3145   VisitOMPExecutableDirective(D);
3146 }
3147 
3148 void EnqueueVisitor::VisitOMPTargetExitDataDirective(
3149     const OMPTargetExitDataDirective *D) {
3150   VisitOMPExecutableDirective(D);
3151 }
3152 
3153 void EnqueueVisitor::VisitOMPTargetParallelDirective(
3154     const OMPTargetParallelDirective *D) {
3155   VisitOMPExecutableDirective(D);
3156 }
3157 
3158 void EnqueueVisitor::VisitOMPTargetParallelForDirective(
3159     const OMPTargetParallelForDirective *D) {
3160   VisitOMPLoopDirective(D);
3161 }
3162 
3163 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
3164   VisitOMPExecutableDirective(D);
3165 }
3166 
3167 void EnqueueVisitor::VisitOMPCancellationPointDirective(
3168     const OMPCancellationPointDirective *D) {
3169   VisitOMPExecutableDirective(D);
3170 }
3171 
3172 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
3173   VisitOMPExecutableDirective(D);
3174 }
3175 
3176 void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
3177   VisitOMPLoopDirective(D);
3178 }
3179 
3180 void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
3181     const OMPTaskLoopSimdDirective *D) {
3182   VisitOMPLoopDirective(D);
3183 }
3184 
3185 void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
3186     const OMPMasterTaskLoopDirective *D) {
3187   VisitOMPLoopDirective(D);
3188 }
3189 
3190 void EnqueueVisitor::VisitOMPMaskedTaskLoopDirective(
3191     const OMPMaskedTaskLoopDirective *D) {
3192   VisitOMPLoopDirective(D);
3193 }
3194 
3195 void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
3196     const OMPMasterTaskLoopSimdDirective *D) {
3197   VisitOMPLoopDirective(D);
3198 }
3199 
3200 void EnqueueVisitor::VisitOMPMaskedTaskLoopSimdDirective(
3201     const OMPMaskedTaskLoopSimdDirective *D) {
3202   VisitOMPLoopDirective(D);
3203 }
3204 
3205 void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
3206     const OMPParallelMasterTaskLoopDirective *D) {
3207   VisitOMPLoopDirective(D);
3208 }
3209 
3210 void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
3211     const OMPParallelMasterTaskLoopSimdDirective *D) {
3212   VisitOMPLoopDirective(D);
3213 }
3214 
3215 void EnqueueVisitor::VisitOMPDistributeDirective(
3216     const OMPDistributeDirective *D) {
3217   VisitOMPLoopDirective(D);
3218 }
3219 
3220 void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
3221     const OMPDistributeParallelForDirective *D) {
3222   VisitOMPLoopDirective(D);
3223 }
3224 
3225 void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
3226     const OMPDistributeParallelForSimdDirective *D) {
3227   VisitOMPLoopDirective(D);
3228 }
3229 
3230 void EnqueueVisitor::VisitOMPDistributeSimdDirective(
3231     const OMPDistributeSimdDirective *D) {
3232   VisitOMPLoopDirective(D);
3233 }
3234 
3235 void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
3236     const OMPTargetParallelForSimdDirective *D) {
3237   VisitOMPLoopDirective(D);
3238 }
3239 
3240 void EnqueueVisitor::VisitOMPTargetSimdDirective(
3241     const OMPTargetSimdDirective *D) {
3242   VisitOMPLoopDirective(D);
3243 }
3244 
3245 void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
3246     const OMPTeamsDistributeDirective *D) {
3247   VisitOMPLoopDirective(D);
3248 }
3249 
3250 void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
3251     const OMPTeamsDistributeSimdDirective *D) {
3252   VisitOMPLoopDirective(D);
3253 }
3254 
3255 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
3256     const OMPTeamsDistributeParallelForSimdDirective *D) {
3257   VisitOMPLoopDirective(D);
3258 }
3259 
3260 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
3261     const OMPTeamsDistributeParallelForDirective *D) {
3262   VisitOMPLoopDirective(D);
3263 }
3264 
3265 void EnqueueVisitor::VisitOMPTargetTeamsDirective(
3266     const OMPTargetTeamsDirective *D) {
3267   VisitOMPExecutableDirective(D);
3268 }
3269 
3270 void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
3271     const OMPTargetTeamsDistributeDirective *D) {
3272   VisitOMPLoopDirective(D);
3273 }
3274 
3275 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3276     const OMPTargetTeamsDistributeParallelForDirective *D) {
3277   VisitOMPLoopDirective(D);
3278 }
3279 
3280 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3281     const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3282   VisitOMPLoopDirective(D);
3283 }
3284 
3285 void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3286     const OMPTargetTeamsDistributeSimdDirective *D) {
3287   VisitOMPLoopDirective(D);
3288 }
3289 
3290 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
3291   EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU, RegionOfInterest))
3292       .Visit(S);
3293 }
3294 
3295 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3296   if (RegionOfInterest.isValid()) {
3297     SourceRange Range = getRawCursorExtent(C);
3298     if (Range.isInvalid() || CompareRegionOfInterest(Range))
3299       return false;
3300   }
3301   return true;
3302 }
3303 
3304 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3305   while (!WL.empty()) {
3306     // Dequeue the worklist item.
3307     VisitorJob LI = WL.pop_back_val();
3308 
3309     // Set the Parent field, then back to its old value once we're done.
3310     SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3311 
3312     switch (LI.getKind()) {
3313     case VisitorJob::DeclVisitKind: {
3314       const Decl *D = cast<DeclVisit>(&LI)->get();
3315       if (!D)
3316         continue;
3317 
3318       // For now, perform default visitation for Decls.
3319       if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3320                              cast<DeclVisit>(&LI)->isFirst())))
3321         return true;
3322 
3323       continue;
3324     }
3325     case VisitorJob::ExplicitTemplateArgsVisitKind: {
3326       for (const TemplateArgumentLoc &Arg :
3327            *cast<ExplicitTemplateArgsVisit>(&LI)) {
3328         if (VisitTemplateArgumentLoc(Arg))
3329           return true;
3330       }
3331       continue;
3332     }
3333     case VisitorJob::TypeLocVisitKind: {
3334       // Perform default visitation for TypeLocs.
3335       if (Visit(cast<TypeLocVisit>(&LI)->get()))
3336         return true;
3337       continue;
3338     }
3339     case VisitorJob::LabelRefVisitKind: {
3340       const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
3341       if (LabelStmt *stmt = LS->getStmt()) {
3342         if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3343                                      TU))) {
3344           return true;
3345         }
3346       }
3347       continue;
3348     }
3349 
3350     case VisitorJob::NestedNameSpecifierLocVisitKind: {
3351       NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3352       if (VisitNestedNameSpecifierLoc(V->get()))
3353         return true;
3354       continue;
3355     }
3356 
3357     case VisitorJob::DeclarationNameInfoVisitKind: {
3358       if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)->get()))
3359         return true;
3360       continue;
3361     }
3362     case VisitorJob::MemberRefVisitKind: {
3363       MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3364       if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3365         return true;
3366       continue;
3367     }
3368     case VisitorJob::StmtVisitKind: {
3369       const Stmt *S = cast<StmtVisit>(&LI)->get();
3370       if (!S)
3371         continue;
3372 
3373       // Update the current cursor.
3374       CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3375       if (!IsInRegionOfInterest(Cursor))
3376         continue;
3377       switch (Visitor(Cursor, Parent, ClientData)) {
3378       case CXChildVisit_Break:
3379         return true;
3380       case CXChildVisit_Continue:
3381         break;
3382       case CXChildVisit_Recurse:
3383         if (PostChildrenVisitor)
3384           WL.push_back(PostChildrenVisit(nullptr, Cursor));
3385         EnqueueWorkList(WL, S);
3386         break;
3387       }
3388       continue;
3389     }
3390     case VisitorJob::MemberExprPartsKind: {
3391       // Handle the other pieces in the MemberExpr besides the base.
3392       const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
3393 
3394       // Visit the nested-name-specifier
3395       if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3396         if (VisitNestedNameSpecifierLoc(QualifierLoc))
3397           return true;
3398 
3399       // Visit the declaration name.
3400       if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3401         return true;
3402 
3403       // Visit the explicitly-specified template arguments, if any.
3404       if (M->hasExplicitTemplateArgs()) {
3405         for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3406                                        *ArgEnd = Arg + M->getNumTemplateArgs();
3407              Arg != ArgEnd; ++Arg) {
3408           if (VisitTemplateArgumentLoc(*Arg))
3409             return true;
3410         }
3411       }
3412       continue;
3413     }
3414     case VisitorJob::DeclRefExprPartsKind: {
3415       const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
3416       // Visit nested-name-specifier, if present.
3417       if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3418         if (VisitNestedNameSpecifierLoc(QualifierLoc))
3419           return true;
3420       // Visit declaration name.
3421       if (VisitDeclarationNameInfo(DR->getNameInfo()))
3422         return true;
3423       continue;
3424     }
3425     case VisitorJob::OverloadExprPartsKind: {
3426       const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
3427       // Visit the nested-name-specifier.
3428       if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3429         if (VisitNestedNameSpecifierLoc(QualifierLoc))
3430           return true;
3431       // Visit the declaration name.
3432       if (VisitDeclarationNameInfo(O->getNameInfo()))
3433         return true;
3434       // Visit the overloaded declaration reference.
3435       if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3436         return true;
3437       continue;
3438     }
3439     case VisitorJob::SizeOfPackExprPartsKind: {
3440       const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
3441       NamedDecl *Pack = E->getPack();
3442       if (isa<TemplateTypeParmDecl>(Pack)) {
3443         if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3444                                     E->getPackLoc(), TU)))
3445           return true;
3446 
3447         continue;
3448       }
3449 
3450       if (isa<TemplateTemplateParmDecl>(Pack)) {
3451         if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3452                                         E->getPackLoc(), TU)))
3453           return true;
3454 
3455         continue;
3456       }
3457 
3458       // Non-type template parameter packs and function parameter packs are
3459       // treated like DeclRefExpr cursors.
3460       continue;
3461     }
3462 
3463     case VisitorJob::LambdaExprPartsKind: {
3464       // Visit non-init captures.
3465       const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
3466       for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3467                                         CEnd = E->explicit_capture_end();
3468            C != CEnd; ++C) {
3469         if (!C->capturesVariable())
3470           continue;
3471 
3472         if (Visit(MakeCursorVariableRef(C->getCapturedVar(), C->getLocation(),
3473                                         TU)))
3474           return true;
3475       }
3476       // Visit init captures
3477       for (auto InitExpr : E->capture_inits()) {
3478         if (InitExpr && Visit(InitExpr))
3479           return true;
3480       }
3481 
3482       TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3483       // Visit parameters and return type, if present.
3484       if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3485         if (E->hasExplicitParameters()) {
3486           // Visit parameters.
3487           for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3488             if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
3489               return true;
3490         }
3491         if (E->hasExplicitResultType()) {
3492           // Visit result type.
3493           if (Visit(Proto.getReturnLoc()))
3494             return true;
3495         }
3496       }
3497       break;
3498     }
3499 
3500     case VisitorJob::ConceptSpecializationExprVisitKind: {
3501       const ConceptSpecializationExpr *E =
3502           cast<ConceptSpecializationExprVisit>(&LI)->get();
3503       if (NestedNameSpecifierLoc QualifierLoc =
3504               E->getNestedNameSpecifierLoc()) {
3505         if (VisitNestedNameSpecifierLoc(QualifierLoc))
3506           return true;
3507       }
3508 
3509       if (E->getNamedConcept() &&
3510           Visit(MakeCursorTemplateRef(E->getNamedConcept(),
3511                                       E->getConceptNameLoc(), TU)))
3512         return true;
3513 
3514       if (auto Args = E->getTemplateArgsAsWritten()) {
3515         for (const auto &Arg : Args->arguments()) {
3516           if (VisitTemplateArgumentLoc(Arg))
3517             return true;
3518         }
3519       }
3520       break;
3521     }
3522 
3523     case VisitorJob::RequiresExprVisitKind: {
3524       const RequiresExpr *E = cast<RequiresExprVisit>(&LI)->get();
3525       for (const concepts::Requirement *R : E->getRequirements())
3526         VisitConceptRequirement(*R);
3527       break;
3528     }
3529 
3530     case VisitorJob::PostChildrenVisitKind:
3531       if (PostChildrenVisitor(Parent, ClientData))
3532         return true;
3533       break;
3534     }
3535   }
3536   return false;
3537 }
3538 
3539 bool CursorVisitor::Visit(const Stmt *S) {
3540   VisitorWorkList *WL = nullptr;
3541   if (!WorkListFreeList.empty()) {
3542     WL = WorkListFreeList.back();
3543     WL->clear();
3544     WorkListFreeList.pop_back();
3545   } else {
3546     WL = new VisitorWorkList();
3547     WorkListCache.push_back(WL);
3548   }
3549   EnqueueWorkList(*WL, S);
3550   bool result = RunVisitorWorkList(*WL);
3551   WorkListFreeList.push_back(WL);
3552   return result;
3553 }
3554 
3555 namespace {
3556 typedef SmallVector<SourceRange, 4> RefNamePieces;
3557 RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3558                           const DeclarationNameInfo &NI, SourceRange QLoc,
3559                           const SourceRange *TemplateArgsLoc = nullptr) {
3560   const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3561   const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3562   const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3563 
3564   const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3565 
3566   RefNamePieces Pieces;
3567 
3568   if (WantQualifier && QLoc.isValid())
3569     Pieces.push_back(QLoc);
3570 
3571   if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3572     Pieces.push_back(NI.getLoc());
3573 
3574   if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3575     Pieces.push_back(*TemplateArgsLoc);
3576 
3577   if (Kind == DeclarationName::CXXOperatorName) {
3578     Pieces.push_back(NI.getInfo().getCXXOperatorNameBeginLoc());
3579     Pieces.push_back(NI.getInfo().getCXXOperatorNameEndLoc());
3580   }
3581 
3582   if (WantSinglePiece) {
3583     SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3584     Pieces.clear();
3585     Pieces.push_back(R);
3586   }
3587 
3588   return Pieces;
3589 }
3590 } // namespace
3591 
3592 //===----------------------------------------------------------------------===//
3593 // Misc. API hooks.
3594 //===----------------------------------------------------------------------===//
3595 
3596 namespace {
3597 struct RegisterFatalErrorHandler {
3598   RegisterFatalErrorHandler() {
3599     clang_install_aborting_llvm_fatal_error_handler();
3600   }
3601 };
3602 } // namespace
3603 
3604 static llvm::ManagedStatic<RegisterFatalErrorHandler>
3605     RegisterFatalErrorHandlerOnce;
3606 
3607 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3608                           int displayDiagnostics) {
3609   // We use crash recovery to make some of our APIs more reliable, implicitly
3610   // enable it.
3611   if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3612     llvm::CrashRecoveryContext::Enable();
3613 
3614   // Look through the managed static to trigger construction of the managed
3615   // static which registers our fatal error handler. This ensures it is only
3616   // registered once.
3617   (void)*RegisterFatalErrorHandlerOnce;
3618 
3619   // Initialize targets for clang module support.
3620   llvm::InitializeAllTargets();
3621   llvm::InitializeAllTargetMCs();
3622   llvm::InitializeAllAsmPrinters();
3623   llvm::InitializeAllAsmParsers();
3624 
3625   CIndexer *CIdxr = new CIndexer();
3626 
3627   if (excludeDeclarationsFromPCH)
3628     CIdxr->setOnlyLocalDecls();
3629   if (displayDiagnostics)
3630     CIdxr->setDisplayDiagnostics();
3631 
3632   if (getenv("LIBCLANG_BGPRIO_INDEX"))
3633     CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3634                                CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3635   if (getenv("LIBCLANG_BGPRIO_EDIT"))
3636     CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3637                                CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3638 
3639   return CIdxr;
3640 }
3641 
3642 void clang_disposeIndex(CXIndex CIdx) {
3643   if (CIdx)
3644     delete static_cast<CIndexer *>(CIdx);
3645 }
3646 
3647 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3648   if (CIdx)
3649     static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3650 }
3651 
3652 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3653   if (CIdx)
3654     return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3655   return 0;
3656 }
3657 
3658 void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3659                                                    const char *Path) {
3660   if (CIdx)
3661     static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3662 }
3663 
3664 void clang_toggleCrashRecovery(unsigned isEnabled) {
3665   if (isEnabled)
3666     llvm::CrashRecoveryContext::Enable();
3667   else
3668     llvm::CrashRecoveryContext::Disable();
3669 }
3670 
3671 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3672                                               const char *ast_filename) {
3673   CXTranslationUnit TU;
3674   enum CXErrorCode Result =
3675       clang_createTranslationUnit2(CIdx, ast_filename, &TU);
3676   (void)Result;
3677   assert((TU && Result == CXError_Success) ||
3678          (!TU && Result != CXError_Success));
3679   return TU;
3680 }
3681 
3682 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3683                                               const char *ast_filename,
3684                                               CXTranslationUnit *out_TU) {
3685   if (out_TU)
3686     *out_TU = nullptr;
3687 
3688   if (!CIdx || !ast_filename || !out_TU)
3689     return CXError_InvalidArguments;
3690 
3691   LOG_FUNC_SECTION { *Log << ast_filename; }
3692 
3693   CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3694   FileSystemOptions FileSystemOpts;
3695 
3696   IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3697       CompilerInstance::createDiagnostics(new DiagnosticOptions());
3698   std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
3699       ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3700       ASTUnit::LoadEverything, Diags, FileSystemOpts, /*UseDebugInfo=*/false,
3701       CXXIdx->getOnlyLocalDecls(), CaptureDiagsKind::All,
3702       /*AllowASTWithCompilerErrors=*/true,
3703       /*UserFilesAreVolatile=*/true);
3704   *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
3705   return *out_TU ? CXError_Success : CXError_Failure;
3706 }
3707 
3708 unsigned clang_defaultEditingTranslationUnitOptions() {
3709   return CXTranslationUnit_PrecompiledPreamble |
3710          CXTranslationUnit_CacheCompletionResults;
3711 }
3712 
3713 CXTranslationUnit clang_createTranslationUnitFromSourceFile(
3714     CXIndex CIdx, const char *source_filename, int num_command_line_args,
3715     const char *const *command_line_args, unsigned num_unsaved_files,
3716     struct CXUnsavedFile *unsaved_files) {
3717   unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3718   return clang_parseTranslationUnit(CIdx, source_filename, command_line_args,
3719                                     num_command_line_args, unsaved_files,
3720                                     num_unsaved_files, Options);
3721 }
3722 
3723 static CXErrorCode
3724 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3725                                 const char *const *command_line_args,
3726                                 int num_command_line_args,
3727                                 ArrayRef<CXUnsavedFile> unsaved_files,
3728                                 unsigned options, CXTranslationUnit *out_TU) {
3729   // Set up the initial return values.
3730   if (out_TU)
3731     *out_TU = nullptr;
3732 
3733   // Check arguments.
3734   if (!CIdx || !out_TU)
3735     return CXError_InvalidArguments;
3736 
3737   CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3738 
3739   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3740     setThreadBackgroundPriority();
3741 
3742   bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3743   bool CreatePreambleOnFirstParse =
3744       options & CXTranslationUnit_CreatePreambleOnFirstParse;
3745   // FIXME: Add a flag for modules.
3746   TranslationUnitKind TUKind = (options & (CXTranslationUnit_Incomplete |
3747                                            CXTranslationUnit_SingleFileParse))
3748                                    ? TU_Prefix
3749                                    : TU_Complete;
3750   bool CacheCodeCompletionResults =
3751       options & CXTranslationUnit_CacheCompletionResults;
3752   bool IncludeBriefCommentsInCodeCompletion =
3753       options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3754   bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3755   bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3756   bool RetainExcludedCB =
3757       options & CXTranslationUnit_RetainExcludedConditionalBlocks;
3758   SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3759   if (options & CXTranslationUnit_SkipFunctionBodies) {
3760     SkipFunctionBodies =
3761         (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3762             ? SkipFunctionBodiesScope::Preamble
3763             : SkipFunctionBodiesScope::PreambleAndMainFile;
3764   }
3765 
3766   // Configure the diagnostics.
3767   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
3768       CompilerInstance::createDiagnostics(new DiagnosticOptions));
3769 
3770   if (options & CXTranslationUnit_KeepGoing)
3771     Diags->setFatalsAsError(true);
3772 
3773   CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3774   if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3775     CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3776 
3777   // Recover resources if we crash before exiting this function.
3778   llvm::CrashRecoveryContextCleanupRegistrar<
3779       DiagnosticsEngine,
3780       llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
3781       DiagCleanup(Diags.get());
3782 
3783   std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3784       new std::vector<ASTUnit::RemappedFile>());
3785 
3786   // Recover resources if we crash before exiting this function.
3787   llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
3788       RemappedCleanup(RemappedFiles.get());
3789 
3790   for (auto &UF : unsaved_files) {
3791     std::unique_ptr<llvm::MemoryBuffer> MB =
3792         llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3793     RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3794   }
3795 
3796   std::unique_ptr<std::vector<const char *>> Args(
3797       new std::vector<const char *>());
3798 
3799   // Recover resources if we crash before exiting this method.
3800   llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char *>>
3801       ArgsCleanup(Args.get());
3802 
3803   // Since the Clang C library is primarily used by batch tools dealing with
3804   // (often very broken) source code, where spell-checking can have a
3805   // significant negative impact on performance (particularly when
3806   // precompiled headers are involved), we disable it by default.
3807   // Only do this if we haven't found a spell-checking-related argument.
3808   bool FoundSpellCheckingArgument = false;
3809   for (int I = 0; I != num_command_line_args; ++I) {
3810     if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3811         strcmp(command_line_args[I], "-fspell-checking") == 0) {
3812       FoundSpellCheckingArgument = true;
3813       break;
3814     }
3815   }
3816   Args->insert(Args->end(), command_line_args,
3817                command_line_args + num_command_line_args);
3818 
3819   if (!FoundSpellCheckingArgument)
3820     Args->insert(Args->begin() + 1, "-fno-spell-checking");
3821 
3822   // The 'source_filename' argument is optional.  If the caller does not
3823   // specify it then it is assumed that the source file is specified
3824   // in the actual argument list.
3825   // Put the source file after command_line_args otherwise if '-x' flag is
3826   // present it will be unused.
3827   if (source_filename)
3828     Args->push_back(source_filename);
3829 
3830   // Do we need the detailed preprocessing record?
3831   if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3832     Args->push_back("-Xclang");
3833     Args->push_back("-detailed-preprocessing-record");
3834   }
3835 
3836   // Suppress any editor placeholder diagnostics.
3837   Args->push_back("-fallow-editor-placeholders");
3838 
3839   unsigned NumErrors = Diags->getClient()->getNumErrors();
3840   std::unique_ptr<ASTUnit> ErrUnit;
3841   // Unless the user specified that they want the preamble on the first parse
3842   // set it up to be created on the first reparse. This makes the first parse
3843   // faster, trading for a slower (first) reparse.
3844   unsigned PrecompilePreambleAfterNParses =
3845       !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
3846 
3847   LibclangInvocationReporter InvocationReporter(
3848       *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
3849       options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3850       unsaved_files);
3851   std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3852       Args->data(), Args->data() + Args->size(),
3853       CXXIdx->getPCHContainerOperations(), Diags,
3854       CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3855       CaptureDiagnostics, *RemappedFiles.get(),
3856       /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3857       TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3858       /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
3859       /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
3860       CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3861       &ErrUnit));
3862 
3863   // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3864   if (!Unit && !ErrUnit)
3865     return CXError_ASTReadError;
3866 
3867   if (NumErrors != Diags->getClient()->getNumErrors()) {
3868     // Make sure to check that 'Unit' is non-NULL.
3869     if (CXXIdx->getDisplayDiagnostics())
3870       printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3871   }
3872 
3873   if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3874     return CXError_ASTReadError;
3875 
3876   *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
3877   if (CXTranslationUnitImpl *TU = *out_TU) {
3878     TU->ParsingOptions = options;
3879     TU->Arguments.reserve(Args->size());
3880     for (const char *Arg : *Args)
3881       TU->Arguments.push_back(Arg);
3882     return CXError_Success;
3883   }
3884   return CXError_Failure;
3885 }
3886 
3887 CXTranslationUnit
3888 clang_parseTranslationUnit(CXIndex CIdx, const char *source_filename,
3889                            const char *const *command_line_args,
3890                            int num_command_line_args,
3891                            struct CXUnsavedFile *unsaved_files,
3892                            unsigned num_unsaved_files, unsigned options) {
3893   CXTranslationUnit TU;
3894   enum CXErrorCode Result = clang_parseTranslationUnit2(
3895       CIdx, source_filename, command_line_args, num_command_line_args,
3896       unsaved_files, num_unsaved_files, options, &TU);
3897   (void)Result;
3898   assert((TU && Result == CXError_Success) ||
3899          (!TU && Result != CXError_Success));
3900   return TU;
3901 }
3902 
3903 enum CXErrorCode clang_parseTranslationUnit2(
3904     CXIndex CIdx, const char *source_filename,
3905     const char *const *command_line_args, int num_command_line_args,
3906     struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3907     unsigned options, CXTranslationUnit *out_TU) {
3908   noteBottomOfStack();
3909   SmallVector<const char *, 4> Args;
3910   Args.push_back("clang");
3911   Args.append(command_line_args, command_line_args + num_command_line_args);
3912   return clang_parseTranslationUnit2FullArgv(
3913       CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3914       num_unsaved_files, options, out_TU);
3915 }
3916 
3917 enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3918     CXIndex CIdx, const char *source_filename,
3919     const char *const *command_line_args, int num_command_line_args,
3920     struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3921     unsigned options, CXTranslationUnit *out_TU) {
3922   LOG_FUNC_SECTION {
3923     *Log << source_filename << ": ";
3924     for (int i = 0; i != num_command_line_args; ++i)
3925       *Log << command_line_args[i] << " ";
3926   }
3927 
3928   if (num_unsaved_files && !unsaved_files)
3929     return CXError_InvalidArguments;
3930 
3931   CXErrorCode result = CXError_Failure;
3932   auto ParseTranslationUnitImpl = [=, &result] {
3933     noteBottomOfStack();
3934     result = clang_parseTranslationUnit_Impl(
3935         CIdx, source_filename, command_line_args, num_command_line_args,
3936         llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3937   };
3938 
3939   llvm::CrashRecoveryContext CRC;
3940 
3941   if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3942     fprintf(stderr, "libclang: crash detected during parsing: {\n");
3943     fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
3944     fprintf(stderr, "  'command_line_args' : [");
3945     for (int i = 0; i != num_command_line_args; ++i) {
3946       if (i)
3947         fprintf(stderr, ", ");
3948       fprintf(stderr, "'%s'", command_line_args[i]);
3949     }
3950     fprintf(stderr, "],\n");
3951     fprintf(stderr, "  'unsaved_files' : [");
3952     for (unsigned i = 0; i != num_unsaved_files; ++i) {
3953       if (i)
3954         fprintf(stderr, ", ");
3955       fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3956               unsaved_files[i].Length);
3957     }
3958     fprintf(stderr, "],\n");
3959     fprintf(stderr, "  'options' : %d,\n", options);
3960     fprintf(stderr, "}\n");
3961 
3962     return CXError_Crashed;
3963   } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3964     if (CXTranslationUnit *TU = out_TU)
3965       PrintLibclangResourceUsage(*TU);
3966   }
3967 
3968   return result;
3969 }
3970 
3971 CXString clang_Type_getObjCEncoding(CXType CT) {
3972   CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3973   ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3974   std::string encoding;
3975   Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]), encoding);
3976 
3977   return cxstring::createDup(encoding);
3978 }
3979 
3980 static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3981   if (C.kind == CXCursor_MacroDefinition) {
3982     if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3983       return MDR->getName();
3984   } else if (C.kind == CXCursor_MacroExpansion) {
3985     MacroExpansionCursor ME = getCursorMacroExpansion(C);
3986     return ME.getName();
3987   }
3988   return nullptr;
3989 }
3990 
3991 unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3992   const IdentifierInfo *II = getMacroIdentifier(C);
3993   if (!II) {
3994     return false;
3995   }
3996   ASTUnit *ASTU = getCursorASTUnit(C);
3997   Preprocessor &PP = ASTU->getPreprocessor();
3998   if (const MacroInfo *MI = PP.getMacroInfo(II))
3999     return MI->isFunctionLike();
4000   return false;
4001 }
4002 
4003 unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
4004   const IdentifierInfo *II = getMacroIdentifier(C);
4005   if (!II) {
4006     return false;
4007   }
4008   ASTUnit *ASTU = getCursorASTUnit(C);
4009   Preprocessor &PP = ASTU->getPreprocessor();
4010   if (const MacroInfo *MI = PP.getMacroInfo(II))
4011     return MI->isBuiltinMacro();
4012   return false;
4013 }
4014 
4015 unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
4016   const Decl *D = getCursorDecl(C);
4017   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
4018   if (!FD) {
4019     return false;
4020   }
4021   return FD->isInlined();
4022 }
4023 
4024 static StringLiteral *getCFSTR_value(CallExpr *callExpr) {
4025   if (callExpr->getNumArgs() != 1) {
4026     return nullptr;
4027   }
4028 
4029   StringLiteral *S = nullptr;
4030   auto *arg = callExpr->getArg(0);
4031   if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
4032     ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
4033     auto *subExpr = I->getSubExprAsWritten();
4034 
4035     if (subExpr->getStmtClass() != Stmt::StringLiteralClass) {
4036       return nullptr;
4037     }
4038 
4039     S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
4040   } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
4041     S = static_cast<StringLiteral *>(callExpr->getArg(0));
4042   } else {
4043     return nullptr;
4044   }
4045   return S;
4046 }
4047 
4048 struct ExprEvalResult {
4049   CXEvalResultKind EvalType;
4050   union {
4051     unsigned long long unsignedVal;
4052     long long intVal;
4053     double floatVal;
4054     char *stringVal;
4055   } EvalData;
4056   bool IsUnsignedInt;
4057   ~ExprEvalResult() {
4058     if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
4059         EvalType != CXEval_Int) {
4060       delete[] EvalData.stringVal;
4061     }
4062   }
4063 };
4064 
4065 void clang_EvalResult_dispose(CXEvalResult E) {
4066   delete static_cast<ExprEvalResult *>(E);
4067 }
4068 
4069 CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
4070   if (!E) {
4071     return CXEval_UnExposed;
4072   }
4073   return ((ExprEvalResult *)E)->EvalType;
4074 }
4075 
4076 int clang_EvalResult_getAsInt(CXEvalResult E) {
4077   return clang_EvalResult_getAsLongLong(E);
4078 }
4079 
4080 long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
4081   if (!E) {
4082     return 0;
4083   }
4084   ExprEvalResult *Result = (ExprEvalResult *)E;
4085   if (Result->IsUnsignedInt)
4086     return Result->EvalData.unsignedVal;
4087   return Result->EvalData.intVal;
4088 }
4089 
4090 unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
4091   return ((ExprEvalResult *)E)->IsUnsignedInt;
4092 }
4093 
4094 unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
4095   if (!E) {
4096     return 0;
4097   }
4098 
4099   ExprEvalResult *Result = (ExprEvalResult *)E;
4100   if (Result->IsUnsignedInt)
4101     return Result->EvalData.unsignedVal;
4102   return Result->EvalData.intVal;
4103 }
4104 
4105 double clang_EvalResult_getAsDouble(CXEvalResult E) {
4106   if (!E) {
4107     return 0;
4108   }
4109   return ((ExprEvalResult *)E)->EvalData.floatVal;
4110 }
4111 
4112 const char *clang_EvalResult_getAsStr(CXEvalResult E) {
4113   if (!E) {
4114     return nullptr;
4115   }
4116   return ((ExprEvalResult *)E)->EvalData.stringVal;
4117 }
4118 
4119 static const ExprEvalResult *evaluateExpr(Expr *expr, CXCursor C) {
4120   Expr::EvalResult ER;
4121   ASTContext &ctx = getCursorContext(C);
4122   if (!expr)
4123     return nullptr;
4124 
4125   expr = expr->IgnoreParens();
4126   if (expr->isValueDependent())
4127     return nullptr;
4128   if (!expr->EvaluateAsRValue(ER, ctx))
4129     return nullptr;
4130 
4131   QualType rettype;
4132   CallExpr *callExpr;
4133   auto result = std::make_unique<ExprEvalResult>();
4134   result->EvalType = CXEval_UnExposed;
4135   result->IsUnsignedInt = false;
4136 
4137   if (ER.Val.isInt()) {
4138     result->EvalType = CXEval_Int;
4139 
4140     auto &val = ER.Val.getInt();
4141     if (val.isUnsigned()) {
4142       result->IsUnsignedInt = true;
4143       result->EvalData.unsignedVal = val.getZExtValue();
4144     } else {
4145       result->EvalData.intVal = val.getExtValue();
4146     }
4147 
4148     return result.release();
4149   }
4150 
4151   if (ER.Val.isFloat()) {
4152     llvm::SmallVector<char, 100> Buffer;
4153     ER.Val.getFloat().toString(Buffer);
4154     std::string floatStr(Buffer.data(), Buffer.size());
4155     result->EvalType = CXEval_Float;
4156     bool ignored;
4157     llvm::APFloat apFloat = ER.Val.getFloat();
4158     apFloat.convert(llvm::APFloat::IEEEdouble(),
4159                     llvm::APFloat::rmNearestTiesToEven, &ignored);
4160     result->EvalData.floatVal = apFloat.convertToDouble();
4161     return result.release();
4162   }
4163 
4164   if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
4165     const auto *I = cast<ImplicitCastExpr>(expr);
4166     auto *subExpr = I->getSubExprAsWritten();
4167     if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
4168         subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
4169       const StringLiteral *StrE = nullptr;
4170       const ObjCStringLiteral *ObjCExpr;
4171       ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
4172 
4173       if (ObjCExpr) {
4174         StrE = ObjCExpr->getString();
4175         result->EvalType = CXEval_ObjCStrLiteral;
4176       } else {
4177         StrE = cast<StringLiteral>(I->getSubExprAsWritten());
4178         result->EvalType = CXEval_StrLiteral;
4179       }
4180 
4181       std::string strRef(StrE->getString().str());
4182       result->EvalData.stringVal = new char[strRef.size() + 1];
4183       strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
4184               strRef.size());
4185       result->EvalData.stringVal[strRef.size()] = '\0';
4186       return result.release();
4187     }
4188   } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
4189              expr->getStmtClass() == Stmt::StringLiteralClass) {
4190     const StringLiteral *StrE = nullptr;
4191     const ObjCStringLiteral *ObjCExpr;
4192     ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
4193 
4194     if (ObjCExpr) {
4195       StrE = ObjCExpr->getString();
4196       result->EvalType = CXEval_ObjCStrLiteral;
4197     } else {
4198       StrE = cast<StringLiteral>(expr);
4199       result->EvalType = CXEval_StrLiteral;
4200     }
4201 
4202     std::string strRef(StrE->getString().str());
4203     result->EvalData.stringVal = new char[strRef.size() + 1];
4204     strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
4205     result->EvalData.stringVal[strRef.size()] = '\0';
4206     return result.release();
4207   }
4208 
4209   if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
4210     CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
4211 
4212     rettype = CC->getType();
4213     if (rettype.getAsString() == "CFStringRef" &&
4214         CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
4215 
4216       callExpr = static_cast<CallExpr *>(CC->getSubExpr());
4217       StringLiteral *S = getCFSTR_value(callExpr);
4218       if (S) {
4219         std::string strLiteral(S->getString().str());
4220         result->EvalType = CXEval_CFStr;
4221 
4222         result->EvalData.stringVal = new char[strLiteral.size() + 1];
4223         strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
4224                 strLiteral.size());
4225         result->EvalData.stringVal[strLiteral.size()] = '\0';
4226         return result.release();
4227       }
4228     }
4229 
4230   } else if (expr->getStmtClass() == Stmt::CallExprClass) {
4231     callExpr = static_cast<CallExpr *>(expr);
4232     rettype = callExpr->getCallReturnType(ctx);
4233 
4234     if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
4235       return nullptr;
4236 
4237     if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
4238       if (callExpr->getNumArgs() == 1 &&
4239           !callExpr->getArg(0)->getType()->isIntegralType(ctx))
4240         return nullptr;
4241     } else if (rettype.getAsString() == "CFStringRef") {
4242 
4243       StringLiteral *S = getCFSTR_value(callExpr);
4244       if (S) {
4245         std::string strLiteral(S->getString().str());
4246         result->EvalType = CXEval_CFStr;
4247         result->EvalData.stringVal = new char[strLiteral.size() + 1];
4248         strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
4249                 strLiteral.size());
4250         result->EvalData.stringVal[strLiteral.size()] = '\0';
4251         return result.release();
4252       }
4253     }
4254   } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
4255     DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
4256     ValueDecl *V = D->getDecl();
4257     if (V->getKind() == Decl::Function) {
4258       std::string strName = V->getNameAsString();
4259       result->EvalType = CXEval_Other;
4260       result->EvalData.stringVal = new char[strName.size() + 1];
4261       strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
4262       result->EvalData.stringVal[strName.size()] = '\0';
4263       return result.release();
4264     }
4265   }
4266 
4267   return nullptr;
4268 }
4269 
4270 static const Expr *evaluateDeclExpr(const Decl *D) {
4271   if (!D)
4272     return nullptr;
4273   if (auto *Var = dyn_cast<VarDecl>(D))
4274     return Var->getInit();
4275   else if (auto *Field = dyn_cast<FieldDecl>(D))
4276     return Field->getInClassInitializer();
4277   return nullptr;
4278 }
4279 
4280 static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
4281   assert(CS && "invalid compound statement");
4282   for (auto *bodyIterator : CS->body()) {
4283     if (const auto *E = dyn_cast<Expr>(bodyIterator))
4284       return E;
4285   }
4286   return nullptr;
4287 }
4288 
4289 CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
4290   const Expr *E = nullptr;
4291   if (clang_getCursorKind(C) == CXCursor_CompoundStmt)
4292     E = evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)));
4293   else if (clang_isDeclaration(C.kind))
4294     E = evaluateDeclExpr(getCursorDecl(C));
4295   else if (clang_isExpression(C.kind))
4296     E = getCursorExpr(C);
4297   if (E)
4298     return const_cast<CXEvalResult>(
4299         reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4300   return nullptr;
4301 }
4302 
4303 unsigned clang_Cursor_hasAttrs(CXCursor C) {
4304   const Decl *D = getCursorDecl(C);
4305   if (!D) {
4306     return 0;
4307   }
4308 
4309   if (D->hasAttrs()) {
4310     return 1;
4311   }
4312 
4313   return 0;
4314 }
4315 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4316   return CXSaveTranslationUnit_None;
4317 }
4318 
4319 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4320                                                   const char *FileName,
4321                                                   unsigned options) {
4322   CIndexer *CXXIdx = TU->CIdx;
4323   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4324     setThreadBackgroundPriority();
4325 
4326   bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4327   return hadError ? CXSaveError_Unknown : CXSaveError_None;
4328 }
4329 
4330 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4331                               unsigned options) {
4332   LOG_FUNC_SECTION { *Log << TU << ' ' << FileName; }
4333 
4334   if (isNotUsableTU(TU)) {
4335     LOG_BAD_TU(TU);
4336     return CXSaveError_InvalidTU;
4337   }
4338 
4339   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4340   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4341   if (!CXXUnit->hasSema())
4342     return CXSaveError_InvalidTU;
4343 
4344   CXSaveError result;
4345   auto SaveTranslationUnitImpl = [=, &result]() {
4346     result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4347   };
4348 
4349   if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
4350     SaveTranslationUnitImpl();
4351 
4352     if (getenv("LIBCLANG_RESOURCE_USAGE"))
4353       PrintLibclangResourceUsage(TU);
4354 
4355     return result;
4356   }
4357 
4358   // We have an AST that has invalid nodes due to compiler errors.
4359   // Use a crash recovery thread for protection.
4360 
4361   llvm::CrashRecoveryContext CRC;
4362 
4363   if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
4364     fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4365     fprintf(stderr, "  'filename' : '%s'\n", FileName);
4366     fprintf(stderr, "  'options' : %d,\n", options);
4367     fprintf(stderr, "}\n");
4368 
4369     return CXSaveError_Unknown;
4370 
4371   } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4372     PrintLibclangResourceUsage(TU);
4373   }
4374 
4375   return result;
4376 }
4377 
4378 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4379   if (CTUnit) {
4380     // If the translation unit has been marked as unsafe to free, just discard
4381     // it.
4382     ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4383     if (Unit && Unit->isUnsafeToFree())
4384       return;
4385 
4386     delete cxtu::getASTUnit(CTUnit);
4387     delete CTUnit->StringPool;
4388     delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4389     disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
4390     delete CTUnit->CommentToXML;
4391     delete CTUnit;
4392   }
4393 }
4394 
4395 unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4396   if (CTUnit) {
4397     ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4398 
4399     if (Unit && Unit->isUnsafeToFree())
4400       return false;
4401 
4402     Unit->ResetForParse();
4403     return true;
4404   }
4405 
4406   return false;
4407 }
4408 
4409 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4410   return CXReparse_None;
4411 }
4412 
4413 static CXErrorCode
4414 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4415                                   ArrayRef<CXUnsavedFile> unsaved_files,
4416                                   unsigned options) {
4417   // Check arguments.
4418   if (isNotUsableTU(TU)) {
4419     LOG_BAD_TU(TU);
4420     return CXError_InvalidArguments;
4421   }
4422 
4423   // Reset the associated diagnostics.
4424   delete static_cast<CXDiagnosticSetImpl *>(TU->Diagnostics);
4425   TU->Diagnostics = nullptr;
4426 
4427   CIndexer *CXXIdx = TU->CIdx;
4428   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4429     setThreadBackgroundPriority();
4430 
4431   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4432   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4433 
4434   std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4435       new std::vector<ASTUnit::RemappedFile>());
4436 
4437   // Recover resources if we crash before exiting this function.
4438   llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
4439       RemappedCleanup(RemappedFiles.get());
4440 
4441   for (auto &UF : unsaved_files) {
4442     std::unique_ptr<llvm::MemoryBuffer> MB =
4443         llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
4444     RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
4445   }
4446 
4447   if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4448                         *RemappedFiles.get()))
4449     return CXError_Success;
4450   if (isASTReadError(CXXUnit))
4451     return CXError_ASTReadError;
4452   return CXError_Failure;
4453 }
4454 
4455 int clang_reparseTranslationUnit(CXTranslationUnit TU,
4456                                  unsigned num_unsaved_files,
4457                                  struct CXUnsavedFile *unsaved_files,
4458                                  unsigned options) {
4459   LOG_FUNC_SECTION { *Log << TU; }
4460 
4461   if (num_unsaved_files && !unsaved_files)
4462     return CXError_InvalidArguments;
4463 
4464   CXErrorCode result;
4465   auto ReparseTranslationUnitImpl = [=, &result]() {
4466     result = clang_reparseTranslationUnit_Impl(
4467         TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4468   };
4469 
4470   llvm::CrashRecoveryContext CRC;
4471 
4472   if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
4473     fprintf(stderr, "libclang: crash detected during reparsing\n");
4474     cxtu::getASTUnit(TU)->setUnsafeToFree(true);
4475     return CXError_Crashed;
4476   } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4477     PrintLibclangResourceUsage(TU);
4478 
4479   return result;
4480 }
4481 
4482 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
4483   if (isNotUsableTU(CTUnit)) {
4484     LOG_BAD_TU(CTUnit);
4485     return cxstring::createEmpty();
4486   }
4487 
4488   ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4489   return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
4490 }
4491 
4492 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
4493   if (isNotUsableTU(TU)) {
4494     LOG_BAD_TU(TU);
4495     return clang_getNullCursor();
4496   }
4497 
4498   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4499   return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4500 }
4501 
4502 CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4503   if (isNotUsableTU(CTUnit)) {
4504     LOG_BAD_TU(CTUnit);
4505     return nullptr;
4506   }
4507 
4508   CXTargetInfoImpl *impl = new CXTargetInfoImpl();
4509   impl->TranslationUnit = CTUnit;
4510   return impl;
4511 }
4512 
4513 CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4514   if (!TargetInfo)
4515     return cxstring::createEmpty();
4516 
4517   CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4518   assert(!isNotUsableTU(CTUnit) &&
4519          "Unexpected unusable translation unit in TargetInfo");
4520 
4521   ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4522   std::string Triple =
4523       CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4524   return cxstring::createDup(Triple);
4525 }
4526 
4527 int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4528   if (!TargetInfo)
4529     return -1;
4530 
4531   CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4532   assert(!isNotUsableTU(CTUnit) &&
4533          "Unexpected unusable translation unit in TargetInfo");
4534 
4535   ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4536   return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4537 }
4538 
4539 void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4540   if (!TargetInfo)
4541     return;
4542 
4543   delete TargetInfo;
4544 }
4545 
4546 //===----------------------------------------------------------------------===//
4547 // CXFile Operations.
4548 //===----------------------------------------------------------------------===//
4549 
4550 CXString clang_getFileName(CXFile SFile) {
4551   if (!SFile)
4552     return cxstring::createNull();
4553 
4554   FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4555   return cxstring::createRef(FEnt->getName());
4556 }
4557 
4558 time_t clang_getFileTime(CXFile SFile) {
4559   if (!SFile)
4560     return 0;
4561 
4562   FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4563   return FEnt->getModificationTime();
4564 }
4565 
4566 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
4567   if (isNotUsableTU(TU)) {
4568     LOG_BAD_TU(TU);
4569     return nullptr;
4570   }
4571 
4572   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4573 
4574   FileManager &FMgr = CXXUnit->getFileManager();
4575   auto File = FMgr.getFile(file_name);
4576   if (!File)
4577     return nullptr;
4578   return const_cast<FileEntry *>(*File);
4579 }
4580 
4581 const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4582                                   size_t *size) {
4583   if (isNotUsableTU(TU)) {
4584     LOG_BAD_TU(TU);
4585     return nullptr;
4586   }
4587 
4588   const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4589   FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4590   llvm::Optional<llvm::MemoryBufferRef> buf = SM.getBufferOrNone(fid);
4591   if (!buf) {
4592     if (size)
4593       *size = 0;
4594     return nullptr;
4595   }
4596   if (size)
4597     *size = buf->getBufferSize();
4598   return buf->getBufferStart();
4599 }
4600 
4601 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, CXFile file) {
4602   if (isNotUsableTU(TU)) {
4603     LOG_BAD_TU(TU);
4604     return 0;
4605   }
4606 
4607   if (!file)
4608     return 0;
4609 
4610   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4611   FileEntry *FEnt = static_cast<FileEntry *>(file);
4612   return CXXUnit->getPreprocessor()
4613       .getHeaderSearchInfo()
4614       .isFileMultipleIncludeGuarded(FEnt);
4615 }
4616 
4617 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4618   if (!file || !outID)
4619     return 1;
4620 
4621   FileEntry *FEnt = static_cast<FileEntry *>(file);
4622   const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4623   outID->data[0] = ID.getDevice();
4624   outID->data[1] = ID.getFile();
4625   outID->data[2] = FEnt->getModificationTime();
4626   return 0;
4627 }
4628 
4629 int clang_File_isEqual(CXFile file1, CXFile file2) {
4630   if (file1 == file2)
4631     return true;
4632 
4633   if (!file1 || !file2)
4634     return false;
4635 
4636   FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4637   FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4638   return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4639 }
4640 
4641 CXString clang_File_tryGetRealPathName(CXFile SFile) {
4642   if (!SFile)
4643     return cxstring::createNull();
4644 
4645   FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4646   return cxstring::createRef(FEnt->tryGetRealPathName());
4647 }
4648 
4649 //===----------------------------------------------------------------------===//
4650 // CXCursor Operations.
4651 //===----------------------------------------------------------------------===//
4652 
4653 static const Decl *getDeclFromExpr(const Stmt *E) {
4654   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4655     return getDeclFromExpr(CE->getSubExpr());
4656 
4657   if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
4658     return RefExpr->getDecl();
4659   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4660     return ME->getMemberDecl();
4661   if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
4662     return RE->getDecl();
4663   if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
4664     if (PRE->isExplicitProperty())
4665       return PRE->getExplicitProperty();
4666     // It could be messaging both getter and setter as in:
4667     // ++myobj.myprop;
4668     // in which case prefer to associate the setter since it is less obvious
4669     // from inspecting the source that the setter is going to get called.
4670     if (PRE->isMessagingSetter())
4671       return PRE->getImplicitPropertySetter();
4672     return PRE->getImplicitPropertyGetter();
4673   }
4674   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
4675     return getDeclFromExpr(POE->getSyntacticForm());
4676   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4677     if (Expr *Src = OVE->getSourceExpr())
4678       return getDeclFromExpr(Src);
4679 
4680   if (const CallExpr *CE = dyn_cast<CallExpr>(E))
4681     return getDeclFromExpr(CE->getCallee());
4682   if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
4683     if (!CE->isElidable())
4684       return CE->getConstructor();
4685   if (const CXXInheritedCtorInitExpr *CE =
4686           dyn_cast<CXXInheritedCtorInitExpr>(E))
4687     return CE->getConstructor();
4688   if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
4689     return OME->getMethodDecl();
4690 
4691   if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
4692     return PE->getProtocol();
4693   if (const SubstNonTypeTemplateParmPackExpr *NTTP =
4694           dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4695     return NTTP->getParameterPack();
4696   if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4697     if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4698         isa<ParmVarDecl>(SizeOfPack->getPack()))
4699       return SizeOfPack->getPack();
4700 
4701   return nullptr;
4702 }
4703 
4704 static SourceLocation getLocationFromExpr(const Expr *E) {
4705   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4706     return getLocationFromExpr(CE->getSubExpr());
4707 
4708   if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
4709     return /*FIXME:*/ Msg->getLeftLoc();
4710   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4711     return DRE->getLocation();
4712   if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
4713     return Member->getMemberLoc();
4714   if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
4715     return Ivar->getLocation();
4716   if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4717     return SizeOfPack->getPackLoc();
4718   if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
4719     return PropRef->getLocation();
4720 
4721   return E->getBeginLoc();
4722 }
4723 
4724 extern "C" {
4725 
4726 unsigned clang_visitChildren(CXCursor parent, CXCursorVisitor visitor,
4727                              CXClientData client_data) {
4728   CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4729                           /*VisitPreprocessorLast=*/false);
4730   return CursorVis.VisitChildren(parent);
4731 }
4732 
4733 #ifndef __has_feature
4734 #define __has_feature(x) 0
4735 #endif
4736 #if __has_feature(blocks)
4737 typedef enum CXChildVisitResult (^CXCursorVisitorBlock)(CXCursor cursor,
4738                                                         CXCursor parent);
4739 
4740 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4741                                               CXClientData client_data) {
4742   CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4743   return block(cursor, parent);
4744 }
4745 #else
4746 // If we are compiled with a compiler that doesn't have native blocks support,
4747 // define and call the block manually, so the
4748 typedef struct _CXChildVisitResult {
4749   void *isa;
4750   int flags;
4751   int reserved;
4752   enum CXChildVisitResult (*invoke)(struct _CXChildVisitResult *, CXCursor,
4753                                     CXCursor);
4754 } * CXCursorVisitorBlock;
4755 
4756 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4757                                               CXClientData client_data) {
4758   CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4759   return block->invoke(block, cursor, parent);
4760 }
4761 #endif
4762 
4763 unsigned clang_visitChildrenWithBlock(CXCursor parent,
4764                                       CXCursorVisitorBlock block) {
4765   return clang_visitChildren(parent, visitWithBlock, block);
4766 }
4767 
4768 static CXString getDeclSpelling(const Decl *D) {
4769   if (!D)
4770     return cxstring::createEmpty();
4771 
4772   const NamedDecl *ND = dyn_cast<NamedDecl>(D);
4773   if (!ND) {
4774     if (const ObjCPropertyImplDecl *PropImpl =
4775             dyn_cast<ObjCPropertyImplDecl>(D))
4776       if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4777         return cxstring::createDup(Property->getIdentifier()->getName());
4778 
4779     if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
4780       if (Module *Mod = ImportD->getImportedModule())
4781         return cxstring::createDup(Mod->getFullModuleName());
4782 
4783     return cxstring::createEmpty();
4784   }
4785 
4786   if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
4787     return cxstring::createDup(OMD->getSelector().getAsString());
4788 
4789   if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
4790     // No, this isn't the same as the code below. getIdentifier() is non-virtual
4791     // and returns different names. NamedDecl returns the class name and
4792     // ObjCCategoryImplDecl returns the category name.
4793     return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
4794 
4795   if (isa<UsingDirectiveDecl>(D))
4796     return cxstring::createEmpty();
4797 
4798   SmallString<1024> S;
4799   llvm::raw_svector_ostream os(S);
4800   ND->printName(os);
4801 
4802   return cxstring::createDup(os.str());
4803 }
4804 
4805 CXString clang_getCursorSpelling(CXCursor C) {
4806   if (clang_isTranslationUnit(C.kind))
4807     return clang_getTranslationUnitSpelling(getCursorTU(C));
4808 
4809   if (clang_isReference(C.kind)) {
4810     switch (C.kind) {
4811     case CXCursor_ObjCSuperClassRef: {
4812       const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
4813       return cxstring::createRef(Super->getIdentifier()->getNameStart());
4814     }
4815     case CXCursor_ObjCClassRef: {
4816       const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4817       return cxstring::createRef(Class->getIdentifier()->getNameStart());
4818     }
4819     case CXCursor_ObjCProtocolRef: {
4820       const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
4821       assert(OID && "getCursorSpelling(): Missing protocol decl");
4822       return cxstring::createRef(OID->getIdentifier()->getNameStart());
4823     }
4824     case CXCursor_CXXBaseSpecifier: {
4825       const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
4826       return cxstring::createDup(B->getType().getAsString());
4827     }
4828     case CXCursor_TypeRef: {
4829       const TypeDecl *Type = getCursorTypeRef(C).first;
4830       assert(Type && "Missing type decl");
4831 
4832       return cxstring::createDup(
4833           getCursorContext(C).getTypeDeclType(Type).getAsString());
4834     }
4835     case CXCursor_TemplateRef: {
4836       const TemplateDecl *Template = getCursorTemplateRef(C).first;
4837       assert(Template && "Missing template decl");
4838 
4839       return cxstring::createDup(Template->getNameAsString());
4840     }
4841 
4842     case CXCursor_NamespaceRef: {
4843       const NamedDecl *NS = getCursorNamespaceRef(C).first;
4844       assert(NS && "Missing namespace decl");
4845 
4846       return cxstring::createDup(NS->getNameAsString());
4847     }
4848 
4849     case CXCursor_MemberRef: {
4850       const FieldDecl *Field = getCursorMemberRef(C).first;
4851       assert(Field && "Missing member decl");
4852 
4853       return cxstring::createDup(Field->getNameAsString());
4854     }
4855 
4856     case CXCursor_LabelRef: {
4857       const LabelStmt *Label = getCursorLabelRef(C).first;
4858       assert(Label && "Missing label");
4859 
4860       return cxstring::createRef(Label->getName());
4861     }
4862 
4863     case CXCursor_OverloadedDeclRef: {
4864       OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4865       if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4866         if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
4867           return cxstring::createDup(ND->getNameAsString());
4868         return cxstring::createEmpty();
4869       }
4870       if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4871         return cxstring::createDup(E->getName().getAsString());
4872       OverloadedTemplateStorage *Ovl =
4873           Storage.get<OverloadedTemplateStorage *>();
4874       if (Ovl->size() == 0)
4875         return cxstring::createEmpty();
4876       return cxstring::createDup((*Ovl->begin())->getNameAsString());
4877     }
4878 
4879     case CXCursor_VariableRef: {
4880       const VarDecl *Var = getCursorVariableRef(C).first;
4881       assert(Var && "Missing variable decl");
4882 
4883       return cxstring::createDup(Var->getNameAsString());
4884     }
4885 
4886     default:
4887       return cxstring::createRef("<not implemented>");
4888     }
4889   }
4890 
4891   if (clang_isExpression(C.kind)) {
4892     const Expr *E = getCursorExpr(C);
4893 
4894     if (C.kind == CXCursor_ObjCStringLiteral ||
4895         C.kind == CXCursor_StringLiteral) {
4896       const StringLiteral *SLit;
4897       if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4898         SLit = OSL->getString();
4899       } else {
4900         SLit = cast<StringLiteral>(E);
4901       }
4902       SmallString<256> Buf;
4903       llvm::raw_svector_ostream OS(Buf);
4904       SLit->outputString(OS);
4905       return cxstring::createDup(OS.str());
4906     }
4907 
4908     const Decl *D = getDeclFromExpr(getCursorExpr(C));
4909     if (D)
4910       return getDeclSpelling(D);
4911     return cxstring::createEmpty();
4912   }
4913 
4914   if (clang_isStatement(C.kind)) {
4915     const Stmt *S = getCursorStmt(C);
4916     if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
4917       return cxstring::createRef(Label->getName());
4918 
4919     return cxstring::createEmpty();
4920   }
4921 
4922   if (C.kind == CXCursor_MacroExpansion)
4923     return cxstring::createRef(
4924         getCursorMacroExpansion(C).getName()->getNameStart());
4925 
4926   if (C.kind == CXCursor_MacroDefinition)
4927     return cxstring::createRef(
4928         getCursorMacroDefinition(C)->getName()->getNameStart());
4929 
4930   if (C.kind == CXCursor_InclusionDirective)
4931     return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
4932 
4933   if (clang_isDeclaration(C.kind))
4934     return getDeclSpelling(getCursorDecl(C));
4935 
4936   if (C.kind == CXCursor_AnnotateAttr) {
4937     const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
4938     return cxstring::createDup(AA->getAnnotation());
4939   }
4940 
4941   if (C.kind == CXCursor_AsmLabelAttr) {
4942     const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
4943     return cxstring::createDup(AA->getLabel());
4944   }
4945 
4946   if (C.kind == CXCursor_PackedAttr) {
4947     return cxstring::createRef("packed");
4948   }
4949 
4950   if (C.kind == CXCursor_VisibilityAttr) {
4951     const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4952     switch (AA->getVisibility()) {
4953     case VisibilityAttr::VisibilityType::Default:
4954       return cxstring::createRef("default");
4955     case VisibilityAttr::VisibilityType::Hidden:
4956       return cxstring::createRef("hidden");
4957     case VisibilityAttr::VisibilityType::Protected:
4958       return cxstring::createRef("protected");
4959     }
4960     llvm_unreachable("unknown visibility type");
4961   }
4962 
4963   return cxstring::createEmpty();
4964 }
4965 
4966 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, unsigned pieceIndex,
4967                                                 unsigned options) {
4968   if (clang_Cursor_isNull(C))
4969     return clang_getNullRange();
4970 
4971   ASTContext &Ctx = getCursorContext(C);
4972 
4973   if (clang_isStatement(C.kind)) {
4974     const Stmt *S = getCursorStmt(C);
4975     if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
4976       if (pieceIndex > 0)
4977         return clang_getNullRange();
4978       return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4979     }
4980 
4981     return clang_getNullRange();
4982   }
4983 
4984   if (C.kind == CXCursor_ObjCMessageExpr) {
4985     if (const ObjCMessageExpr *ME =
4986             dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4987       if (pieceIndex >= ME->getNumSelectorLocs())
4988         return clang_getNullRange();
4989       return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4990     }
4991   }
4992 
4993   if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4994       C.kind == CXCursor_ObjCClassMethodDecl) {
4995     if (const ObjCMethodDecl *MD =
4996             dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4997       if (pieceIndex >= MD->getNumSelectorLocs())
4998         return clang_getNullRange();
4999       return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
5000     }
5001   }
5002 
5003   if (C.kind == CXCursor_ObjCCategoryDecl ||
5004       C.kind == CXCursor_ObjCCategoryImplDecl) {
5005     if (pieceIndex > 0)
5006       return clang_getNullRange();
5007     if (const ObjCCategoryDecl *CD =
5008             dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
5009       return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
5010     if (const ObjCCategoryImplDecl *CID =
5011             dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
5012       return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
5013   }
5014 
5015   if (C.kind == CXCursor_ModuleImportDecl) {
5016     if (pieceIndex > 0)
5017       return clang_getNullRange();
5018     if (const ImportDecl *ImportD =
5019             dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
5020       ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
5021       if (!Locs.empty())
5022         return cxloc::translateSourceRange(
5023             Ctx, SourceRange(Locs.front(), Locs.back()));
5024     }
5025     return clang_getNullRange();
5026   }
5027 
5028   if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
5029       C.kind == CXCursor_ConversionFunction ||
5030       C.kind == CXCursor_FunctionDecl) {
5031     if (pieceIndex > 0)
5032       return clang_getNullRange();
5033     if (const FunctionDecl *FD =
5034             dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
5035       DeclarationNameInfo FunctionName = FD->getNameInfo();
5036       return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
5037     }
5038     return clang_getNullRange();
5039   }
5040 
5041   // FIXME: A CXCursor_InclusionDirective should give the location of the
5042   // filename, but we don't keep track of this.
5043 
5044   // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
5045   // but we don't keep track of this.
5046 
5047   // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
5048   // but we don't keep track of this.
5049 
5050   // Default handling, give the location of the cursor.
5051 
5052   if (pieceIndex > 0)
5053     return clang_getNullRange();
5054 
5055   CXSourceLocation CXLoc = clang_getCursorLocation(C);
5056   SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
5057   return cxloc::translateSourceRange(Ctx, Loc);
5058 }
5059 
5060 CXString clang_Cursor_getMangling(CXCursor C) {
5061   if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
5062     return cxstring::createEmpty();
5063 
5064   // Mangling only works for functions and variables.
5065   const Decl *D = getCursorDecl(C);
5066   if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
5067     return cxstring::createEmpty();
5068 
5069   ASTContext &Ctx = D->getASTContext();
5070   ASTNameGenerator ASTNameGen(Ctx);
5071   return cxstring::createDup(ASTNameGen.getName(D));
5072 }
5073 
5074 CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
5075   if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
5076     return nullptr;
5077 
5078   const Decl *D = getCursorDecl(C);
5079   if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
5080     return nullptr;
5081 
5082   ASTContext &Ctx = D->getASTContext();
5083   ASTNameGenerator ASTNameGen(Ctx);
5084   std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
5085   return cxstring::createSet(Manglings);
5086 }
5087 
5088 CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
5089   if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
5090     return nullptr;
5091 
5092   const Decl *D = getCursorDecl(C);
5093   if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
5094     return nullptr;
5095 
5096   ASTContext &Ctx = D->getASTContext();
5097   ASTNameGenerator ASTNameGen(Ctx);
5098   std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
5099   return cxstring::createSet(Manglings);
5100 }
5101 
5102 CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
5103   if (clang_Cursor_isNull(C))
5104     return nullptr;
5105   return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
5106 }
5107 
5108 void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
5109   if (Policy)
5110     delete static_cast<PrintingPolicy *>(Policy);
5111 }
5112 
5113 unsigned
5114 clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
5115                                  enum CXPrintingPolicyProperty Property) {
5116   if (!Policy)
5117     return 0;
5118 
5119   PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
5120   switch (Property) {
5121   case CXPrintingPolicy_Indentation:
5122     return P->Indentation;
5123   case CXPrintingPolicy_SuppressSpecifiers:
5124     return P->SuppressSpecifiers;
5125   case CXPrintingPolicy_SuppressTagKeyword:
5126     return P->SuppressTagKeyword;
5127   case CXPrintingPolicy_IncludeTagDefinition:
5128     return P->IncludeTagDefinition;
5129   case CXPrintingPolicy_SuppressScope:
5130     return P->SuppressScope;
5131   case CXPrintingPolicy_SuppressUnwrittenScope:
5132     return P->SuppressUnwrittenScope;
5133   case CXPrintingPolicy_SuppressInitializers:
5134     return P->SuppressInitializers;
5135   case CXPrintingPolicy_ConstantArraySizeAsWritten:
5136     return P->ConstantArraySizeAsWritten;
5137   case CXPrintingPolicy_AnonymousTagLocations:
5138     return P->AnonymousTagLocations;
5139   case CXPrintingPolicy_SuppressStrongLifetime:
5140     return P->SuppressStrongLifetime;
5141   case CXPrintingPolicy_SuppressLifetimeQualifiers:
5142     return P->SuppressLifetimeQualifiers;
5143   case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
5144     return P->SuppressTemplateArgsInCXXConstructors;
5145   case CXPrintingPolicy_Bool:
5146     return P->Bool;
5147   case CXPrintingPolicy_Restrict:
5148     return P->Restrict;
5149   case CXPrintingPolicy_Alignof:
5150     return P->Alignof;
5151   case CXPrintingPolicy_UnderscoreAlignof:
5152     return P->UnderscoreAlignof;
5153   case CXPrintingPolicy_UseVoidForZeroParams:
5154     return P->UseVoidForZeroParams;
5155   case CXPrintingPolicy_TerseOutput:
5156     return P->TerseOutput;
5157   case CXPrintingPolicy_PolishForDeclaration:
5158     return P->PolishForDeclaration;
5159   case CXPrintingPolicy_Half:
5160     return P->Half;
5161   case CXPrintingPolicy_MSWChar:
5162     return P->MSWChar;
5163   case CXPrintingPolicy_IncludeNewlines:
5164     return P->IncludeNewlines;
5165   case CXPrintingPolicy_MSVCFormatting:
5166     return P->MSVCFormatting;
5167   case CXPrintingPolicy_ConstantsAsWritten:
5168     return P->ConstantsAsWritten;
5169   case CXPrintingPolicy_SuppressImplicitBase:
5170     return P->SuppressImplicitBase;
5171   case CXPrintingPolicy_FullyQualifiedName:
5172     return P->FullyQualifiedName;
5173   }
5174 
5175   assert(false && "Invalid CXPrintingPolicyProperty");
5176   return 0;
5177 }
5178 
5179 void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
5180                                       enum CXPrintingPolicyProperty Property,
5181                                       unsigned Value) {
5182   if (!Policy)
5183     return;
5184 
5185   PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
5186   switch (Property) {
5187   case CXPrintingPolicy_Indentation:
5188     P->Indentation = Value;
5189     return;
5190   case CXPrintingPolicy_SuppressSpecifiers:
5191     P->SuppressSpecifiers = Value;
5192     return;
5193   case CXPrintingPolicy_SuppressTagKeyword:
5194     P->SuppressTagKeyword = Value;
5195     return;
5196   case CXPrintingPolicy_IncludeTagDefinition:
5197     P->IncludeTagDefinition = Value;
5198     return;
5199   case CXPrintingPolicy_SuppressScope:
5200     P->SuppressScope = Value;
5201     return;
5202   case CXPrintingPolicy_SuppressUnwrittenScope:
5203     P->SuppressUnwrittenScope = Value;
5204     return;
5205   case CXPrintingPolicy_SuppressInitializers:
5206     P->SuppressInitializers = Value;
5207     return;
5208   case CXPrintingPolicy_ConstantArraySizeAsWritten:
5209     P->ConstantArraySizeAsWritten = Value;
5210     return;
5211   case CXPrintingPolicy_AnonymousTagLocations:
5212     P->AnonymousTagLocations = Value;
5213     return;
5214   case CXPrintingPolicy_SuppressStrongLifetime:
5215     P->SuppressStrongLifetime = Value;
5216     return;
5217   case CXPrintingPolicy_SuppressLifetimeQualifiers:
5218     P->SuppressLifetimeQualifiers = Value;
5219     return;
5220   case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
5221     P->SuppressTemplateArgsInCXXConstructors = Value;
5222     return;
5223   case CXPrintingPolicy_Bool:
5224     P->Bool = Value;
5225     return;
5226   case CXPrintingPolicy_Restrict:
5227     P->Restrict = Value;
5228     return;
5229   case CXPrintingPolicy_Alignof:
5230     P->Alignof = Value;
5231     return;
5232   case CXPrintingPolicy_UnderscoreAlignof:
5233     P->UnderscoreAlignof = Value;
5234     return;
5235   case CXPrintingPolicy_UseVoidForZeroParams:
5236     P->UseVoidForZeroParams = Value;
5237     return;
5238   case CXPrintingPolicy_TerseOutput:
5239     P->TerseOutput = Value;
5240     return;
5241   case CXPrintingPolicy_PolishForDeclaration:
5242     P->PolishForDeclaration = Value;
5243     return;
5244   case CXPrintingPolicy_Half:
5245     P->Half = Value;
5246     return;
5247   case CXPrintingPolicy_MSWChar:
5248     P->MSWChar = Value;
5249     return;
5250   case CXPrintingPolicy_IncludeNewlines:
5251     P->IncludeNewlines = Value;
5252     return;
5253   case CXPrintingPolicy_MSVCFormatting:
5254     P->MSVCFormatting = Value;
5255     return;
5256   case CXPrintingPolicy_ConstantsAsWritten:
5257     P->ConstantsAsWritten = Value;
5258     return;
5259   case CXPrintingPolicy_SuppressImplicitBase:
5260     P->SuppressImplicitBase = Value;
5261     return;
5262   case CXPrintingPolicy_FullyQualifiedName:
5263     P->FullyQualifiedName = Value;
5264     return;
5265   }
5266 
5267   assert(false && "Invalid CXPrintingPolicyProperty");
5268 }
5269 
5270 CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
5271   if (clang_Cursor_isNull(C))
5272     return cxstring::createEmpty();
5273 
5274   if (clang_isDeclaration(C.kind)) {
5275     const Decl *D = getCursorDecl(C);
5276     if (!D)
5277       return cxstring::createEmpty();
5278 
5279     SmallString<128> Str;
5280     llvm::raw_svector_ostream OS(Str);
5281     PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
5282     D->print(OS, UserPolicy ? *UserPolicy
5283                             : getCursorContext(C).getPrintingPolicy());
5284 
5285     return cxstring::createDup(OS.str());
5286   }
5287 
5288   return cxstring::createEmpty();
5289 }
5290 
5291 CXString clang_getCursorDisplayName(CXCursor C) {
5292   if (!clang_isDeclaration(C.kind))
5293     return clang_getCursorSpelling(C);
5294 
5295   const Decl *D = getCursorDecl(C);
5296   if (!D)
5297     return cxstring::createEmpty();
5298 
5299   PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
5300   if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
5301     D = FunTmpl->getTemplatedDecl();
5302 
5303   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
5304     SmallString<64> Str;
5305     llvm::raw_svector_ostream OS(Str);
5306     OS << *Function;
5307     if (Function->getPrimaryTemplate())
5308       OS << "<>";
5309     OS << "(";
5310     for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5311       if (I)
5312         OS << ", ";
5313       OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5314     }
5315 
5316     if (Function->isVariadic()) {
5317       if (Function->getNumParams())
5318         OS << ", ";
5319       OS << "...";
5320     }
5321     OS << ")";
5322     return cxstring::createDup(OS.str());
5323   }
5324 
5325   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
5326     SmallString<64> Str;
5327     llvm::raw_svector_ostream OS(Str);
5328     OS << *ClassTemplate;
5329     OS << "<";
5330     TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5331     for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5332       if (I)
5333         OS << ", ";
5334 
5335       NamedDecl *Param = Params->getParam(I);
5336       if (Param->getIdentifier()) {
5337         OS << Param->getIdentifier()->getName();
5338         continue;
5339       }
5340 
5341       // There is no parameter name, which makes this tricky. Try to come up
5342       // with something useful that isn't too long.
5343       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5344         if (const auto *TC = TTP->getTypeConstraint()) {
5345           TC->getConceptNameInfo().printName(OS, Policy);
5346           if (TC->hasExplicitTemplateArgs())
5347             OS << "<...>";
5348         } else
5349           OS << (TTP->wasDeclaredWithTypename() ? "typename" : "class");
5350       else if (NonTypeTemplateParmDecl *NTTP =
5351                    dyn_cast<NonTypeTemplateParmDecl>(Param))
5352         OS << NTTP->getType().getAsString(Policy);
5353       else
5354         OS << "template<...> class";
5355     }
5356 
5357     OS << ">";
5358     return cxstring::createDup(OS.str());
5359   }
5360 
5361   if (const ClassTemplateSpecializationDecl *ClassSpec =
5362           dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5363     // If the type was explicitly written, use that.
5364     if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
5365       return cxstring::createDup(TSInfo->getType().getAsString(Policy));
5366 
5367     SmallString<128> Str;
5368     llvm::raw_svector_ostream OS(Str);
5369     OS << *ClassSpec;
5370     printTemplateArgumentList(
5371         OS, ClassSpec->getTemplateArgs().asArray(), Policy,
5372         ClassSpec->getSpecializedTemplate()->getTemplateParameters());
5373     return cxstring::createDup(OS.str());
5374   }
5375 
5376   return clang_getCursorSpelling(C);
5377 }
5378 
5379 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5380   switch (Kind) {
5381   case CXCursor_FunctionDecl:
5382     return cxstring::createRef("FunctionDecl");
5383   case CXCursor_TypedefDecl:
5384     return cxstring::createRef("TypedefDecl");
5385   case CXCursor_EnumDecl:
5386     return cxstring::createRef("EnumDecl");
5387   case CXCursor_EnumConstantDecl:
5388     return cxstring::createRef("EnumConstantDecl");
5389   case CXCursor_StructDecl:
5390     return cxstring::createRef("StructDecl");
5391   case CXCursor_UnionDecl:
5392     return cxstring::createRef("UnionDecl");
5393   case CXCursor_ClassDecl:
5394     return cxstring::createRef("ClassDecl");
5395   case CXCursor_FieldDecl:
5396     return cxstring::createRef("FieldDecl");
5397   case CXCursor_VarDecl:
5398     return cxstring::createRef("VarDecl");
5399   case CXCursor_ParmDecl:
5400     return cxstring::createRef("ParmDecl");
5401   case CXCursor_ObjCInterfaceDecl:
5402     return cxstring::createRef("ObjCInterfaceDecl");
5403   case CXCursor_ObjCCategoryDecl:
5404     return cxstring::createRef("ObjCCategoryDecl");
5405   case CXCursor_ObjCProtocolDecl:
5406     return cxstring::createRef("ObjCProtocolDecl");
5407   case CXCursor_ObjCPropertyDecl:
5408     return cxstring::createRef("ObjCPropertyDecl");
5409   case CXCursor_ObjCIvarDecl:
5410     return cxstring::createRef("ObjCIvarDecl");
5411   case CXCursor_ObjCInstanceMethodDecl:
5412     return cxstring::createRef("ObjCInstanceMethodDecl");
5413   case CXCursor_ObjCClassMethodDecl:
5414     return cxstring::createRef("ObjCClassMethodDecl");
5415   case CXCursor_ObjCImplementationDecl:
5416     return cxstring::createRef("ObjCImplementationDecl");
5417   case CXCursor_ObjCCategoryImplDecl:
5418     return cxstring::createRef("ObjCCategoryImplDecl");
5419   case CXCursor_CXXMethod:
5420     return cxstring::createRef("CXXMethod");
5421   case CXCursor_UnexposedDecl:
5422     return cxstring::createRef("UnexposedDecl");
5423   case CXCursor_ObjCSuperClassRef:
5424     return cxstring::createRef("ObjCSuperClassRef");
5425   case CXCursor_ObjCProtocolRef:
5426     return cxstring::createRef("ObjCProtocolRef");
5427   case CXCursor_ObjCClassRef:
5428     return cxstring::createRef("ObjCClassRef");
5429   case CXCursor_TypeRef:
5430     return cxstring::createRef("TypeRef");
5431   case CXCursor_TemplateRef:
5432     return cxstring::createRef("TemplateRef");
5433   case CXCursor_NamespaceRef:
5434     return cxstring::createRef("NamespaceRef");
5435   case CXCursor_MemberRef:
5436     return cxstring::createRef("MemberRef");
5437   case CXCursor_LabelRef:
5438     return cxstring::createRef("LabelRef");
5439   case CXCursor_OverloadedDeclRef:
5440     return cxstring::createRef("OverloadedDeclRef");
5441   case CXCursor_VariableRef:
5442     return cxstring::createRef("VariableRef");
5443   case CXCursor_IntegerLiteral:
5444     return cxstring::createRef("IntegerLiteral");
5445   case CXCursor_FixedPointLiteral:
5446     return cxstring::createRef("FixedPointLiteral");
5447   case CXCursor_FloatingLiteral:
5448     return cxstring::createRef("FloatingLiteral");
5449   case CXCursor_ImaginaryLiteral:
5450     return cxstring::createRef("ImaginaryLiteral");
5451   case CXCursor_StringLiteral:
5452     return cxstring::createRef("StringLiteral");
5453   case CXCursor_CharacterLiteral:
5454     return cxstring::createRef("CharacterLiteral");
5455   case CXCursor_ParenExpr:
5456     return cxstring::createRef("ParenExpr");
5457   case CXCursor_UnaryOperator:
5458     return cxstring::createRef("UnaryOperator");
5459   case CXCursor_ArraySubscriptExpr:
5460     return cxstring::createRef("ArraySubscriptExpr");
5461   case CXCursor_OMPArraySectionExpr:
5462     return cxstring::createRef("OMPArraySectionExpr");
5463   case CXCursor_OMPArrayShapingExpr:
5464     return cxstring::createRef("OMPArrayShapingExpr");
5465   case CXCursor_OMPIteratorExpr:
5466     return cxstring::createRef("OMPIteratorExpr");
5467   case CXCursor_BinaryOperator:
5468     return cxstring::createRef("BinaryOperator");
5469   case CXCursor_CompoundAssignOperator:
5470     return cxstring::createRef("CompoundAssignOperator");
5471   case CXCursor_ConditionalOperator:
5472     return cxstring::createRef("ConditionalOperator");
5473   case CXCursor_CStyleCastExpr:
5474     return cxstring::createRef("CStyleCastExpr");
5475   case CXCursor_CompoundLiteralExpr:
5476     return cxstring::createRef("CompoundLiteralExpr");
5477   case CXCursor_InitListExpr:
5478     return cxstring::createRef("InitListExpr");
5479   case CXCursor_AddrLabelExpr:
5480     return cxstring::createRef("AddrLabelExpr");
5481   case CXCursor_StmtExpr:
5482     return cxstring::createRef("StmtExpr");
5483   case CXCursor_GenericSelectionExpr:
5484     return cxstring::createRef("GenericSelectionExpr");
5485   case CXCursor_GNUNullExpr:
5486     return cxstring::createRef("GNUNullExpr");
5487   case CXCursor_CXXStaticCastExpr:
5488     return cxstring::createRef("CXXStaticCastExpr");
5489   case CXCursor_CXXDynamicCastExpr:
5490     return cxstring::createRef("CXXDynamicCastExpr");
5491   case CXCursor_CXXReinterpretCastExpr:
5492     return cxstring::createRef("CXXReinterpretCastExpr");
5493   case CXCursor_CXXConstCastExpr:
5494     return cxstring::createRef("CXXConstCastExpr");
5495   case CXCursor_CXXFunctionalCastExpr:
5496     return cxstring::createRef("CXXFunctionalCastExpr");
5497   case CXCursor_CXXAddrspaceCastExpr:
5498     return cxstring::createRef("CXXAddrspaceCastExpr");
5499   case CXCursor_CXXTypeidExpr:
5500     return cxstring::createRef("CXXTypeidExpr");
5501   case CXCursor_CXXBoolLiteralExpr:
5502     return cxstring::createRef("CXXBoolLiteralExpr");
5503   case CXCursor_CXXNullPtrLiteralExpr:
5504     return cxstring::createRef("CXXNullPtrLiteralExpr");
5505   case CXCursor_CXXThisExpr:
5506     return cxstring::createRef("CXXThisExpr");
5507   case CXCursor_CXXThrowExpr:
5508     return cxstring::createRef("CXXThrowExpr");
5509   case CXCursor_CXXNewExpr:
5510     return cxstring::createRef("CXXNewExpr");
5511   case CXCursor_CXXDeleteExpr:
5512     return cxstring::createRef("CXXDeleteExpr");
5513   case CXCursor_UnaryExpr:
5514     return cxstring::createRef("UnaryExpr");
5515   case CXCursor_ObjCStringLiteral:
5516     return cxstring::createRef("ObjCStringLiteral");
5517   case CXCursor_ObjCBoolLiteralExpr:
5518     return cxstring::createRef("ObjCBoolLiteralExpr");
5519   case CXCursor_ObjCAvailabilityCheckExpr:
5520     return cxstring::createRef("ObjCAvailabilityCheckExpr");
5521   case CXCursor_ObjCSelfExpr:
5522     return cxstring::createRef("ObjCSelfExpr");
5523   case CXCursor_ObjCEncodeExpr:
5524     return cxstring::createRef("ObjCEncodeExpr");
5525   case CXCursor_ObjCSelectorExpr:
5526     return cxstring::createRef("ObjCSelectorExpr");
5527   case CXCursor_ObjCProtocolExpr:
5528     return cxstring::createRef("ObjCProtocolExpr");
5529   case CXCursor_ObjCBridgedCastExpr:
5530     return cxstring::createRef("ObjCBridgedCastExpr");
5531   case CXCursor_BlockExpr:
5532     return cxstring::createRef("BlockExpr");
5533   case CXCursor_PackExpansionExpr:
5534     return cxstring::createRef("PackExpansionExpr");
5535   case CXCursor_SizeOfPackExpr:
5536     return cxstring::createRef("SizeOfPackExpr");
5537   case CXCursor_LambdaExpr:
5538     return cxstring::createRef("LambdaExpr");
5539   case CXCursor_UnexposedExpr:
5540     return cxstring::createRef("UnexposedExpr");
5541   case CXCursor_DeclRefExpr:
5542     return cxstring::createRef("DeclRefExpr");
5543   case CXCursor_MemberRefExpr:
5544     return cxstring::createRef("MemberRefExpr");
5545   case CXCursor_CallExpr:
5546     return cxstring::createRef("CallExpr");
5547   case CXCursor_ObjCMessageExpr:
5548     return cxstring::createRef("ObjCMessageExpr");
5549   case CXCursor_BuiltinBitCastExpr:
5550     return cxstring::createRef("BuiltinBitCastExpr");
5551   case CXCursor_ConceptSpecializationExpr:
5552     return cxstring::createRef("ConceptSpecializationExpr");
5553   case CXCursor_RequiresExpr:
5554     return cxstring::createRef("RequiresExpr");
5555   case CXCursor_UnexposedStmt:
5556     return cxstring::createRef("UnexposedStmt");
5557   case CXCursor_DeclStmt:
5558     return cxstring::createRef("DeclStmt");
5559   case CXCursor_LabelStmt:
5560     return cxstring::createRef("LabelStmt");
5561   case CXCursor_CompoundStmt:
5562     return cxstring::createRef("CompoundStmt");
5563   case CXCursor_CaseStmt:
5564     return cxstring::createRef("CaseStmt");
5565   case CXCursor_DefaultStmt:
5566     return cxstring::createRef("DefaultStmt");
5567   case CXCursor_IfStmt:
5568     return cxstring::createRef("IfStmt");
5569   case CXCursor_SwitchStmt:
5570     return cxstring::createRef("SwitchStmt");
5571   case CXCursor_WhileStmt:
5572     return cxstring::createRef("WhileStmt");
5573   case CXCursor_DoStmt:
5574     return cxstring::createRef("DoStmt");
5575   case CXCursor_ForStmt:
5576     return cxstring::createRef("ForStmt");
5577   case CXCursor_GotoStmt:
5578     return cxstring::createRef("GotoStmt");
5579   case CXCursor_IndirectGotoStmt:
5580     return cxstring::createRef("IndirectGotoStmt");
5581   case CXCursor_ContinueStmt:
5582     return cxstring::createRef("ContinueStmt");
5583   case CXCursor_BreakStmt:
5584     return cxstring::createRef("BreakStmt");
5585   case CXCursor_ReturnStmt:
5586     return cxstring::createRef("ReturnStmt");
5587   case CXCursor_GCCAsmStmt:
5588     return cxstring::createRef("GCCAsmStmt");
5589   case CXCursor_MSAsmStmt:
5590     return cxstring::createRef("MSAsmStmt");
5591   case CXCursor_ObjCAtTryStmt:
5592     return cxstring::createRef("ObjCAtTryStmt");
5593   case CXCursor_ObjCAtCatchStmt:
5594     return cxstring::createRef("ObjCAtCatchStmt");
5595   case CXCursor_ObjCAtFinallyStmt:
5596     return cxstring::createRef("ObjCAtFinallyStmt");
5597   case CXCursor_ObjCAtThrowStmt:
5598     return cxstring::createRef("ObjCAtThrowStmt");
5599   case CXCursor_ObjCAtSynchronizedStmt:
5600     return cxstring::createRef("ObjCAtSynchronizedStmt");
5601   case CXCursor_ObjCAutoreleasePoolStmt:
5602     return cxstring::createRef("ObjCAutoreleasePoolStmt");
5603   case CXCursor_ObjCForCollectionStmt:
5604     return cxstring::createRef("ObjCForCollectionStmt");
5605   case CXCursor_CXXCatchStmt:
5606     return cxstring::createRef("CXXCatchStmt");
5607   case CXCursor_CXXTryStmt:
5608     return cxstring::createRef("CXXTryStmt");
5609   case CXCursor_CXXForRangeStmt:
5610     return cxstring::createRef("CXXForRangeStmt");
5611   case CXCursor_SEHTryStmt:
5612     return cxstring::createRef("SEHTryStmt");
5613   case CXCursor_SEHExceptStmt:
5614     return cxstring::createRef("SEHExceptStmt");
5615   case CXCursor_SEHFinallyStmt:
5616     return cxstring::createRef("SEHFinallyStmt");
5617   case CXCursor_SEHLeaveStmt:
5618     return cxstring::createRef("SEHLeaveStmt");
5619   case CXCursor_NullStmt:
5620     return cxstring::createRef("NullStmt");
5621   case CXCursor_InvalidFile:
5622     return cxstring::createRef("InvalidFile");
5623   case CXCursor_InvalidCode:
5624     return cxstring::createRef("InvalidCode");
5625   case CXCursor_NoDeclFound:
5626     return cxstring::createRef("NoDeclFound");
5627   case CXCursor_NotImplemented:
5628     return cxstring::createRef("NotImplemented");
5629   case CXCursor_TranslationUnit:
5630     return cxstring::createRef("TranslationUnit");
5631   case CXCursor_UnexposedAttr:
5632     return cxstring::createRef("UnexposedAttr");
5633   case CXCursor_IBActionAttr:
5634     return cxstring::createRef("attribute(ibaction)");
5635   case CXCursor_IBOutletAttr:
5636     return cxstring::createRef("attribute(iboutlet)");
5637   case CXCursor_IBOutletCollectionAttr:
5638     return cxstring::createRef("attribute(iboutletcollection)");
5639   case CXCursor_CXXFinalAttr:
5640     return cxstring::createRef("attribute(final)");
5641   case CXCursor_CXXOverrideAttr:
5642     return cxstring::createRef("attribute(override)");
5643   case CXCursor_AnnotateAttr:
5644     return cxstring::createRef("attribute(annotate)");
5645   case CXCursor_AsmLabelAttr:
5646     return cxstring::createRef("asm label");
5647   case CXCursor_PackedAttr:
5648     return cxstring::createRef("attribute(packed)");
5649   case CXCursor_PureAttr:
5650     return cxstring::createRef("attribute(pure)");
5651   case CXCursor_ConstAttr:
5652     return cxstring::createRef("attribute(const)");
5653   case CXCursor_NoDuplicateAttr:
5654     return cxstring::createRef("attribute(noduplicate)");
5655   case CXCursor_CUDAConstantAttr:
5656     return cxstring::createRef("attribute(constant)");
5657   case CXCursor_CUDADeviceAttr:
5658     return cxstring::createRef("attribute(device)");
5659   case CXCursor_CUDAGlobalAttr:
5660     return cxstring::createRef("attribute(global)");
5661   case CXCursor_CUDAHostAttr:
5662     return cxstring::createRef("attribute(host)");
5663   case CXCursor_CUDASharedAttr:
5664     return cxstring::createRef("attribute(shared)");
5665   case CXCursor_VisibilityAttr:
5666     return cxstring::createRef("attribute(visibility)");
5667   case CXCursor_DLLExport:
5668     return cxstring::createRef("attribute(dllexport)");
5669   case CXCursor_DLLImport:
5670     return cxstring::createRef("attribute(dllimport)");
5671   case CXCursor_NSReturnsRetained:
5672     return cxstring::createRef("attribute(ns_returns_retained)");
5673   case CXCursor_NSReturnsNotRetained:
5674     return cxstring::createRef("attribute(ns_returns_not_retained)");
5675   case CXCursor_NSReturnsAutoreleased:
5676     return cxstring::createRef("attribute(ns_returns_autoreleased)");
5677   case CXCursor_NSConsumesSelf:
5678     return cxstring::createRef("attribute(ns_consumes_self)");
5679   case CXCursor_NSConsumed:
5680     return cxstring::createRef("attribute(ns_consumed)");
5681   case CXCursor_ObjCException:
5682     return cxstring::createRef("attribute(objc_exception)");
5683   case CXCursor_ObjCNSObject:
5684     return cxstring::createRef("attribute(NSObject)");
5685   case CXCursor_ObjCIndependentClass:
5686     return cxstring::createRef("attribute(objc_independent_class)");
5687   case CXCursor_ObjCPreciseLifetime:
5688     return cxstring::createRef("attribute(objc_precise_lifetime)");
5689   case CXCursor_ObjCReturnsInnerPointer:
5690     return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5691   case CXCursor_ObjCRequiresSuper:
5692     return cxstring::createRef("attribute(objc_requires_super)");
5693   case CXCursor_ObjCRootClass:
5694     return cxstring::createRef("attribute(objc_root_class)");
5695   case CXCursor_ObjCSubclassingRestricted:
5696     return cxstring::createRef("attribute(objc_subclassing_restricted)");
5697   case CXCursor_ObjCExplicitProtocolImpl:
5698     return cxstring::createRef(
5699         "attribute(objc_protocol_requires_explicit_implementation)");
5700   case CXCursor_ObjCDesignatedInitializer:
5701     return cxstring::createRef("attribute(objc_designated_initializer)");
5702   case CXCursor_ObjCRuntimeVisible:
5703     return cxstring::createRef("attribute(objc_runtime_visible)");
5704   case CXCursor_ObjCBoxable:
5705     return cxstring::createRef("attribute(objc_boxable)");
5706   case CXCursor_FlagEnum:
5707     return cxstring::createRef("attribute(flag_enum)");
5708   case CXCursor_PreprocessingDirective:
5709     return cxstring::createRef("preprocessing directive");
5710   case CXCursor_MacroDefinition:
5711     return cxstring::createRef("macro definition");
5712   case CXCursor_MacroExpansion:
5713     return cxstring::createRef("macro expansion");
5714   case CXCursor_InclusionDirective:
5715     return cxstring::createRef("inclusion directive");
5716   case CXCursor_Namespace:
5717     return cxstring::createRef("Namespace");
5718   case CXCursor_LinkageSpec:
5719     return cxstring::createRef("LinkageSpec");
5720   case CXCursor_CXXBaseSpecifier:
5721     return cxstring::createRef("C++ base class specifier");
5722   case CXCursor_Constructor:
5723     return cxstring::createRef("CXXConstructor");
5724   case CXCursor_Destructor:
5725     return cxstring::createRef("CXXDestructor");
5726   case CXCursor_ConversionFunction:
5727     return cxstring::createRef("CXXConversion");
5728   case CXCursor_TemplateTypeParameter:
5729     return cxstring::createRef("TemplateTypeParameter");
5730   case CXCursor_NonTypeTemplateParameter:
5731     return cxstring::createRef("NonTypeTemplateParameter");
5732   case CXCursor_TemplateTemplateParameter:
5733     return cxstring::createRef("TemplateTemplateParameter");
5734   case CXCursor_FunctionTemplate:
5735     return cxstring::createRef("FunctionTemplate");
5736   case CXCursor_ClassTemplate:
5737     return cxstring::createRef("ClassTemplate");
5738   case CXCursor_ClassTemplatePartialSpecialization:
5739     return cxstring::createRef("ClassTemplatePartialSpecialization");
5740   case CXCursor_NamespaceAlias:
5741     return cxstring::createRef("NamespaceAlias");
5742   case CXCursor_UsingDirective:
5743     return cxstring::createRef("UsingDirective");
5744   case CXCursor_UsingDeclaration:
5745     return cxstring::createRef("UsingDeclaration");
5746   case CXCursor_TypeAliasDecl:
5747     return cxstring::createRef("TypeAliasDecl");
5748   case CXCursor_ObjCSynthesizeDecl:
5749     return cxstring::createRef("ObjCSynthesizeDecl");
5750   case CXCursor_ObjCDynamicDecl:
5751     return cxstring::createRef("ObjCDynamicDecl");
5752   case CXCursor_CXXAccessSpecifier:
5753     return cxstring::createRef("CXXAccessSpecifier");
5754   case CXCursor_ModuleImportDecl:
5755     return cxstring::createRef("ModuleImport");
5756   case CXCursor_OMPCanonicalLoop:
5757     return cxstring::createRef("OMPCanonicalLoop");
5758   case CXCursor_OMPMetaDirective:
5759     return cxstring::createRef("OMPMetaDirective");
5760   case CXCursor_OMPParallelDirective:
5761     return cxstring::createRef("OMPParallelDirective");
5762   case CXCursor_OMPSimdDirective:
5763     return cxstring::createRef("OMPSimdDirective");
5764   case CXCursor_OMPTileDirective:
5765     return cxstring::createRef("OMPTileDirective");
5766   case CXCursor_OMPUnrollDirective:
5767     return cxstring::createRef("OMPUnrollDirective");
5768   case CXCursor_OMPForDirective:
5769     return cxstring::createRef("OMPForDirective");
5770   case CXCursor_OMPForSimdDirective:
5771     return cxstring::createRef("OMPForSimdDirective");
5772   case CXCursor_OMPSectionsDirective:
5773     return cxstring::createRef("OMPSectionsDirective");
5774   case CXCursor_OMPSectionDirective:
5775     return cxstring::createRef("OMPSectionDirective");
5776   case CXCursor_OMPSingleDirective:
5777     return cxstring::createRef("OMPSingleDirective");
5778   case CXCursor_OMPMasterDirective:
5779     return cxstring::createRef("OMPMasterDirective");
5780   case CXCursor_OMPCriticalDirective:
5781     return cxstring::createRef("OMPCriticalDirective");
5782   case CXCursor_OMPParallelForDirective:
5783     return cxstring::createRef("OMPParallelForDirective");
5784   case CXCursor_OMPParallelForSimdDirective:
5785     return cxstring::createRef("OMPParallelForSimdDirective");
5786   case CXCursor_OMPParallelMasterDirective:
5787     return cxstring::createRef("OMPParallelMasterDirective");
5788   case CXCursor_OMPParallelMaskedDirective:
5789     return cxstring::createRef("OMPParallelMaskedDirective");
5790   case CXCursor_OMPParallelSectionsDirective:
5791     return cxstring::createRef("OMPParallelSectionsDirective");
5792   case CXCursor_OMPTaskDirective:
5793     return cxstring::createRef("OMPTaskDirective");
5794   case CXCursor_OMPTaskyieldDirective:
5795     return cxstring::createRef("OMPTaskyieldDirective");
5796   case CXCursor_OMPBarrierDirective:
5797     return cxstring::createRef("OMPBarrierDirective");
5798   case CXCursor_OMPTaskwaitDirective:
5799     return cxstring::createRef("OMPTaskwaitDirective");
5800   case CXCursor_OMPTaskgroupDirective:
5801     return cxstring::createRef("OMPTaskgroupDirective");
5802   case CXCursor_OMPFlushDirective:
5803     return cxstring::createRef("OMPFlushDirective");
5804   case CXCursor_OMPDepobjDirective:
5805     return cxstring::createRef("OMPDepobjDirective");
5806   case CXCursor_OMPScanDirective:
5807     return cxstring::createRef("OMPScanDirective");
5808   case CXCursor_OMPOrderedDirective:
5809     return cxstring::createRef("OMPOrderedDirective");
5810   case CXCursor_OMPAtomicDirective:
5811     return cxstring::createRef("OMPAtomicDirective");
5812   case CXCursor_OMPTargetDirective:
5813     return cxstring::createRef("OMPTargetDirective");
5814   case CXCursor_OMPTargetDataDirective:
5815     return cxstring::createRef("OMPTargetDataDirective");
5816   case CXCursor_OMPTargetEnterDataDirective:
5817     return cxstring::createRef("OMPTargetEnterDataDirective");
5818   case CXCursor_OMPTargetExitDataDirective:
5819     return cxstring::createRef("OMPTargetExitDataDirective");
5820   case CXCursor_OMPTargetParallelDirective:
5821     return cxstring::createRef("OMPTargetParallelDirective");
5822   case CXCursor_OMPTargetParallelForDirective:
5823     return cxstring::createRef("OMPTargetParallelForDirective");
5824   case CXCursor_OMPTargetUpdateDirective:
5825     return cxstring::createRef("OMPTargetUpdateDirective");
5826   case CXCursor_OMPTeamsDirective:
5827     return cxstring::createRef("OMPTeamsDirective");
5828   case CXCursor_OMPCancellationPointDirective:
5829     return cxstring::createRef("OMPCancellationPointDirective");
5830   case CXCursor_OMPCancelDirective:
5831     return cxstring::createRef("OMPCancelDirective");
5832   case CXCursor_OMPTaskLoopDirective:
5833     return cxstring::createRef("OMPTaskLoopDirective");
5834   case CXCursor_OMPTaskLoopSimdDirective:
5835     return cxstring::createRef("OMPTaskLoopSimdDirective");
5836   case CXCursor_OMPMasterTaskLoopDirective:
5837     return cxstring::createRef("OMPMasterTaskLoopDirective");
5838   case CXCursor_OMPMaskedTaskLoopDirective:
5839     return cxstring::createRef("OMPMaskedTaskLoopDirective");
5840   case CXCursor_OMPMasterTaskLoopSimdDirective:
5841     return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
5842   case CXCursor_OMPMaskedTaskLoopSimdDirective:
5843     return cxstring::createRef("OMPMaskedTaskLoopSimdDirective");
5844   case CXCursor_OMPParallelMasterTaskLoopDirective:
5845     return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
5846   case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5847     return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
5848   case CXCursor_OMPDistributeDirective:
5849     return cxstring::createRef("OMPDistributeDirective");
5850   case CXCursor_OMPDistributeParallelForDirective:
5851     return cxstring::createRef("OMPDistributeParallelForDirective");
5852   case CXCursor_OMPDistributeParallelForSimdDirective:
5853     return cxstring::createRef("OMPDistributeParallelForSimdDirective");
5854   case CXCursor_OMPDistributeSimdDirective:
5855     return cxstring::createRef("OMPDistributeSimdDirective");
5856   case CXCursor_OMPTargetParallelForSimdDirective:
5857     return cxstring::createRef("OMPTargetParallelForSimdDirective");
5858   case CXCursor_OMPTargetSimdDirective:
5859     return cxstring::createRef("OMPTargetSimdDirective");
5860   case CXCursor_OMPTeamsDistributeDirective:
5861     return cxstring::createRef("OMPTeamsDistributeDirective");
5862   case CXCursor_OMPTeamsDistributeSimdDirective:
5863     return cxstring::createRef("OMPTeamsDistributeSimdDirective");
5864   case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5865     return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
5866   case CXCursor_OMPTeamsDistributeParallelForDirective:
5867     return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
5868   case CXCursor_OMPTargetTeamsDirective:
5869     return cxstring::createRef("OMPTargetTeamsDirective");
5870   case CXCursor_OMPTargetTeamsDistributeDirective:
5871     return cxstring::createRef("OMPTargetTeamsDistributeDirective");
5872   case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5873     return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
5874   case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5875     return cxstring::createRef(
5876         "OMPTargetTeamsDistributeParallelForSimdDirective");
5877   case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5878     return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
5879   case CXCursor_OMPInteropDirective:
5880     return cxstring::createRef("OMPInteropDirective");
5881   case CXCursor_OMPDispatchDirective:
5882     return cxstring::createRef("OMPDispatchDirective");
5883   case CXCursor_OMPMaskedDirective:
5884     return cxstring::createRef("OMPMaskedDirective");
5885   case CXCursor_OMPGenericLoopDirective:
5886     return cxstring::createRef("OMPGenericLoopDirective");
5887   case CXCursor_OMPTeamsGenericLoopDirective:
5888     return cxstring::createRef("OMPTeamsGenericLoopDirective");
5889   case CXCursor_OMPTargetTeamsGenericLoopDirective:
5890     return cxstring::createRef("OMPTargetTeamsGenericLoopDirective");
5891   case CXCursor_OMPParallelGenericLoopDirective:
5892     return cxstring::createRef("OMPParallelGenericLoopDirective");
5893   case CXCursor_OMPTargetParallelGenericLoopDirective:
5894     return cxstring::createRef("OMPTargetParallelGenericLoopDirective");
5895   case CXCursor_OverloadCandidate:
5896     return cxstring::createRef("OverloadCandidate");
5897   case CXCursor_TypeAliasTemplateDecl:
5898     return cxstring::createRef("TypeAliasTemplateDecl");
5899   case CXCursor_StaticAssert:
5900     return cxstring::createRef("StaticAssert");
5901   case CXCursor_FriendDecl:
5902     return cxstring::createRef("FriendDecl");
5903   case CXCursor_ConvergentAttr:
5904     return cxstring::createRef("attribute(convergent)");
5905   case CXCursor_WarnUnusedAttr:
5906     return cxstring::createRef("attribute(warn_unused)");
5907   case CXCursor_WarnUnusedResultAttr:
5908     return cxstring::createRef("attribute(warn_unused_result)");
5909   case CXCursor_AlignedAttr:
5910     return cxstring::createRef("attribute(aligned)");
5911   case CXCursor_ConceptDecl:
5912     return cxstring::createRef("ConceptDecl");
5913   }
5914 
5915   llvm_unreachable("Unhandled CXCursorKind");
5916 }
5917 
5918 struct GetCursorData {
5919   SourceLocation TokenBeginLoc;
5920   bool PointsAtMacroArgExpansion;
5921   bool VisitedObjCPropertyImplDecl;
5922   SourceLocation VisitedDeclaratorDeclStartLoc;
5923   CXCursor &BestCursor;
5924 
5925   GetCursorData(SourceManager &SM, SourceLocation tokenBegin,
5926                 CXCursor &outputCursor)
5927       : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5928     PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5929     VisitedObjCPropertyImplDecl = false;
5930   }
5931 };
5932 
5933 static enum CXChildVisitResult
5934 GetCursorVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
5935   GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5936   CXCursor *BestCursor = &Data->BestCursor;
5937 
5938   // If we point inside a macro argument we should provide info of what the
5939   // token is so use the actual cursor, don't replace it with a macro expansion
5940   // cursor.
5941   if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5942     return CXChildVisit_Recurse;
5943 
5944   if (clang_isDeclaration(cursor.kind)) {
5945     // Avoid having the implicit methods override the property decls.
5946     if (const ObjCMethodDecl *MD =
5947             dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5948       if (MD->isImplicit())
5949         return CXChildVisit_Break;
5950 
5951     } else if (const ObjCInterfaceDecl *ID =
5952                    dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5953       // Check that when we have multiple @class references in the same line,
5954       // that later ones do not override the previous ones.
5955       // If we have:
5956       // @class Foo, Bar;
5957       // source ranges for both start at '@', so 'Bar' will end up overriding
5958       // 'Foo' even though the cursor location was at 'Foo'.
5959       if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5960           BestCursor->kind == CXCursor_ObjCClassRef)
5961         if (const ObjCInterfaceDecl *PrevID =
5962                 dyn_cast_or_null<ObjCInterfaceDecl>(
5963                     getCursorDecl(*BestCursor))) {
5964           if (PrevID != ID && !PrevID->isThisDeclarationADefinition() &&
5965               !ID->isThisDeclarationADefinition())
5966             return CXChildVisit_Break;
5967         }
5968 
5969     } else if (const DeclaratorDecl *DD =
5970                    dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5971       SourceLocation StartLoc = DD->getSourceRange().getBegin();
5972       // Check that when we have multiple declarators in the same line,
5973       // that later ones do not override the previous ones.
5974       // If we have:
5975       // int Foo, Bar;
5976       // source ranges for both start at 'int', so 'Bar' will end up overriding
5977       // 'Foo' even though the cursor location was at 'Foo'.
5978       if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5979         return CXChildVisit_Break;
5980       Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5981 
5982     } else if (const ObjCPropertyImplDecl *PropImp =
5983                    dyn_cast_or_null<ObjCPropertyImplDecl>(
5984                        getCursorDecl(cursor))) {
5985       (void)PropImp;
5986       // Check that when we have multiple @synthesize in the same line,
5987       // that later ones do not override the previous ones.
5988       // If we have:
5989       // @synthesize Foo, Bar;
5990       // source ranges for both start at '@', so 'Bar' will end up overriding
5991       // 'Foo' even though the cursor location was at 'Foo'.
5992       if (Data->VisitedObjCPropertyImplDecl)
5993         return CXChildVisit_Break;
5994       Data->VisitedObjCPropertyImplDecl = true;
5995     }
5996   }
5997 
5998   if (clang_isExpression(cursor.kind) &&
5999       clang_isDeclaration(BestCursor->kind)) {
6000     if (const Decl *D = getCursorDecl(*BestCursor)) {
6001       // Avoid having the cursor of an expression replace the declaration cursor
6002       // when the expression source range overlaps the declaration range.
6003       // This can happen for C++ constructor expressions whose range generally
6004       // include the variable declaration, e.g.:
6005       //  MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl
6006       //  cursor.
6007       if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
6008           D->getLocation() == Data->TokenBeginLoc)
6009         return CXChildVisit_Break;
6010     }
6011   }
6012 
6013   // If our current best cursor is the construction of a temporary object,
6014   // don't replace that cursor with a type reference, because we want
6015   // clang_getCursor() to point at the constructor.
6016   if (clang_isExpression(BestCursor->kind) &&
6017       isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
6018       cursor.kind == CXCursor_TypeRef) {
6019     // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
6020     // as having the actual point on the type reference.
6021     *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
6022     return CXChildVisit_Recurse;
6023   }
6024 
6025   // If we already have an Objective-C superclass reference, don't
6026   // update it further.
6027   if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
6028     return CXChildVisit_Break;
6029 
6030   *BestCursor = cursor;
6031   return CXChildVisit_Recurse;
6032 }
6033 
6034 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
6035   if (isNotUsableTU(TU)) {
6036     LOG_BAD_TU(TU);
6037     return clang_getNullCursor();
6038   }
6039 
6040   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6041   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6042 
6043   SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
6044   CXCursor Result = cxcursor::getCursor(TU, SLoc);
6045 
6046   LOG_FUNC_SECTION {
6047     CXFile SearchFile;
6048     unsigned SearchLine, SearchColumn;
6049     CXFile ResultFile;
6050     unsigned ResultLine, ResultColumn;
6051     CXString SearchFileName, ResultFileName, KindSpelling, USR;
6052     const char *IsDef = clang_isCursorDefinition(Result) ? " (Definition)" : "";
6053     CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
6054 
6055     clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
6056                           nullptr);
6057     clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine, &ResultColumn,
6058                           nullptr);
6059     SearchFileName = clang_getFileName(SearchFile);
6060     ResultFileName = clang_getFileName(ResultFile);
6061     KindSpelling = clang_getCursorKindSpelling(Result.kind);
6062     USR = clang_getCursorUSR(Result);
6063     *Log << llvm::format("(%s:%d:%d) = %s", clang_getCString(SearchFileName),
6064                          SearchLine, SearchColumn,
6065                          clang_getCString(KindSpelling))
6066          << llvm::format("(%s:%d:%d):%s%s", clang_getCString(ResultFileName),
6067                          ResultLine, ResultColumn, clang_getCString(USR),
6068                          IsDef);
6069     clang_disposeString(SearchFileName);
6070     clang_disposeString(ResultFileName);
6071     clang_disposeString(KindSpelling);
6072     clang_disposeString(USR);
6073 
6074     CXCursor Definition = clang_getCursorDefinition(Result);
6075     if (!clang_equalCursors(Definition, clang_getNullCursor())) {
6076       CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
6077       CXString DefinitionKindSpelling =
6078           clang_getCursorKindSpelling(Definition.kind);
6079       CXFile DefinitionFile;
6080       unsigned DefinitionLine, DefinitionColumn;
6081       clang_getFileLocation(DefinitionLoc, &DefinitionFile, &DefinitionLine,
6082                             &DefinitionColumn, nullptr);
6083       CXString DefinitionFileName = clang_getFileName(DefinitionFile);
6084       *Log << llvm::format("  -> %s(%s:%d:%d)",
6085                            clang_getCString(DefinitionKindSpelling),
6086                            clang_getCString(DefinitionFileName), DefinitionLine,
6087                            DefinitionColumn);
6088       clang_disposeString(DefinitionFileName);
6089       clang_disposeString(DefinitionKindSpelling);
6090     }
6091   }
6092 
6093   return Result;
6094 }
6095 
6096 CXCursor clang_getNullCursor(void) {
6097   return MakeCXCursorInvalid(CXCursor_InvalidFile);
6098 }
6099 
6100 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
6101   // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
6102   // can't set consistently. For example, when visiting a DeclStmt we will set
6103   // it but we don't set it on the result of clang_getCursorDefinition for
6104   // a reference of the same declaration.
6105   // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
6106   // when visiting a DeclStmt currently, the AST should be enhanced to be able
6107   // to provide that kind of info.
6108   if (clang_isDeclaration(X.kind))
6109     X.data[1] = nullptr;
6110   if (clang_isDeclaration(Y.kind))
6111     Y.data[1] = nullptr;
6112 
6113   return X == Y;
6114 }
6115 
6116 unsigned clang_hashCursor(CXCursor C) {
6117   unsigned Index = 0;
6118   if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
6119     Index = 1;
6120 
6121   return llvm::DenseMapInfo<std::pair<unsigned, const void *>>::getHashValue(
6122       std::make_pair(C.kind, C.data[Index]));
6123 }
6124 
6125 unsigned clang_isInvalid(enum CXCursorKind K) {
6126   return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
6127 }
6128 
6129 unsigned clang_isDeclaration(enum CXCursorKind K) {
6130   return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
6131          (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
6132 }
6133 
6134 unsigned clang_isInvalidDeclaration(CXCursor C) {
6135   if (clang_isDeclaration(C.kind)) {
6136     if (const Decl *D = getCursorDecl(C))
6137       return D->isInvalidDecl();
6138   }
6139 
6140   return 0;
6141 }
6142 
6143 unsigned clang_isReference(enum CXCursorKind K) {
6144   return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
6145 }
6146 
6147 unsigned clang_isExpression(enum CXCursorKind K) {
6148   return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
6149 }
6150 
6151 unsigned clang_isStatement(enum CXCursorKind K) {
6152   return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
6153 }
6154 
6155 unsigned clang_isAttribute(enum CXCursorKind K) {
6156   return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
6157 }
6158 
6159 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
6160   return K == CXCursor_TranslationUnit;
6161 }
6162 
6163 unsigned clang_isPreprocessing(enum CXCursorKind K) {
6164   return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
6165 }
6166 
6167 unsigned clang_isUnexposed(enum CXCursorKind K) {
6168   switch (K) {
6169   case CXCursor_UnexposedDecl:
6170   case CXCursor_UnexposedExpr:
6171   case CXCursor_UnexposedStmt:
6172   case CXCursor_UnexposedAttr:
6173     return true;
6174   default:
6175     return false;
6176   }
6177 }
6178 
6179 CXCursorKind clang_getCursorKind(CXCursor C) { return C.kind; }
6180 
6181 CXSourceLocation clang_getCursorLocation(CXCursor C) {
6182   if (clang_isReference(C.kind)) {
6183     switch (C.kind) {
6184     case CXCursor_ObjCSuperClassRef: {
6185       std::pair<const ObjCInterfaceDecl *, SourceLocation> P =
6186           getCursorObjCSuperClassRef(C);
6187       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6188     }
6189 
6190     case CXCursor_ObjCProtocolRef: {
6191       std::pair<const ObjCProtocolDecl *, SourceLocation> P =
6192           getCursorObjCProtocolRef(C);
6193       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6194     }
6195 
6196     case CXCursor_ObjCClassRef: {
6197       std::pair<const ObjCInterfaceDecl *, SourceLocation> P =
6198           getCursorObjCClassRef(C);
6199       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6200     }
6201 
6202     case CXCursor_TypeRef: {
6203       std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
6204       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6205     }
6206 
6207     case CXCursor_TemplateRef: {
6208       std::pair<const TemplateDecl *, SourceLocation> P =
6209           getCursorTemplateRef(C);
6210       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6211     }
6212 
6213     case CXCursor_NamespaceRef: {
6214       std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
6215       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6216     }
6217 
6218     case CXCursor_MemberRef: {
6219       std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
6220       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6221     }
6222 
6223     case CXCursor_VariableRef: {
6224       std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
6225       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6226     }
6227 
6228     case CXCursor_CXXBaseSpecifier: {
6229       const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
6230       if (!BaseSpec)
6231         return clang_getNullLocation();
6232 
6233       if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
6234         return cxloc::translateSourceLocation(
6235             getCursorContext(C), TSInfo->getTypeLoc().getBeginLoc());
6236 
6237       return cxloc::translateSourceLocation(getCursorContext(C),
6238                                             BaseSpec->getBeginLoc());
6239     }
6240 
6241     case CXCursor_LabelRef: {
6242       std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
6243       return cxloc::translateSourceLocation(getCursorContext(C), P.second);
6244     }
6245 
6246     case CXCursor_OverloadedDeclRef:
6247       return cxloc::translateSourceLocation(
6248           getCursorContext(C), getCursorOverloadedDeclRef(C).second);
6249 
6250     default:
6251       // FIXME: Need a way to enumerate all non-reference cases.
6252       llvm_unreachable("Missed a reference kind");
6253     }
6254   }
6255 
6256   if (clang_isExpression(C.kind))
6257     return cxloc::translateSourceLocation(
6258         getCursorContext(C), getLocationFromExpr(getCursorExpr(C)));
6259 
6260   if (clang_isStatement(C.kind))
6261     return cxloc::translateSourceLocation(getCursorContext(C),
6262                                           getCursorStmt(C)->getBeginLoc());
6263 
6264   if (C.kind == CXCursor_PreprocessingDirective) {
6265     SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
6266     return cxloc::translateSourceLocation(getCursorContext(C), L);
6267   }
6268 
6269   if (C.kind == CXCursor_MacroExpansion) {
6270     SourceLocation L =
6271         cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
6272     return cxloc::translateSourceLocation(getCursorContext(C), L);
6273   }
6274 
6275   if (C.kind == CXCursor_MacroDefinition) {
6276     SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
6277     return cxloc::translateSourceLocation(getCursorContext(C), L);
6278   }
6279 
6280   if (C.kind == CXCursor_InclusionDirective) {
6281     SourceLocation L =
6282         cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
6283     return cxloc::translateSourceLocation(getCursorContext(C), L);
6284   }
6285 
6286   if (clang_isAttribute(C.kind)) {
6287     SourceLocation L = cxcursor::getCursorAttr(C)->getLocation();
6288     return cxloc::translateSourceLocation(getCursorContext(C), L);
6289   }
6290 
6291   if (!clang_isDeclaration(C.kind))
6292     return clang_getNullLocation();
6293 
6294   const Decl *D = getCursorDecl(C);
6295   if (!D)
6296     return clang_getNullLocation();
6297 
6298   SourceLocation Loc = D->getLocation();
6299   // FIXME: Multiple variables declared in a single declaration
6300   // currently lack the information needed to correctly determine their
6301   // ranges when accounting for the type-specifier.  We use context
6302   // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6303   // and if so, whether it is the first decl.
6304   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6305     if (!cxcursor::isFirstInDeclGroup(C))
6306       Loc = VD->getLocation();
6307   }
6308 
6309   // For ObjC methods, give the start location of the method name.
6310   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6311     Loc = MD->getSelectorStartLoc();
6312 
6313   return cxloc::translateSourceLocation(getCursorContext(C), Loc);
6314 }
6315 
6316 } // end extern "C"
6317 
6318 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
6319   assert(TU);
6320 
6321   // Guard against an invalid SourceLocation, or we may assert in one
6322   // of the following calls.
6323   if (SLoc.isInvalid())
6324     return clang_getNullCursor();
6325 
6326   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6327 
6328   // Translate the given source location to make it point at the beginning of
6329   // the token under the cursor.
6330   SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
6331                                     CXXUnit->getASTContext().getLangOpts());
6332 
6333   CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
6334   if (SLoc.isValid()) {
6335     GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
6336     CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
6337                             /*VisitPreprocessorLast=*/true,
6338                             /*VisitIncludedEntities=*/false,
6339                             SourceLocation(SLoc));
6340     CursorVis.visitFileRegion();
6341   }
6342 
6343   return Result;
6344 }
6345 
6346 static SourceRange getRawCursorExtent(CXCursor C) {
6347   if (clang_isReference(C.kind)) {
6348     switch (C.kind) {
6349     case CXCursor_ObjCSuperClassRef:
6350       return getCursorObjCSuperClassRef(C).second;
6351 
6352     case CXCursor_ObjCProtocolRef:
6353       return getCursorObjCProtocolRef(C).second;
6354 
6355     case CXCursor_ObjCClassRef:
6356       return getCursorObjCClassRef(C).second;
6357 
6358     case CXCursor_TypeRef:
6359       return getCursorTypeRef(C).second;
6360 
6361     case CXCursor_TemplateRef:
6362       return getCursorTemplateRef(C).second;
6363 
6364     case CXCursor_NamespaceRef:
6365       return getCursorNamespaceRef(C).second;
6366 
6367     case CXCursor_MemberRef:
6368       return getCursorMemberRef(C).second;
6369 
6370     case CXCursor_CXXBaseSpecifier:
6371       return getCursorCXXBaseSpecifier(C)->getSourceRange();
6372 
6373     case CXCursor_LabelRef:
6374       return getCursorLabelRef(C).second;
6375 
6376     case CXCursor_OverloadedDeclRef:
6377       return getCursorOverloadedDeclRef(C).second;
6378 
6379     case CXCursor_VariableRef:
6380       return getCursorVariableRef(C).second;
6381 
6382     default:
6383       // FIXME: Need a way to enumerate all non-reference cases.
6384       llvm_unreachable("Missed a reference kind");
6385     }
6386   }
6387 
6388   if (clang_isExpression(C.kind))
6389     return getCursorExpr(C)->getSourceRange();
6390 
6391   if (clang_isStatement(C.kind))
6392     return getCursorStmt(C)->getSourceRange();
6393 
6394   if (clang_isAttribute(C.kind))
6395     return getCursorAttr(C)->getRange();
6396 
6397   if (C.kind == CXCursor_PreprocessingDirective)
6398     return cxcursor::getCursorPreprocessingDirective(C);
6399 
6400   if (C.kind == CXCursor_MacroExpansion) {
6401     ASTUnit *TU = getCursorASTUnit(C);
6402     SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
6403     return TU->mapRangeFromPreamble(Range);
6404   }
6405 
6406   if (C.kind == CXCursor_MacroDefinition) {
6407     ASTUnit *TU = getCursorASTUnit(C);
6408     SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6409     return TU->mapRangeFromPreamble(Range);
6410   }
6411 
6412   if (C.kind == CXCursor_InclusionDirective) {
6413     ASTUnit *TU = getCursorASTUnit(C);
6414     SourceRange Range =
6415         cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6416     return TU->mapRangeFromPreamble(Range);
6417   }
6418 
6419   if (C.kind == CXCursor_TranslationUnit) {
6420     ASTUnit *TU = getCursorASTUnit(C);
6421     FileID MainID = TU->getSourceManager().getMainFileID();
6422     SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6423     SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6424     return SourceRange(Start, End);
6425   }
6426 
6427   if (clang_isDeclaration(C.kind)) {
6428     const Decl *D = cxcursor::getCursorDecl(C);
6429     if (!D)
6430       return SourceRange();
6431 
6432     SourceRange R = D->getSourceRange();
6433     // FIXME: Multiple variables declared in a single declaration
6434     // currently lack the information needed to correctly determine their
6435     // ranges when accounting for the type-specifier.  We use context
6436     // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6437     // and if so, whether it is the first decl.
6438     if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6439       if (!cxcursor::isFirstInDeclGroup(C))
6440         R.setBegin(VD->getLocation());
6441     }
6442     return R;
6443   }
6444   return SourceRange();
6445 }
6446 
6447 /// Retrieves the "raw" cursor extent, which is then extended to include
6448 /// the decl-specifier-seq for declarations.
6449 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6450   if (clang_isDeclaration(C.kind)) {
6451     const Decl *D = cxcursor::getCursorDecl(C);
6452     if (!D)
6453       return SourceRange();
6454 
6455     SourceRange R = D->getSourceRange();
6456 
6457     // Adjust the start of the location for declarations preceded by
6458     // declaration specifiers.
6459     SourceLocation StartLoc;
6460     if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6461       if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
6462         StartLoc = TI->getTypeLoc().getBeginLoc();
6463     } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
6464       if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
6465         StartLoc = TI->getTypeLoc().getBeginLoc();
6466     }
6467 
6468     if (StartLoc.isValid() && R.getBegin().isValid() &&
6469         SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6470       R.setBegin(StartLoc);
6471 
6472     // FIXME: Multiple variables declared in a single declaration
6473     // currently lack the information needed to correctly determine their
6474     // ranges when accounting for the type-specifier.  We use context
6475     // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6476     // and if so, whether it is the first decl.
6477     if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6478       if (!cxcursor::isFirstInDeclGroup(C))
6479         R.setBegin(VD->getLocation());
6480     }
6481 
6482     return R;
6483   }
6484 
6485   return getRawCursorExtent(C);
6486 }
6487 
6488 CXSourceRange clang_getCursorExtent(CXCursor C) {
6489   SourceRange R = getRawCursorExtent(C);
6490   if (R.isInvalid())
6491     return clang_getNullRange();
6492 
6493   return cxloc::translateSourceRange(getCursorContext(C), R);
6494 }
6495 
6496 CXCursor clang_getCursorReferenced(CXCursor C) {
6497   if (clang_isInvalid(C.kind))
6498     return clang_getNullCursor();
6499 
6500   CXTranslationUnit tu = getCursorTU(C);
6501   if (clang_isDeclaration(C.kind)) {
6502     const Decl *D = getCursorDecl(C);
6503     if (!D)
6504       return clang_getNullCursor();
6505     if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
6506       return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
6507     if (const ObjCPropertyImplDecl *PropImpl =
6508             dyn_cast<ObjCPropertyImplDecl>(D))
6509       if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6510         return MakeCXCursor(Property, tu);
6511 
6512     return C;
6513   }
6514 
6515   if (clang_isExpression(C.kind)) {
6516     const Expr *E = getCursorExpr(C);
6517     const Decl *D = getDeclFromExpr(E);
6518     if (D) {
6519       CXCursor declCursor = MakeCXCursor(D, tu);
6520       declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6521                                                declCursor);
6522       return declCursor;
6523     }
6524 
6525     if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
6526       return MakeCursorOverloadedDeclRef(Ovl, tu);
6527 
6528     return clang_getNullCursor();
6529   }
6530 
6531   if (clang_isStatement(C.kind)) {
6532     const Stmt *S = getCursorStmt(C);
6533     if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
6534       if (LabelDecl *label = Goto->getLabel())
6535         if (LabelStmt *labelS = label->getStmt())
6536           return MakeCXCursor(labelS, getCursorDecl(C), tu);
6537 
6538     return clang_getNullCursor();
6539   }
6540 
6541   if (C.kind == CXCursor_MacroExpansion) {
6542     if (const MacroDefinitionRecord *Def =
6543             getCursorMacroExpansion(C).getDefinition())
6544       return MakeMacroDefinitionCursor(Def, tu);
6545   }
6546 
6547   if (!clang_isReference(C.kind))
6548     return clang_getNullCursor();
6549 
6550   switch (C.kind) {
6551   case CXCursor_ObjCSuperClassRef:
6552     return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6553 
6554   case CXCursor_ObjCProtocolRef: {
6555     const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6556     if (const ObjCProtocolDecl *Def = Prot->getDefinition())
6557       return MakeCXCursor(Def, tu);
6558 
6559     return MakeCXCursor(Prot, tu);
6560   }
6561 
6562   case CXCursor_ObjCClassRef: {
6563     const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6564     if (const ObjCInterfaceDecl *Def = Class->getDefinition())
6565       return MakeCXCursor(Def, tu);
6566 
6567     return MakeCXCursor(Class, tu);
6568   }
6569 
6570   case CXCursor_TypeRef:
6571     return MakeCXCursor(getCursorTypeRef(C).first, tu);
6572 
6573   case CXCursor_TemplateRef:
6574     return MakeCXCursor(getCursorTemplateRef(C).first, tu);
6575 
6576   case CXCursor_NamespaceRef:
6577     return MakeCXCursor(getCursorNamespaceRef(C).first, tu);
6578 
6579   case CXCursor_MemberRef:
6580     return MakeCXCursor(getCursorMemberRef(C).first, tu);
6581 
6582   case CXCursor_CXXBaseSpecifier: {
6583     const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
6584     return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), tu));
6585   }
6586 
6587   case CXCursor_LabelRef:
6588     // FIXME: We end up faking the "parent" declaration here because we
6589     // don't want to make CXCursor larger.
6590     return MakeCXCursor(
6591         getCursorLabelRef(C).first,
6592         cxtu::getASTUnit(tu)->getASTContext().getTranslationUnitDecl(), tu);
6593 
6594   case CXCursor_OverloadedDeclRef:
6595     return C;
6596 
6597   case CXCursor_VariableRef:
6598     return MakeCXCursor(getCursorVariableRef(C).first, tu);
6599 
6600   default:
6601     // We would prefer to enumerate all non-reference cursor kinds here.
6602     llvm_unreachable("Unhandled reference cursor kind");
6603   }
6604 }
6605 
6606 CXCursor clang_getCursorDefinition(CXCursor C) {
6607   if (clang_isInvalid(C.kind))
6608     return clang_getNullCursor();
6609 
6610   CXTranslationUnit TU = getCursorTU(C);
6611 
6612   bool WasReference = false;
6613   if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6614     C = clang_getCursorReferenced(C);
6615     WasReference = true;
6616   }
6617 
6618   if (C.kind == CXCursor_MacroExpansion)
6619     return clang_getCursorReferenced(C);
6620 
6621   if (!clang_isDeclaration(C.kind))
6622     return clang_getNullCursor();
6623 
6624   const Decl *D = getCursorDecl(C);
6625   if (!D)
6626     return clang_getNullCursor();
6627 
6628   switch (D->getKind()) {
6629   // Declaration kinds that don't really separate the notions of
6630   // declaration and definition.
6631   case Decl::Namespace:
6632   case Decl::Typedef:
6633   case Decl::TypeAlias:
6634   case Decl::TypeAliasTemplate:
6635   case Decl::TemplateTypeParm:
6636   case Decl::EnumConstant:
6637   case Decl::Field:
6638   case Decl::Binding:
6639   case Decl::MSProperty:
6640   case Decl::MSGuid:
6641   case Decl::UnnamedGlobalConstant:
6642   case Decl::TemplateParamObject:
6643   case Decl::IndirectField:
6644   case Decl::ObjCIvar:
6645   case Decl::ObjCAtDefsField:
6646   case Decl::ImplicitParam:
6647   case Decl::ParmVar:
6648   case Decl::NonTypeTemplateParm:
6649   case Decl::TemplateTemplateParm:
6650   case Decl::ObjCCategoryImpl:
6651   case Decl::ObjCImplementation:
6652   case Decl::AccessSpec:
6653   case Decl::LinkageSpec:
6654   case Decl::Export:
6655   case Decl::ObjCPropertyImpl:
6656   case Decl::FileScopeAsm:
6657   case Decl::StaticAssert:
6658   case Decl::Block:
6659   case Decl::Captured:
6660   case Decl::OMPCapturedExpr:
6661   case Decl::Label: // FIXME: Is this right??
6662   case Decl::ClassScopeFunctionSpecialization:
6663   case Decl::CXXDeductionGuide:
6664   case Decl::Import:
6665   case Decl::OMPThreadPrivate:
6666   case Decl::OMPAllocate:
6667   case Decl::OMPDeclareReduction:
6668   case Decl::OMPDeclareMapper:
6669   case Decl::OMPRequires:
6670   case Decl::ObjCTypeParam:
6671   case Decl::BuiltinTemplate:
6672   case Decl::PragmaComment:
6673   case Decl::PragmaDetectMismatch:
6674   case Decl::UsingPack:
6675   case Decl::Concept:
6676   case Decl::LifetimeExtendedTemporary:
6677   case Decl::RequiresExprBody:
6678   case Decl::UnresolvedUsingIfExists:
6679     return C;
6680 
6681   // Declaration kinds that don't make any sense here, but are
6682   // nonetheless harmless.
6683   case Decl::Empty:
6684   case Decl::TranslationUnit:
6685   case Decl::ExternCContext:
6686     break;
6687 
6688   // Declaration kinds for which the definition is not resolvable.
6689   case Decl::UnresolvedUsingTypename:
6690   case Decl::UnresolvedUsingValue:
6691     break;
6692 
6693   case Decl::UsingDirective:
6694     return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6695                         TU);
6696 
6697   case Decl::NamespaceAlias:
6698     return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6699 
6700   case Decl::Enum:
6701   case Decl::Record:
6702   case Decl::CXXRecord:
6703   case Decl::ClassTemplateSpecialization:
6704   case Decl::ClassTemplatePartialSpecialization:
6705     if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6706       return MakeCXCursor(Def, TU);
6707     return clang_getNullCursor();
6708 
6709   case Decl::Function:
6710   case Decl::CXXMethod:
6711   case Decl::CXXConstructor:
6712   case Decl::CXXDestructor:
6713   case Decl::CXXConversion: {
6714     const FunctionDecl *Def = nullptr;
6715     if (cast<FunctionDecl>(D)->getBody(Def))
6716       return MakeCXCursor(Def, TU);
6717     return clang_getNullCursor();
6718   }
6719 
6720   case Decl::Var:
6721   case Decl::VarTemplateSpecialization:
6722   case Decl::VarTemplatePartialSpecialization:
6723   case Decl::Decomposition: {
6724     // Ask the variable if it has a definition.
6725     if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
6726       return MakeCXCursor(Def, TU);
6727     return clang_getNullCursor();
6728   }
6729 
6730   case Decl::FunctionTemplate: {
6731     const FunctionDecl *Def = nullptr;
6732     if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6733       return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6734     return clang_getNullCursor();
6735   }
6736 
6737   case Decl::ClassTemplate: {
6738     if (RecordDecl *Def =
6739             cast<ClassTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6740       return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6741                           TU);
6742     return clang_getNullCursor();
6743   }
6744 
6745   case Decl::VarTemplate: {
6746     if (VarDecl *Def =
6747             cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6748       return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6749     return clang_getNullCursor();
6750   }
6751 
6752   case Decl::Using:
6753   case Decl::UsingEnum:
6754     return MakeCursorOverloadedDeclRef(cast<BaseUsingDecl>(D), D->getLocation(),
6755                                        TU);
6756 
6757   case Decl::UsingShadow:
6758   case Decl::ConstructorUsingShadow:
6759     return clang_getCursorDefinition(
6760         MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), TU));
6761 
6762   case Decl::ObjCMethod: {
6763     const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
6764     if (Method->isThisDeclarationADefinition())
6765       return C;
6766 
6767     // Dig out the method definition in the associated
6768     // @implementation, if we have it.
6769     // FIXME: The ASTs should make finding the definition easier.
6770     if (const ObjCInterfaceDecl *Class =
6771             dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6772       if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6773         if (ObjCMethodDecl *Def = ClassImpl->getMethod(
6774                 Method->getSelector(), Method->isInstanceMethod()))
6775           if (Def->isThisDeclarationADefinition())
6776             return MakeCXCursor(Def, TU);
6777 
6778     return clang_getNullCursor();
6779   }
6780 
6781   case Decl::ObjCCategory:
6782     if (ObjCCategoryImplDecl *Impl =
6783             cast<ObjCCategoryDecl>(D)->getImplementation())
6784       return MakeCXCursor(Impl, TU);
6785     return clang_getNullCursor();
6786 
6787   case Decl::ObjCProtocol:
6788     if (const ObjCProtocolDecl *Def =
6789             cast<ObjCProtocolDecl>(D)->getDefinition())
6790       return MakeCXCursor(Def, TU);
6791     return clang_getNullCursor();
6792 
6793   case Decl::ObjCInterface: {
6794     // There are two notions of a "definition" for an Objective-C
6795     // class: the interface and its implementation. When we resolved a
6796     // reference to an Objective-C class, produce the @interface as
6797     // the definition; when we were provided with the interface,
6798     // produce the @implementation as the definition.
6799     const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
6800     if (WasReference) {
6801       if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
6802         return MakeCXCursor(Def, TU);
6803     } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6804       return MakeCXCursor(Impl, TU);
6805     return clang_getNullCursor();
6806   }
6807 
6808   case Decl::ObjCProperty:
6809     // FIXME: We don't really know where to find the
6810     // ObjCPropertyImplDecls that implement this property.
6811     return clang_getNullCursor();
6812 
6813   case Decl::ObjCCompatibleAlias:
6814     if (const ObjCInterfaceDecl *Class =
6815             cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
6816       if (const ObjCInterfaceDecl *Def = Class->getDefinition())
6817         return MakeCXCursor(Def, TU);
6818 
6819     return clang_getNullCursor();
6820 
6821   case Decl::Friend:
6822     if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6823       return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6824     return clang_getNullCursor();
6825 
6826   case Decl::FriendTemplate:
6827     if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6828       return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6829     return clang_getNullCursor();
6830   }
6831 
6832   return clang_getNullCursor();
6833 }
6834 
6835 unsigned clang_isCursorDefinition(CXCursor C) {
6836   if (!clang_isDeclaration(C.kind))
6837     return 0;
6838 
6839   return clang_getCursorDefinition(C) == C;
6840 }
6841 
6842 CXCursor clang_getCanonicalCursor(CXCursor C) {
6843   if (!clang_isDeclaration(C.kind))
6844     return C;
6845 
6846   if (const Decl *D = getCursorDecl(C)) {
6847     if (const ObjCCategoryImplDecl *CatImplD =
6848             dyn_cast<ObjCCategoryImplDecl>(D))
6849       if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6850         return MakeCXCursor(CatD, getCursorTU(C));
6851 
6852     if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6853       if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
6854         return MakeCXCursor(IFD, getCursorTU(C));
6855 
6856     return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6857   }
6858 
6859   return C;
6860 }
6861 
6862 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6863   return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6864 }
6865 
6866 unsigned clang_getNumOverloadedDecls(CXCursor C) {
6867   if (C.kind != CXCursor_OverloadedDeclRef)
6868     return 0;
6869 
6870   OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
6871   if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
6872     return E->getNumDecls();
6873 
6874   if (OverloadedTemplateStorage *S =
6875           Storage.dyn_cast<OverloadedTemplateStorage *>())
6876     return S->size();
6877 
6878   const Decl *D = Storage.get<const Decl *>();
6879   if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
6880     return Using->shadow_size();
6881 
6882   return 0;
6883 }
6884 
6885 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6886   if (cursor.kind != CXCursor_OverloadedDeclRef)
6887     return clang_getNullCursor();
6888 
6889   if (index >= clang_getNumOverloadedDecls(cursor))
6890     return clang_getNullCursor();
6891 
6892   CXTranslationUnit TU = getCursorTU(cursor);
6893   OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
6894   if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
6895     return MakeCXCursor(E->decls_begin()[index], TU);
6896 
6897   if (OverloadedTemplateStorage *S =
6898           Storage.dyn_cast<OverloadedTemplateStorage *>())
6899     return MakeCXCursor(S->begin()[index], TU);
6900 
6901   const Decl *D = Storage.get<const Decl *>();
6902   if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
6903     // FIXME: This is, unfortunately, linear time.
6904     UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6905     std::advance(Pos, index);
6906     return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6907   }
6908 
6909   return clang_getNullCursor();
6910 }
6911 
6912 void clang_getDefinitionSpellingAndExtent(
6913     CXCursor C, const char **startBuf, const char **endBuf, unsigned *startLine,
6914     unsigned *startColumn, unsigned *endLine, unsigned *endColumn) {
6915   assert(getCursorDecl(C) && "CXCursor has null decl");
6916   const auto *FD = cast<FunctionDecl>(getCursorDecl(C));
6917   const auto *Body = cast<CompoundStmt>(FD->getBody());
6918 
6919   SourceManager &SM = FD->getASTContext().getSourceManager();
6920   *startBuf = SM.getCharacterData(Body->getLBracLoc());
6921   *endBuf = SM.getCharacterData(Body->getRBracLoc());
6922   *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6923   *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6924   *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6925   *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6926 }
6927 
6928 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6929                                                 unsigned PieceIndex) {
6930   RefNamePieces Pieces;
6931 
6932   switch (C.kind) {
6933   case CXCursor_MemberRefExpr:
6934     if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
6935       Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6936                            E->getQualifierLoc().getSourceRange());
6937     break;
6938 
6939   case CXCursor_DeclRefExpr:
6940     if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6941       SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6942       Pieces =
6943           buildPieces(NameFlags, false, E->getNameInfo(),
6944                       E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6945     }
6946     break;
6947 
6948   case CXCursor_CallExpr:
6949     if (const CXXOperatorCallExpr *OCE =
6950             dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
6951       const Expr *Callee = OCE->getCallee();
6952       if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
6953         Callee = ICE->getSubExpr();
6954 
6955       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
6956         Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6957                              DRE->getQualifierLoc().getSourceRange());
6958     }
6959     break;
6960 
6961   default:
6962     break;
6963   }
6964 
6965   if (Pieces.empty()) {
6966     if (PieceIndex == 0)
6967       return clang_getCursorExtent(C);
6968   } else if (PieceIndex < Pieces.size()) {
6969     SourceRange R = Pieces[PieceIndex];
6970     if (R.isValid())
6971       return cxloc::translateSourceRange(getCursorContext(C), R);
6972   }
6973 
6974   return clang_getNullRange();
6975 }
6976 
6977 void clang_enableStackTraces(void) {
6978   // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6979   llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
6980 }
6981 
6982 void clang_executeOnThread(void (*fn)(void *), void *user_data,
6983                            unsigned stack_size) {
6984   llvm::thread Thread(stack_size == 0 ? clang::DesiredStackSize
6985                                       : llvm::Optional<unsigned>(stack_size),
6986                       fn, user_data);
6987   Thread.join();
6988 }
6989 
6990 //===----------------------------------------------------------------------===//
6991 // Token-based Operations.
6992 //===----------------------------------------------------------------------===//
6993 
6994 /* CXToken layout:
6995  *   int_data[0]: a CXTokenKind
6996  *   int_data[1]: starting token location
6997  *   int_data[2]: token length
6998  *   int_data[3]: reserved
6999  *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
7000  *   otherwise unused.
7001  */
7002 CXTokenKind clang_getTokenKind(CXToken CXTok) {
7003   return static_cast<CXTokenKind>(CXTok.int_data[0]);
7004 }
7005 
7006 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
7007   switch (clang_getTokenKind(CXTok)) {
7008   case CXToken_Identifier:
7009   case CXToken_Keyword:
7010     // We know we have an IdentifierInfo*, so use that.
7011     return cxstring::createRef(
7012         static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
7013 
7014   case CXToken_Literal: {
7015     // We have stashed the starting pointer in the ptr_data field. Use it.
7016     const char *Text = static_cast<const char *>(CXTok.ptr_data);
7017     return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
7018   }
7019 
7020   case CXToken_Punctuation:
7021   case CXToken_Comment:
7022     break;
7023   }
7024 
7025   if (isNotUsableTU(TU)) {
7026     LOG_BAD_TU(TU);
7027     return cxstring::createEmpty();
7028   }
7029 
7030   // We have to find the starting buffer pointer the hard way, by
7031   // deconstructing the source location.
7032   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7033   if (!CXXUnit)
7034     return cxstring::createEmpty();
7035 
7036   SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
7037   std::pair<FileID, unsigned> LocInfo =
7038       CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
7039   bool Invalid = false;
7040   StringRef Buffer =
7041       CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
7042   if (Invalid)
7043     return cxstring::createEmpty();
7044 
7045   return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
7046 }
7047 
7048 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
7049   if (isNotUsableTU(TU)) {
7050     LOG_BAD_TU(TU);
7051     return clang_getNullLocation();
7052   }
7053 
7054   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7055   if (!CXXUnit)
7056     return clang_getNullLocation();
7057 
7058   return cxloc::translateSourceLocation(
7059       CXXUnit->getASTContext(),
7060       SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
7061 }
7062 
7063 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
7064   if (isNotUsableTU(TU)) {
7065     LOG_BAD_TU(TU);
7066     return clang_getNullRange();
7067   }
7068 
7069   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7070   if (!CXXUnit)
7071     return clang_getNullRange();
7072 
7073   return cxloc::translateSourceRange(
7074       CXXUnit->getASTContext(),
7075       SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
7076 }
7077 
7078 static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
7079                       SmallVectorImpl<CXToken> &CXTokens) {
7080   SourceManager &SourceMgr = CXXUnit->getSourceManager();
7081   std::pair<FileID, unsigned> BeginLocInfo =
7082       SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
7083   std::pair<FileID, unsigned> EndLocInfo =
7084       SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
7085 
7086   // Cannot tokenize across files.
7087   if (BeginLocInfo.first != EndLocInfo.first)
7088     return;
7089 
7090   // Create a lexer
7091   bool Invalid = false;
7092   StringRef Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7093   if (Invalid)
7094     return;
7095 
7096   Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7097             CXXUnit->getASTContext().getLangOpts(), Buffer.begin(),
7098             Buffer.data() + BeginLocInfo.second, Buffer.end());
7099   Lex.SetCommentRetentionState(true);
7100 
7101   // Lex tokens until we hit the end of the range.
7102   const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
7103   Token Tok;
7104   bool previousWasAt = false;
7105   do {
7106     // Lex the next token
7107     Lex.LexFromRawLexer(Tok);
7108     if (Tok.is(tok::eof))
7109       break;
7110 
7111     // Initialize the CXToken.
7112     CXToken CXTok;
7113 
7114     //   - Common fields
7115     CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
7116     CXTok.int_data[2] = Tok.getLength();
7117     CXTok.int_data[3] = 0;
7118 
7119     //   - Kind-specific fields
7120     if (Tok.isLiteral()) {
7121       CXTok.int_data[0] = CXToken_Literal;
7122       CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
7123     } else if (Tok.is(tok::raw_identifier)) {
7124       // Lookup the identifier to determine whether we have a keyword.
7125       IdentifierInfo *II = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
7126 
7127       if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
7128         CXTok.int_data[0] = CXToken_Keyword;
7129       } else {
7130         CXTok.int_data[0] =
7131             Tok.is(tok::identifier) ? CXToken_Identifier : CXToken_Keyword;
7132       }
7133       CXTok.ptr_data = II;
7134     } else if (Tok.is(tok::comment)) {
7135       CXTok.int_data[0] = CXToken_Comment;
7136       CXTok.ptr_data = nullptr;
7137     } else {
7138       CXTok.int_data[0] = CXToken_Punctuation;
7139       CXTok.ptr_data = nullptr;
7140     }
7141     CXTokens.push_back(CXTok);
7142     previousWasAt = Tok.is(tok::at);
7143   } while (Lex.getBufferLocation() < EffectiveBufferEnd);
7144 }
7145 
7146 CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
7147   LOG_FUNC_SECTION { *Log << TU << ' ' << Location; }
7148 
7149   if (isNotUsableTU(TU)) {
7150     LOG_BAD_TU(TU);
7151     return nullptr;
7152   }
7153 
7154   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7155   if (!CXXUnit)
7156     return nullptr;
7157 
7158   SourceLocation Begin = cxloc::translateSourceLocation(Location);
7159   if (Begin.isInvalid())
7160     return nullptr;
7161   SourceManager &SM = CXXUnit->getSourceManager();
7162   std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
7163   DecomposedEnd.second +=
7164       Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
7165 
7166   SourceLocation End =
7167       SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
7168 
7169   SmallVector<CXToken, 32> CXTokens;
7170   getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
7171 
7172   if (CXTokens.empty())
7173     return nullptr;
7174 
7175   CXTokens.resize(1);
7176   CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
7177 
7178   memmove(Token, CXTokens.data(), sizeof(CXToken));
7179   return Token;
7180 }
7181 
7182 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, CXToken **Tokens,
7183                     unsigned *NumTokens) {
7184   LOG_FUNC_SECTION { *Log << TU << ' ' << Range; }
7185 
7186   if (Tokens)
7187     *Tokens = nullptr;
7188   if (NumTokens)
7189     *NumTokens = 0;
7190 
7191   if (isNotUsableTU(TU)) {
7192     LOG_BAD_TU(TU);
7193     return;
7194   }
7195 
7196   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7197   if (!CXXUnit || !Tokens || !NumTokens)
7198     return;
7199 
7200   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
7201 
7202   SourceRange R = cxloc::translateCXSourceRange(Range);
7203   if (R.isInvalid())
7204     return;
7205 
7206   SmallVector<CXToken, 32> CXTokens;
7207   getTokens(CXXUnit, R, CXTokens);
7208 
7209   if (CXTokens.empty())
7210     return;
7211 
7212   *Tokens = static_cast<CXToken *>(
7213       llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
7214   memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
7215   *NumTokens = CXTokens.size();
7216 }
7217 
7218 void clang_disposeTokens(CXTranslationUnit TU, CXToken *Tokens,
7219                          unsigned NumTokens) {
7220   free(Tokens);
7221 }
7222 
7223 //===----------------------------------------------------------------------===//
7224 // Token annotation APIs.
7225 //===----------------------------------------------------------------------===//
7226 
7227 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7228                                                      CXCursor parent,
7229                                                      CXClientData client_data);
7230 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7231                                               CXClientData client_data);
7232 
7233 namespace {
7234 class AnnotateTokensWorker {
7235   CXToken *Tokens;
7236   CXCursor *Cursors;
7237   unsigned NumTokens;
7238   unsigned TokIdx;
7239   unsigned PreprocessingTokIdx;
7240   CursorVisitor AnnotateVis;
7241   SourceManager &SrcMgr;
7242   bool HasContextSensitiveKeywords;
7243 
7244   struct PostChildrenAction {
7245     CXCursor cursor;
7246     enum Action { Invalid, Ignore, Postpone } action;
7247   };
7248   using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
7249 
7250   struct PostChildrenInfo {
7251     CXCursor Cursor;
7252     SourceRange CursorRange;
7253     unsigned BeforeReachingCursorIdx;
7254     unsigned BeforeChildrenTokenIdx;
7255     PostChildrenActions ChildActions;
7256   };
7257   SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
7258 
7259   CXToken &getTok(unsigned Idx) {
7260     assert(Idx < NumTokens);
7261     return Tokens[Idx];
7262   }
7263   const CXToken &getTok(unsigned Idx) const {
7264     assert(Idx < NumTokens);
7265     return Tokens[Idx];
7266   }
7267   bool MoreTokens() const { return TokIdx < NumTokens; }
7268   unsigned NextToken() const { return TokIdx; }
7269   void AdvanceToken() { ++TokIdx; }
7270   SourceLocation GetTokenLoc(unsigned tokI) {
7271     return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
7272   }
7273   bool isFunctionMacroToken(unsigned tokI) const {
7274     return getTok(tokI).int_data[3] != 0;
7275   }
7276   SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
7277     return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
7278   }
7279 
7280   void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
7281   bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
7282                                              SourceRange);
7283 
7284 public:
7285   AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
7286                        CXTranslationUnit TU, SourceRange RegionOfInterest)
7287       : Tokens(tokens), Cursors(cursors), NumTokens(numTokens), TokIdx(0),
7288         PreprocessingTokIdx(0),
7289         AnnotateVis(TU, AnnotateTokensVisitor, this,
7290                     /*VisitPreprocessorLast=*/true,
7291                     /*VisitIncludedEntities=*/false, RegionOfInterest,
7292                     /*VisitDeclsOnly=*/false,
7293                     AnnotateTokensPostChildrenVisitor),
7294         SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
7295         HasContextSensitiveKeywords(false) {}
7296 
7297   void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
7298   enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
7299   bool IsIgnoredChildCursor(CXCursor cursor) const;
7300   PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
7301 
7302   bool postVisitChildren(CXCursor cursor);
7303   void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
7304   void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
7305 
7306   void AnnotateTokens();
7307 
7308   /// Determine whether the annotator saw any cursors that have
7309   /// context-sensitive keywords.
7310   bool hasContextSensitiveKeywords() const {
7311     return HasContextSensitiveKeywords;
7312   }
7313 
7314   ~AnnotateTokensWorker() { assert(PostChildrenInfos.empty()); }
7315 };
7316 } // namespace
7317 
7318 void AnnotateTokensWorker::AnnotateTokens() {
7319   // Walk the AST within the region of interest, annotating tokens
7320   // along the way.
7321   AnnotateVis.visitFileRegion();
7322 }
7323 
7324 bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
7325   if (PostChildrenInfos.empty())
7326     return false;
7327 
7328   for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
7329     if (ChildAction.cursor == cursor &&
7330         ChildAction.action == PostChildrenAction::Ignore) {
7331       return true;
7332     }
7333   }
7334 
7335   return false;
7336 }
7337 
7338 const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
7339   if (!clang_isExpression(Cursor.kind))
7340     return nullptr;
7341 
7342   const Expr *E = getCursorExpr(Cursor);
7343   if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7344     const OverloadedOperatorKind Kind = OCE->getOperator();
7345     if (Kind == OO_Call || Kind == OO_Subscript)
7346       return OCE;
7347   }
7348 
7349   return nullptr;
7350 }
7351 
7352 AnnotateTokensWorker::PostChildrenActions
7353 AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
7354   PostChildrenActions actions;
7355 
7356   // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
7357   // visited before the arguments to the operator call. For the Call and
7358   // Subscript operator the range of this DeclRefExpr includes the whole call
7359   // expression, so that all tokens in that range would be mapped to the
7360   // operator function, including the tokens of the arguments. To avoid that,
7361   // ensure to visit this DeclRefExpr as last node.
7362   if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
7363     const Expr *Callee = OCE->getCallee();
7364     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
7365       const Expr *SubExpr = ICE->getSubExpr();
7366       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
7367         const Decl *parentDecl = getCursorDecl(Cursor);
7368         CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7369 
7370         // Visit the DeclRefExpr as last.
7371         CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7372         actions.push_back({cxChild, PostChildrenAction::Postpone});
7373 
7374         // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7375         // wide range as the DeclRefExpr. We can skip visiting this entirely.
7376         cxChild = MakeCXCursor(ICE, parentDecl, TU);
7377         actions.push_back({cxChild, PostChildrenAction::Ignore});
7378       }
7379     }
7380   }
7381 
7382   return actions;
7383 }
7384 
7385 static inline void updateCursorAnnotation(CXCursor &Cursor,
7386                                           const CXCursor &updateC) {
7387   if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
7388     return;
7389   Cursor = updateC;
7390 }
7391 
7392 /// It annotates and advances tokens with a cursor until the comparison
7393 //// between the cursor location and the source range is the same as
7394 /// \arg compResult.
7395 ///
7396 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7397 /// Pass RangeOverlap to annotate tokens inside a range.
7398 void AnnotateTokensWorker::annotateAndAdvanceTokens(
7399     CXCursor updateC, RangeComparisonResult compResult, SourceRange range) {
7400   while (MoreTokens()) {
7401     const unsigned I = NextToken();
7402     if (isFunctionMacroToken(I))
7403       if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7404         return;
7405 
7406     SourceLocation TokLoc = GetTokenLoc(I);
7407     if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7408       updateCursorAnnotation(Cursors[I], updateC);
7409       AdvanceToken();
7410       continue;
7411     }
7412     break;
7413   }
7414 }
7415 
7416 /// Special annotation handling for macro argument tokens.
7417 /// \returns true if it advanced beyond all macro tokens, false otherwise.
7418 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
7419     CXCursor updateC, RangeComparisonResult compResult, SourceRange range) {
7420   assert(MoreTokens());
7421   assert(isFunctionMacroToken(NextToken()) &&
7422          "Should be called only for macro arg tokens");
7423 
7424   // This works differently than annotateAndAdvanceTokens; because expanded
7425   // macro arguments can have arbitrary translation-unit source order, we do not
7426   // advance the token index one by one until a token fails the range test.
7427   // We only advance once past all of the macro arg tokens if all of them
7428   // pass the range test. If one of them fails we keep the token index pointing
7429   // at the start of the macro arg tokens so that the failing token will be
7430   // annotated by a subsequent annotation try.
7431 
7432   bool atLeastOneCompFail = false;
7433 
7434   unsigned I = NextToken();
7435   for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7436     SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7437     if (TokLoc.isFileID())
7438       continue; // not macro arg token, it's parens or comma.
7439     if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7440       if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7441         Cursors[I] = updateC;
7442     } else
7443       atLeastOneCompFail = true;
7444   }
7445 
7446   if (atLeastOneCompFail)
7447     return false;
7448 
7449   TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7450   return true;
7451 }
7452 
7453 enum CXChildVisitResult AnnotateTokensWorker::Visit(CXCursor cursor,
7454                                                     CXCursor parent) {
7455   SourceRange cursorRange = getRawCursorExtent(cursor);
7456   if (cursorRange.isInvalid())
7457     return CXChildVisit_Recurse;
7458 
7459   if (IsIgnoredChildCursor(cursor))
7460     return CXChildVisit_Continue;
7461 
7462   if (!HasContextSensitiveKeywords) {
7463     // Objective-C properties can have context-sensitive keywords.
7464     if (cursor.kind == CXCursor_ObjCPropertyDecl) {
7465       if (const ObjCPropertyDecl *Property =
7466               dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7467         HasContextSensitiveKeywords =
7468             Property->getPropertyAttributesAsWritten() != 0;
7469     }
7470     // Objective-C methods can have context-sensitive keywords.
7471     else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7472              cursor.kind == CXCursor_ObjCClassMethodDecl) {
7473       if (const ObjCMethodDecl *Method =
7474               dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7475         if (Method->getObjCDeclQualifier())
7476           HasContextSensitiveKeywords = true;
7477         else {
7478           for (const auto *P : Method->parameters()) {
7479             if (P->getObjCDeclQualifier()) {
7480               HasContextSensitiveKeywords = true;
7481               break;
7482             }
7483           }
7484         }
7485       }
7486     }
7487     // C++ methods can have context-sensitive keywords.
7488     else if (cursor.kind == CXCursor_CXXMethod) {
7489       if (const CXXMethodDecl *Method =
7490               dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7491         if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7492           HasContextSensitiveKeywords = true;
7493       }
7494     }
7495     // C++ classes can have context-sensitive keywords.
7496     else if (cursor.kind == CXCursor_StructDecl ||
7497              cursor.kind == CXCursor_ClassDecl ||
7498              cursor.kind == CXCursor_ClassTemplate ||
7499              cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
7500       if (const Decl *D = getCursorDecl(cursor))
7501         if (D->hasAttr<FinalAttr>())
7502           HasContextSensitiveKeywords = true;
7503     }
7504   }
7505 
7506   // Don't override a property annotation with its getter/setter method.
7507   if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7508       parent.kind == CXCursor_ObjCPropertyDecl)
7509     return CXChildVisit_Continue;
7510 
7511   if (clang_isPreprocessing(cursor.kind)) {
7512     // Items in the preprocessing record are kept separate from items in
7513     // declarations, so we keep a separate token index.
7514     unsigned SavedTokIdx = TokIdx;
7515     TokIdx = PreprocessingTokIdx;
7516 
7517     // Skip tokens up until we catch up to the beginning of the preprocessing
7518     // entry.
7519     while (MoreTokens()) {
7520       const unsigned I = NextToken();
7521       SourceLocation TokLoc = GetTokenLoc(I);
7522       switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7523       case RangeBefore:
7524         AdvanceToken();
7525         continue;
7526       case RangeAfter:
7527       case RangeOverlap:
7528         break;
7529       }
7530       break;
7531     }
7532 
7533     // Look at all of the tokens within this range.
7534     while (MoreTokens()) {
7535       const unsigned I = NextToken();
7536       SourceLocation TokLoc = GetTokenLoc(I);
7537       switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7538       case RangeBefore:
7539         llvm_unreachable("Infeasible");
7540       case RangeAfter:
7541         break;
7542       case RangeOverlap:
7543         // For macro expansions, just note where the beginning of the macro
7544         // expansion occurs.
7545         if (cursor.kind == CXCursor_MacroExpansion) {
7546           if (TokLoc == cursorRange.getBegin())
7547             Cursors[I] = cursor;
7548           AdvanceToken();
7549           break;
7550         }
7551         // We may have already annotated macro names inside macro definitions.
7552         if (Cursors[I].kind != CXCursor_MacroExpansion)
7553           Cursors[I] = cursor;
7554         AdvanceToken();
7555         continue;
7556       }
7557       break;
7558     }
7559 
7560     // Save the preprocessing token index; restore the non-preprocessing
7561     // token index.
7562     PreprocessingTokIdx = TokIdx;
7563     TokIdx = SavedTokIdx;
7564     return CXChildVisit_Recurse;
7565   }
7566 
7567   if (cursorRange.isInvalid())
7568     return CXChildVisit_Continue;
7569 
7570   unsigned BeforeReachingCursorIdx = NextToken();
7571   const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
7572   const enum CXCursorKind K = clang_getCursorKind(parent);
7573   const CXCursor updateC =
7574       (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7575        // Attributes are annotated out-of-order, skip tokens until we reach it.
7576        clang_isAttribute(cursor.kind))
7577           ? clang_getNullCursor()
7578           : parent;
7579 
7580   annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7581 
7582   // Avoid having the cursor of an expression "overwrite" the annotation of the
7583   // variable declaration that it belongs to.
7584   // This can happen for C++ constructor expressions whose range generally
7585   // include the variable declaration, e.g.:
7586   //  MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
7587   if (clang_isExpression(cursorK) && MoreTokens()) {
7588     const Expr *E = getCursorExpr(cursor);
7589     if (const Decl *D = getCursorDecl(cursor)) {
7590       const unsigned I = NextToken();
7591       if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7592           E->getBeginLoc() == D->getLocation() &&
7593           E->getBeginLoc() == GetTokenLoc(I)) {
7594         updateCursorAnnotation(Cursors[I], updateC);
7595         AdvanceToken();
7596       }
7597     }
7598   }
7599 
7600   // Before recursing into the children keep some state that we are going
7601   // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7602   // extra work after the child nodes are visited.
7603   // Note that we don't call VisitChildren here to avoid traversing statements
7604   // code-recursively which can blow the stack.
7605 
7606   PostChildrenInfo Info;
7607   Info.Cursor = cursor;
7608   Info.CursorRange = cursorRange;
7609   Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
7610   Info.BeforeChildrenTokenIdx = NextToken();
7611   Info.ChildActions = DetermineChildActions(cursor);
7612   PostChildrenInfos.push_back(Info);
7613 
7614   return CXChildVisit_Recurse;
7615 }
7616 
7617 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7618   if (PostChildrenInfos.empty())
7619     return false;
7620   const PostChildrenInfo &Info = PostChildrenInfos.back();
7621   if (!clang_equalCursors(Info.Cursor, cursor))
7622     return false;
7623 
7624   HandlePostPonedChildCursors(Info);
7625 
7626   const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7627   const unsigned AfterChildren = NextToken();
7628   SourceRange cursorRange = Info.CursorRange;
7629 
7630   // Scan the tokens that are at the end of the cursor, but are not captured
7631   // but the child cursors.
7632   annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7633 
7634   // Scan the tokens that are at the beginning of the cursor, but are not
7635   // capture by the child cursors.
7636   for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7637     if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7638       break;
7639 
7640     Cursors[I] = cursor;
7641   }
7642 
7643   // Attributes are annotated out-of-order, rewind TokIdx to when we first
7644   // encountered the attribute cursor.
7645   if (clang_isAttribute(cursor.kind))
7646     TokIdx = Info.BeforeReachingCursorIdx;
7647 
7648   PostChildrenInfos.pop_back();
7649   return false;
7650 }
7651 
7652 void AnnotateTokensWorker::HandlePostPonedChildCursors(
7653     const PostChildrenInfo &Info) {
7654   for (const auto &ChildAction : Info.ChildActions) {
7655     if (ChildAction.action == PostChildrenAction::Postpone) {
7656       HandlePostPonedChildCursor(ChildAction.cursor,
7657                                  Info.BeforeChildrenTokenIdx);
7658     }
7659   }
7660 }
7661 
7662 void AnnotateTokensWorker::HandlePostPonedChildCursor(
7663     CXCursor Cursor, unsigned StartTokenIndex) {
7664   unsigned I = StartTokenIndex;
7665 
7666   // The bracket tokens of a Call or Subscript operator are mapped to
7667   // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7668   // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7669   for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
7670     const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7671         Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
7672     if (clang_Range_isNull(CXRefNameRange))
7673       break; // All ranges handled.
7674 
7675     SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7676     while (I < NumTokens) {
7677       const SourceLocation TokenLocation = GetTokenLoc(I);
7678       if (!TokenLocation.isValid())
7679         break;
7680 
7681       // Adapt the end range, because LocationCompare() reports
7682       // RangeOverlap even for the not-inclusive end location.
7683       const SourceLocation fixedEnd =
7684           RefNameRange.getEnd().getLocWithOffset(-1);
7685       RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7686 
7687       const RangeComparisonResult ComparisonResult =
7688           LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7689 
7690       if (ComparisonResult == RangeOverlap) {
7691         Cursors[I++] = Cursor;
7692       } else if (ComparisonResult == RangeBefore) {
7693         ++I; // Not relevant token, check next one.
7694       } else if (ComparisonResult == RangeAfter) {
7695         break; // All tokens updated for current range, check next.
7696       }
7697     }
7698   }
7699 }
7700 
7701 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7702                                                      CXCursor parent,
7703                                                      CXClientData client_data) {
7704   return static_cast<AnnotateTokensWorker *>(client_data)
7705       ->Visit(cursor, parent);
7706 }
7707 
7708 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7709                                               CXClientData client_data) {
7710   return static_cast<AnnotateTokensWorker *>(client_data)
7711       ->postVisitChildren(cursor);
7712 }
7713 
7714 namespace {
7715 
7716 /// Uses the macro expansions in the preprocessing record to find
7717 /// and mark tokens that are macro arguments. This info is used by the
7718 /// AnnotateTokensWorker.
7719 class MarkMacroArgTokensVisitor {
7720   SourceManager &SM;
7721   CXToken *Tokens;
7722   unsigned NumTokens;
7723   unsigned CurIdx;
7724 
7725 public:
7726   MarkMacroArgTokensVisitor(SourceManager &SM, CXToken *tokens,
7727                             unsigned numTokens)
7728       : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) {}
7729 
7730   CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7731     if (cursor.kind != CXCursor_MacroExpansion)
7732       return CXChildVisit_Continue;
7733 
7734     SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
7735     if (macroRange.getBegin() == macroRange.getEnd())
7736       return CXChildVisit_Continue; // it's not a function macro.
7737 
7738     for (; CurIdx < NumTokens; ++CurIdx) {
7739       if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7740                                         macroRange.getBegin()))
7741         break;
7742     }
7743 
7744     if (CurIdx == NumTokens)
7745       return CXChildVisit_Break;
7746 
7747     for (; CurIdx < NumTokens; ++CurIdx) {
7748       SourceLocation tokLoc = getTokenLoc(CurIdx);
7749       if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7750         break;
7751 
7752       setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7753     }
7754 
7755     if (CurIdx == NumTokens)
7756       return CXChildVisit_Break;
7757 
7758     return CXChildVisit_Continue;
7759   }
7760 
7761 private:
7762   CXToken &getTok(unsigned Idx) {
7763     assert(Idx < NumTokens);
7764     return Tokens[Idx];
7765   }
7766   const CXToken &getTok(unsigned Idx) const {
7767     assert(Idx < NumTokens);
7768     return Tokens[Idx];
7769   }
7770 
7771   SourceLocation getTokenLoc(unsigned tokI) {
7772     return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
7773   }
7774 
7775   void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7776     // The third field is reserved and currently not used. Use it here
7777     // to mark macro arg expanded tokens with their expanded locations.
7778     getTok(tokI).int_data[3] = loc.getRawEncoding();
7779   }
7780 };
7781 
7782 } // end anonymous namespace
7783 
7784 static CXChildVisitResult
7785 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7786                                   CXClientData client_data) {
7787   return static_cast<MarkMacroArgTokensVisitor *>(client_data)
7788       ->visit(cursor, parent);
7789 }
7790 
7791 /// Used by \c annotatePreprocessorTokens.
7792 /// \returns true if lexing was finished, false otherwise.
7793 static bool lexNext(Lexer &Lex, Token &Tok, unsigned &NextIdx,
7794                     unsigned NumTokens) {
7795   if (NextIdx >= NumTokens)
7796     return true;
7797 
7798   ++NextIdx;
7799   Lex.LexFromRawLexer(Tok);
7800   return Tok.is(tok::eof);
7801 }
7802 
7803 static void annotatePreprocessorTokens(CXTranslationUnit TU,
7804                                        SourceRange RegionOfInterest,
7805                                        CXCursor *Cursors, CXToken *Tokens,
7806                                        unsigned NumTokens) {
7807   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7808 
7809   Preprocessor &PP = CXXUnit->getPreprocessor();
7810   SourceManager &SourceMgr = CXXUnit->getSourceManager();
7811   std::pair<FileID, unsigned> BeginLocInfo =
7812       SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
7813   std::pair<FileID, unsigned> EndLocInfo =
7814       SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
7815 
7816   if (BeginLocInfo.first != EndLocInfo.first)
7817     return;
7818 
7819   StringRef Buffer;
7820   bool Invalid = false;
7821   Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7822   if (Buffer.empty() || Invalid)
7823     return;
7824 
7825   Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7826             CXXUnit->getASTContext().getLangOpts(), Buffer.begin(),
7827             Buffer.data() + BeginLocInfo.second, Buffer.end());
7828   Lex.SetCommentRetentionState(true);
7829 
7830   unsigned NextIdx = 0;
7831   // Lex tokens in raw mode until we hit the end of the range, to avoid
7832   // entering #includes or expanding macros.
7833   while (true) {
7834     Token Tok;
7835     if (lexNext(Lex, Tok, NextIdx, NumTokens))
7836       break;
7837     unsigned TokIdx = NextIdx - 1;
7838     assert(Tok.getLocation() ==
7839            SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
7840 
7841   reprocess:
7842     if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
7843       // We have found a preprocessing directive. Annotate the tokens
7844       // appropriately.
7845       //
7846       // FIXME: Some simple tests here could identify macro definitions and
7847       // #undefs, to provide specific cursor kinds for those.
7848 
7849       SourceLocation BeginLoc = Tok.getLocation();
7850       if (lexNext(Lex, Tok, NextIdx, NumTokens))
7851         break;
7852 
7853       MacroInfo *MI = nullptr;
7854       if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
7855         if (lexNext(Lex, Tok, NextIdx, NumTokens))
7856           break;
7857 
7858         if (Tok.is(tok::raw_identifier)) {
7859           IdentifierInfo &II =
7860               PP.getIdentifierTable().get(Tok.getRawIdentifier());
7861           SourceLocation MappedTokLoc =
7862               CXXUnit->mapLocationToPreamble(Tok.getLocation());
7863           MI = getMacroInfo(II, MappedTokLoc, TU);
7864         }
7865       }
7866 
7867       bool finished = false;
7868       do {
7869         if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7870           finished = true;
7871           break;
7872         }
7873         // If we are in a macro definition, check if the token was ever a
7874         // macro name and annotate it if that's the case.
7875         if (MI) {
7876           SourceLocation SaveLoc = Tok.getLocation();
7877           Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
7878           MacroDefinitionRecord *MacroDef =
7879               checkForMacroInMacroDefinition(MI, Tok, TU);
7880           Tok.setLocation(SaveLoc);
7881           if (MacroDef)
7882             Cursors[NextIdx - 1] =
7883                 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
7884         }
7885       } while (!Tok.isAtStartOfLine());
7886 
7887       unsigned LastIdx = finished ? NextIdx - 1 : NextIdx - 2;
7888       assert(TokIdx <= LastIdx);
7889       SourceLocation EndLoc =
7890           SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7891       CXCursor Cursor =
7892           MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7893 
7894       for (; TokIdx <= LastIdx; ++TokIdx)
7895         updateCursorAnnotation(Cursors[TokIdx], Cursor);
7896 
7897       if (finished)
7898         break;
7899       goto reprocess;
7900     }
7901   }
7902 }
7903 
7904 // This gets run a separate thread to avoid stack blowout.
7905 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7906                                      CXToken *Tokens, unsigned NumTokens,
7907                                      CXCursor *Cursors) {
7908   CIndexer *CXXIdx = TU->CIdx;
7909   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7910     setThreadBackgroundPriority();
7911 
7912   // Determine the region of interest, which contains all of the tokens.
7913   SourceRange RegionOfInterest;
7914   RegionOfInterest.setBegin(
7915       cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7916   RegionOfInterest.setEnd(cxloc::translateSourceLocation(
7917       clang_getTokenLocation(TU, Tokens[NumTokens - 1])));
7918 
7919   // Relex the tokens within the source range to look for preprocessing
7920   // directives.
7921   annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
7922 
7923   // If begin location points inside a macro argument, set it to the expansion
7924   // location so we can have the full context when annotating semantically.
7925   {
7926     SourceManager &SM = CXXUnit->getSourceManager();
7927     SourceLocation Loc =
7928         SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7929     if (Loc.isMacroID())
7930       RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7931   }
7932 
7933   if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7934     // Search and mark tokens that are macro argument expansions.
7935     MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(), Tokens,
7936                                       NumTokens);
7937     CursorVisitor MacroArgMarker(
7938         TU, MarkMacroArgTokensVisitorDelegate, &Visitor,
7939         /*VisitPreprocessorLast=*/true,
7940         /*VisitIncludedEntities=*/false, RegionOfInterest);
7941     MacroArgMarker.visitPreprocessedEntitiesInRegion();
7942   }
7943 
7944   // Annotate all of the source locations in the region of interest that map to
7945   // a specific cursor.
7946   AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
7947 
7948   // FIXME: We use a ridiculous stack size here because the data-recursion
7949   // algorithm uses a large stack frame than the non-data recursive version,
7950   // and AnnotationTokensWorker currently transforms the data-recursion
7951   // algorithm back into a traditional recursion by explicitly calling
7952   // VisitChildren().  We will need to remove this explicit recursive call.
7953   W.AnnotateTokens();
7954 
7955   // If we ran into any entities that involve context-sensitive keywords,
7956   // take another pass through the tokens to mark them as such.
7957   if (W.hasContextSensitiveKeywords()) {
7958     for (unsigned I = 0; I != NumTokens; ++I) {
7959       if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7960         continue;
7961 
7962       if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7963         IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7964         if (const ObjCPropertyDecl *Property =
7965                 dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7966           if (Property->getPropertyAttributesAsWritten() != 0 &&
7967               llvm::StringSwitch<bool>(II->getName())
7968                   .Case("readonly", true)
7969                   .Case("assign", true)
7970                   .Case("unsafe_unretained", true)
7971                   .Case("readwrite", true)
7972                   .Case("retain", true)
7973                   .Case("copy", true)
7974                   .Case("nonatomic", true)
7975                   .Case("atomic", true)
7976                   .Case("getter", true)
7977                   .Case("setter", true)
7978                   .Case("strong", true)
7979                   .Case("weak", true)
7980                   .Case("class", true)
7981                   .Default(false))
7982             Tokens[I].int_data[0] = CXToken_Keyword;
7983         }
7984         continue;
7985       }
7986 
7987       if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7988           Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7989         IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7990         if (llvm::StringSwitch<bool>(II->getName())
7991                 .Case("in", true)
7992                 .Case("out", true)
7993                 .Case("inout", true)
7994                 .Case("oneway", true)
7995                 .Case("bycopy", true)
7996                 .Case("byref", true)
7997                 .Default(false))
7998           Tokens[I].int_data[0] = CXToken_Keyword;
7999         continue;
8000       }
8001 
8002       if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
8003           Cursors[I].kind == CXCursor_CXXOverrideAttr) {
8004         Tokens[I].int_data[0] = CXToken_Keyword;
8005         continue;
8006       }
8007     }
8008   }
8009 }
8010 
8011 void clang_annotateTokens(CXTranslationUnit TU, CXToken *Tokens,
8012                           unsigned NumTokens, CXCursor *Cursors) {
8013   if (isNotUsableTU(TU)) {
8014     LOG_BAD_TU(TU);
8015     return;
8016   }
8017   if (NumTokens == 0 || !Tokens || !Cursors) {
8018     LOG_FUNC_SECTION { *Log << "<null input>"; }
8019     return;
8020   }
8021 
8022   LOG_FUNC_SECTION {
8023     *Log << TU << ' ';
8024     CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
8025     CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens - 1]);
8026     *Log << clang_getRange(bloc, eloc);
8027   }
8028 
8029   // Any token we don't specifically annotate will have a NULL cursor.
8030   CXCursor C = clang_getNullCursor();
8031   for (unsigned I = 0; I != NumTokens; ++I)
8032     Cursors[I] = C;
8033 
8034   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
8035   if (!CXXUnit)
8036     return;
8037 
8038   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
8039 
8040   auto AnnotateTokensImpl = [=]() {
8041     clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
8042   };
8043   llvm::CrashRecoveryContext CRC;
8044   if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
8045     fprintf(stderr, "libclang: crash detected while annotating tokens\n");
8046   }
8047 }
8048 
8049 //===----------------------------------------------------------------------===//
8050 // Operations for querying linkage of a cursor.
8051 //===----------------------------------------------------------------------===//
8052 
8053 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
8054   if (!clang_isDeclaration(cursor.kind))
8055     return CXLinkage_Invalid;
8056 
8057   const Decl *D = cxcursor::getCursorDecl(cursor);
8058   if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
8059     switch (ND->getLinkageInternal()) {
8060     case NoLinkage:
8061     case VisibleNoLinkage:
8062       return CXLinkage_NoLinkage;
8063     case ModuleInternalLinkage:
8064     case InternalLinkage:
8065       return CXLinkage_Internal;
8066     case UniqueExternalLinkage:
8067       return CXLinkage_UniqueExternal;
8068     case ModuleLinkage:
8069     case ExternalLinkage:
8070       return CXLinkage_External;
8071     };
8072 
8073   return CXLinkage_Invalid;
8074 }
8075 
8076 //===----------------------------------------------------------------------===//
8077 // Operations for querying visibility of a cursor.
8078 //===----------------------------------------------------------------------===//
8079 
8080 CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
8081   if (!clang_isDeclaration(cursor.kind))
8082     return CXVisibility_Invalid;
8083 
8084   const Decl *D = cxcursor::getCursorDecl(cursor);
8085   if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
8086     switch (ND->getVisibility()) {
8087     case HiddenVisibility:
8088       return CXVisibility_Hidden;
8089     case ProtectedVisibility:
8090       return CXVisibility_Protected;
8091     case DefaultVisibility:
8092       return CXVisibility_Default;
8093     };
8094 
8095   return CXVisibility_Invalid;
8096 }
8097 
8098 //===----------------------------------------------------------------------===//
8099 // Operations for querying language of a cursor.
8100 //===----------------------------------------------------------------------===//
8101 
8102 static CXLanguageKind getDeclLanguage(const Decl *D) {
8103   if (!D)
8104     return CXLanguage_C;
8105 
8106   switch (D->getKind()) {
8107   default:
8108     break;
8109   case Decl::ImplicitParam:
8110   case Decl::ObjCAtDefsField:
8111   case Decl::ObjCCategory:
8112   case Decl::ObjCCategoryImpl:
8113   case Decl::ObjCCompatibleAlias:
8114   case Decl::ObjCImplementation:
8115   case Decl::ObjCInterface:
8116   case Decl::ObjCIvar:
8117   case Decl::ObjCMethod:
8118   case Decl::ObjCProperty:
8119   case Decl::ObjCPropertyImpl:
8120   case Decl::ObjCProtocol:
8121   case Decl::ObjCTypeParam:
8122     return CXLanguage_ObjC;
8123   case Decl::CXXConstructor:
8124   case Decl::CXXConversion:
8125   case Decl::CXXDestructor:
8126   case Decl::CXXMethod:
8127   case Decl::CXXRecord:
8128   case Decl::ClassTemplate:
8129   case Decl::ClassTemplatePartialSpecialization:
8130   case Decl::ClassTemplateSpecialization:
8131   case Decl::Friend:
8132   case Decl::FriendTemplate:
8133   case Decl::FunctionTemplate:
8134   case Decl::LinkageSpec:
8135   case Decl::Namespace:
8136   case Decl::NamespaceAlias:
8137   case Decl::NonTypeTemplateParm:
8138   case Decl::StaticAssert:
8139   case Decl::TemplateTemplateParm:
8140   case Decl::TemplateTypeParm:
8141   case Decl::UnresolvedUsingTypename:
8142   case Decl::UnresolvedUsingValue:
8143   case Decl::Using:
8144   case Decl::UsingDirective:
8145   case Decl::UsingShadow:
8146     return CXLanguage_CPlusPlus;
8147   }
8148 
8149   return CXLanguage_C;
8150 }
8151 
8152 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
8153   if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
8154     return CXAvailability_NotAvailable;
8155 
8156   switch (D->getAvailability()) {
8157   case AR_Available:
8158   case AR_NotYetIntroduced:
8159     if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
8160       return getCursorAvailabilityForDecl(
8161           cast<Decl>(EnumConst->getDeclContext()));
8162     return CXAvailability_Available;
8163 
8164   case AR_Deprecated:
8165     return CXAvailability_Deprecated;
8166 
8167   case AR_Unavailable:
8168     return CXAvailability_NotAvailable;
8169   }
8170 
8171   llvm_unreachable("Unknown availability kind!");
8172 }
8173 
8174 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
8175   if (clang_isDeclaration(cursor.kind))
8176     if (const Decl *D = cxcursor::getCursorDecl(cursor))
8177       return getCursorAvailabilityForDecl(D);
8178 
8179   return CXAvailability_Available;
8180 }
8181 
8182 static CXVersion convertVersion(VersionTuple In) {
8183   CXVersion Out = {-1, -1, -1};
8184   if (In.empty())
8185     return Out;
8186 
8187   Out.Major = In.getMajor();
8188 
8189   Optional<unsigned> Minor = In.getMinor();
8190   if (Minor)
8191     Out.Minor = *Minor;
8192   else
8193     return Out;
8194 
8195   Optional<unsigned> Subminor = In.getSubminor();
8196   if (Subminor)
8197     Out.Subminor = *Subminor;
8198 
8199   return Out;
8200 }
8201 
8202 static void getCursorPlatformAvailabilityForDecl(
8203     const Decl *D, int *always_deprecated, CXString *deprecated_message,
8204     int *always_unavailable, CXString *unavailable_message,
8205     SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
8206   bool HadAvailAttr = false;
8207   for (auto A : D->attrs()) {
8208     if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
8209       HadAvailAttr = true;
8210       if (always_deprecated)
8211         *always_deprecated = 1;
8212       if (deprecated_message) {
8213         clang_disposeString(*deprecated_message);
8214         *deprecated_message = cxstring::createDup(Deprecated->getMessage());
8215       }
8216       continue;
8217     }
8218 
8219     if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
8220       HadAvailAttr = true;
8221       if (always_unavailable)
8222         *always_unavailable = 1;
8223       if (unavailable_message) {
8224         clang_disposeString(*unavailable_message);
8225         *unavailable_message = cxstring::createDup(Unavailable->getMessage());
8226       }
8227       continue;
8228     }
8229 
8230     if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
8231       AvailabilityAttrs.push_back(Avail);
8232       HadAvailAttr = true;
8233     }
8234   }
8235 
8236   if (!HadAvailAttr)
8237     if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
8238       return getCursorPlatformAvailabilityForDecl(
8239           cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
8240           deprecated_message, always_unavailable, unavailable_message,
8241           AvailabilityAttrs);
8242 
8243   if (AvailabilityAttrs.empty())
8244     return;
8245 
8246   llvm::sort(
8247       AvailabilityAttrs, [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
8248         return LHS->getPlatform()->getName() < RHS->getPlatform()->getName();
8249       });
8250   ASTContext &Ctx = D->getASTContext();
8251   auto It = std::unique(
8252       AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
8253       [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
8254         if (LHS->getPlatform() != RHS->getPlatform())
8255           return false;
8256 
8257         if (LHS->getIntroduced() == RHS->getIntroduced() &&
8258             LHS->getDeprecated() == RHS->getDeprecated() &&
8259             LHS->getObsoleted() == RHS->getObsoleted() &&
8260             LHS->getMessage() == RHS->getMessage() &&
8261             LHS->getReplacement() == RHS->getReplacement())
8262           return true;
8263 
8264         if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
8265             (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
8266             (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
8267           return false;
8268 
8269         if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
8270           LHS->setIntroduced(Ctx, RHS->getIntroduced());
8271 
8272         if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
8273           LHS->setDeprecated(Ctx, RHS->getDeprecated());
8274           if (LHS->getMessage().empty())
8275             LHS->setMessage(Ctx, RHS->getMessage());
8276           if (LHS->getReplacement().empty())
8277             LHS->setReplacement(Ctx, RHS->getReplacement());
8278         }
8279 
8280         if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
8281           LHS->setObsoleted(Ctx, RHS->getObsoleted());
8282           if (LHS->getMessage().empty())
8283             LHS->setMessage(Ctx, RHS->getMessage());
8284           if (LHS->getReplacement().empty())
8285             LHS->setReplacement(Ctx, RHS->getReplacement());
8286         }
8287 
8288         return true;
8289       });
8290   AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
8291 }
8292 
8293 int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
8294                                         CXString *deprecated_message,
8295                                         int *always_unavailable,
8296                                         CXString *unavailable_message,
8297                                         CXPlatformAvailability *availability,
8298                                         int availability_size) {
8299   if (always_deprecated)
8300     *always_deprecated = 0;
8301   if (deprecated_message)
8302     *deprecated_message = cxstring::createEmpty();
8303   if (always_unavailable)
8304     *always_unavailable = 0;
8305   if (unavailable_message)
8306     *unavailable_message = cxstring::createEmpty();
8307 
8308   if (!clang_isDeclaration(cursor.kind))
8309     return 0;
8310 
8311   const Decl *D = cxcursor::getCursorDecl(cursor);
8312   if (!D)
8313     return 0;
8314 
8315   SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
8316   getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
8317                                        always_unavailable, unavailable_message,
8318                                        AvailabilityAttrs);
8319   for (const auto &Avail :
8320        llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
8321                            .take_front(availability_size))) {
8322     availability[Avail.index()].Platform =
8323         cxstring::createDup(Avail.value()->getPlatform()->getName());
8324     availability[Avail.index()].Introduced =
8325         convertVersion(Avail.value()->getIntroduced());
8326     availability[Avail.index()].Deprecated =
8327         convertVersion(Avail.value()->getDeprecated());
8328     availability[Avail.index()].Obsoleted =
8329         convertVersion(Avail.value()->getObsoleted());
8330     availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
8331     availability[Avail.index()].Message =
8332         cxstring::createDup(Avail.value()->getMessage());
8333   }
8334 
8335   return AvailabilityAttrs.size();
8336 }
8337 
8338 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
8339   clang_disposeString(availability->Platform);
8340   clang_disposeString(availability->Message);
8341 }
8342 
8343 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
8344   if (clang_isDeclaration(cursor.kind))
8345     return getDeclLanguage(cxcursor::getCursorDecl(cursor));
8346 
8347   return CXLanguage_Invalid;
8348 }
8349 
8350 CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
8351   const Decl *D = cxcursor::getCursorDecl(cursor);
8352   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8353     switch (VD->getTLSKind()) {
8354     case VarDecl::TLS_None:
8355       return CXTLS_None;
8356     case VarDecl::TLS_Dynamic:
8357       return CXTLS_Dynamic;
8358     case VarDecl::TLS_Static:
8359       return CXTLS_Static;
8360     }
8361   }
8362 
8363   return CXTLS_None;
8364 }
8365 
8366 /// If the given cursor is the "templated" declaration
8367 /// describing a class or function template, return the class or
8368 /// function template.
8369 static const Decl *maybeGetTemplateCursor(const Decl *D) {
8370   if (!D)
8371     return nullptr;
8372 
8373   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8374     if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8375       return FunTmpl;
8376 
8377   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
8378     if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8379       return ClassTmpl;
8380 
8381   return D;
8382 }
8383 
8384 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8385   StorageClass sc = SC_None;
8386   const Decl *D = getCursorDecl(C);
8387   if (D) {
8388     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8389       sc = FD->getStorageClass();
8390     } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8391       sc = VD->getStorageClass();
8392     } else {
8393       return CX_SC_Invalid;
8394     }
8395   } else {
8396     return CX_SC_Invalid;
8397   }
8398   switch (sc) {
8399   case SC_None:
8400     return CX_SC_None;
8401   case SC_Extern:
8402     return CX_SC_Extern;
8403   case SC_Static:
8404     return CX_SC_Static;
8405   case SC_PrivateExtern:
8406     return CX_SC_PrivateExtern;
8407   case SC_Auto:
8408     return CX_SC_Auto;
8409   case SC_Register:
8410     return CX_SC_Register;
8411   }
8412   llvm_unreachable("Unhandled storage class!");
8413 }
8414 
8415 CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8416   if (clang_isDeclaration(cursor.kind)) {
8417     if (const Decl *D = getCursorDecl(cursor)) {
8418       const DeclContext *DC = D->getDeclContext();
8419       if (!DC)
8420         return clang_getNullCursor();
8421 
8422       return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8423                           getCursorTU(cursor));
8424     }
8425   }
8426 
8427   if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
8428     if (const Decl *D = getCursorDecl(cursor))
8429       return MakeCXCursor(D, getCursorTU(cursor));
8430   }
8431 
8432   return clang_getNullCursor();
8433 }
8434 
8435 CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8436   if (clang_isDeclaration(cursor.kind)) {
8437     if (const Decl *D = getCursorDecl(cursor)) {
8438       const DeclContext *DC = D->getLexicalDeclContext();
8439       if (!DC)
8440         return clang_getNullCursor();
8441 
8442       return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8443                           getCursorTU(cursor));
8444     }
8445   }
8446 
8447   // FIXME: Note that we can't easily compute the lexical context of a
8448   // statement or expression, so we return nothing.
8449   return clang_getNullCursor();
8450 }
8451 
8452 CXFile clang_getIncludedFile(CXCursor cursor) {
8453   if (cursor.kind != CXCursor_InclusionDirective)
8454     return nullptr;
8455 
8456   const InclusionDirective *ID = getCursorInclusionDirective(cursor);
8457   Optional<FileEntryRef> File = ID->getFile();
8458   return const_cast<FileEntry *>(File ? &File->getFileEntry() : nullptr);
8459 }
8460 
8461 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8462   if (C.kind != CXCursor_ObjCPropertyDecl)
8463     return CXObjCPropertyAttr_noattr;
8464 
8465   unsigned Result = CXObjCPropertyAttr_noattr;
8466   const auto *PD = cast<ObjCPropertyDecl>(getCursorDecl(C));
8467   ObjCPropertyAttribute::Kind Attr = PD->getPropertyAttributesAsWritten();
8468 
8469 #define SET_CXOBJCPROP_ATTR(A)                                                 \
8470   if (Attr & ObjCPropertyAttribute::kind_##A)                                  \
8471   Result |= CXObjCPropertyAttr_##A
8472   SET_CXOBJCPROP_ATTR(readonly);
8473   SET_CXOBJCPROP_ATTR(getter);
8474   SET_CXOBJCPROP_ATTR(assign);
8475   SET_CXOBJCPROP_ATTR(readwrite);
8476   SET_CXOBJCPROP_ATTR(retain);
8477   SET_CXOBJCPROP_ATTR(copy);
8478   SET_CXOBJCPROP_ATTR(nonatomic);
8479   SET_CXOBJCPROP_ATTR(setter);
8480   SET_CXOBJCPROP_ATTR(atomic);
8481   SET_CXOBJCPROP_ATTR(weak);
8482   SET_CXOBJCPROP_ATTR(strong);
8483   SET_CXOBJCPROP_ATTR(unsafe_unretained);
8484   SET_CXOBJCPROP_ATTR(class);
8485 #undef SET_CXOBJCPROP_ATTR
8486 
8487   return Result;
8488 }
8489 
8490 CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8491   if (C.kind != CXCursor_ObjCPropertyDecl)
8492     return cxstring::createNull();
8493 
8494   const auto *PD = cast<ObjCPropertyDecl>(getCursorDecl(C));
8495   Selector sel = PD->getGetterName();
8496   if (sel.isNull())
8497     return cxstring::createNull();
8498 
8499   return cxstring::createDup(sel.getAsString());
8500 }
8501 
8502 CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8503   if (C.kind != CXCursor_ObjCPropertyDecl)
8504     return cxstring::createNull();
8505 
8506   const auto *PD = cast<ObjCPropertyDecl>(getCursorDecl(C));
8507   Selector sel = PD->getSetterName();
8508   if (sel.isNull())
8509     return cxstring::createNull();
8510 
8511   return cxstring::createDup(sel.getAsString());
8512 }
8513 
8514 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8515   if (!clang_isDeclaration(C.kind))
8516     return CXObjCDeclQualifier_None;
8517 
8518   Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8519   const Decl *D = getCursorDecl(C);
8520   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8521     QT = MD->getObjCDeclQualifier();
8522   else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8523     QT = PD->getObjCDeclQualifier();
8524   if (QT == Decl::OBJC_TQ_None)
8525     return CXObjCDeclQualifier_None;
8526 
8527   unsigned Result = CXObjCDeclQualifier_None;
8528   if (QT & Decl::OBJC_TQ_In)
8529     Result |= CXObjCDeclQualifier_In;
8530   if (QT & Decl::OBJC_TQ_Inout)
8531     Result |= CXObjCDeclQualifier_Inout;
8532   if (QT & Decl::OBJC_TQ_Out)
8533     Result |= CXObjCDeclQualifier_Out;
8534   if (QT & Decl::OBJC_TQ_Bycopy)
8535     Result |= CXObjCDeclQualifier_Bycopy;
8536   if (QT & Decl::OBJC_TQ_Byref)
8537     Result |= CXObjCDeclQualifier_Byref;
8538   if (QT & Decl::OBJC_TQ_Oneway)
8539     Result |= CXObjCDeclQualifier_Oneway;
8540 
8541   return Result;
8542 }
8543 
8544 unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8545   if (!clang_isDeclaration(C.kind))
8546     return 0;
8547 
8548   const Decl *D = getCursorDecl(C);
8549   if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8550     return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8551   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8552     return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8553 
8554   return 0;
8555 }
8556 
8557 unsigned clang_Cursor_isVariadic(CXCursor C) {
8558   if (!clang_isDeclaration(C.kind))
8559     return 0;
8560 
8561   const Decl *D = getCursorDecl(C);
8562   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8563     return FD->isVariadic();
8564   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8565     return MD->isVariadic();
8566 
8567   return 0;
8568 }
8569 
8570 unsigned clang_Cursor_isExternalSymbol(CXCursor C, CXString *language,
8571                                        CXString *definedIn,
8572                                        unsigned *isGenerated) {
8573   if (!clang_isDeclaration(C.kind))
8574     return 0;
8575 
8576   const Decl *D = getCursorDecl(C);
8577 
8578   if (auto *attr = D->getExternalSourceSymbolAttr()) {
8579     if (language)
8580       *language = cxstring::createDup(attr->getLanguage());
8581     if (definedIn)
8582       *definedIn = cxstring::createDup(attr->getDefinedIn());
8583     if (isGenerated)
8584       *isGenerated = attr->getGeneratedDeclaration();
8585     return 1;
8586   }
8587   return 0;
8588 }
8589 
8590 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8591   if (!clang_isDeclaration(C.kind))
8592     return clang_getNullRange();
8593 
8594   const Decl *D = getCursorDecl(C);
8595   ASTContext &Context = getCursorContext(C);
8596   const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8597   if (!RC)
8598     return clang_getNullRange();
8599 
8600   return cxloc::translateSourceRange(Context, RC->getSourceRange());
8601 }
8602 
8603 CXString clang_Cursor_getRawCommentText(CXCursor C) {
8604   if (!clang_isDeclaration(C.kind))
8605     return cxstring::createNull();
8606 
8607   const Decl *D = getCursorDecl(C);
8608   ASTContext &Context = getCursorContext(C);
8609   const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8610   StringRef RawText =
8611       RC ? RC->getRawText(Context.getSourceManager()) : StringRef();
8612 
8613   // Don't duplicate the string because RawText points directly into source
8614   // code.
8615   return cxstring::createRef(RawText);
8616 }
8617 
8618 CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8619   if (!clang_isDeclaration(C.kind))
8620     return cxstring::createNull();
8621 
8622   const Decl *D = getCursorDecl(C);
8623   const ASTContext &Context = getCursorContext(C);
8624   const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8625 
8626   if (RC) {
8627     StringRef BriefText = RC->getBriefText(Context);
8628 
8629     // Don't duplicate the string because RawComment ensures that this memory
8630     // will not go away.
8631     return cxstring::createRef(BriefText);
8632   }
8633 
8634   return cxstring::createNull();
8635 }
8636 
8637 CXModule clang_Cursor_getModule(CXCursor C) {
8638   if (C.kind == CXCursor_ModuleImportDecl) {
8639     if (const ImportDecl *ImportD =
8640             dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
8641       return ImportD->getImportedModule();
8642   }
8643 
8644   return nullptr;
8645 }
8646 
8647 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8648   if (isNotUsableTU(TU)) {
8649     LOG_BAD_TU(TU);
8650     return nullptr;
8651   }
8652   if (!File)
8653     return nullptr;
8654   FileEntry *FE = static_cast<FileEntry *>(File);
8655 
8656   ASTUnit &Unit = *cxtu::getASTUnit(TU);
8657   HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8658   ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8659 
8660   return Header.getModule();
8661 }
8662 
8663 CXFile clang_Module_getASTFile(CXModule CXMod) {
8664   if (!CXMod)
8665     return nullptr;
8666   Module *Mod = static_cast<Module *>(CXMod);
8667   if (auto File = Mod->getASTFile())
8668     return const_cast<FileEntry *>(&File->getFileEntry());
8669   return nullptr;
8670 }
8671 
8672 CXModule clang_Module_getParent(CXModule CXMod) {
8673   if (!CXMod)
8674     return nullptr;
8675   Module *Mod = static_cast<Module *>(CXMod);
8676   return Mod->Parent;
8677 }
8678 
8679 CXString clang_Module_getName(CXModule CXMod) {
8680   if (!CXMod)
8681     return cxstring::createEmpty();
8682   Module *Mod = static_cast<Module *>(CXMod);
8683   return cxstring::createDup(Mod->Name);
8684 }
8685 
8686 CXString clang_Module_getFullName(CXModule CXMod) {
8687   if (!CXMod)
8688     return cxstring::createEmpty();
8689   Module *Mod = static_cast<Module *>(CXMod);
8690   return cxstring::createDup(Mod->getFullModuleName());
8691 }
8692 
8693 int clang_Module_isSystem(CXModule CXMod) {
8694   if (!CXMod)
8695     return 0;
8696   Module *Mod = static_cast<Module *>(CXMod);
8697   return Mod->IsSystem;
8698 }
8699 
8700 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8701                                             CXModule CXMod) {
8702   if (isNotUsableTU(TU)) {
8703     LOG_BAD_TU(TU);
8704     return 0;
8705   }
8706   if (!CXMod)
8707     return 0;
8708   Module *Mod = static_cast<Module *>(CXMod);
8709   FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8710   ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8711   return TopHeaders.size();
8712 }
8713 
8714 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU, CXModule CXMod,
8715                                       unsigned Index) {
8716   if (isNotUsableTU(TU)) {
8717     LOG_BAD_TU(TU);
8718     return nullptr;
8719   }
8720   if (!CXMod)
8721     return nullptr;
8722   Module *Mod = static_cast<Module *>(CXMod);
8723   FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8724 
8725   ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8726   if (Index < TopHeaders.size())
8727     return const_cast<FileEntry *>(TopHeaders[Index]);
8728 
8729   return nullptr;
8730 }
8731 
8732 //===----------------------------------------------------------------------===//
8733 // C++ AST instrospection.
8734 //===----------------------------------------------------------------------===//
8735 
8736 unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8737   if (!clang_isDeclaration(C.kind))
8738     return 0;
8739 
8740   const Decl *D = cxcursor::getCursorDecl(C);
8741   const CXXConstructorDecl *Constructor =
8742       D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8743   return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8744 }
8745 
8746 unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8747   if (!clang_isDeclaration(C.kind))
8748     return 0;
8749 
8750   const Decl *D = cxcursor::getCursorDecl(C);
8751   const CXXConstructorDecl *Constructor =
8752       D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8753   return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8754 }
8755 
8756 unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8757   if (!clang_isDeclaration(C.kind))
8758     return 0;
8759 
8760   const Decl *D = cxcursor::getCursorDecl(C);
8761   const CXXConstructorDecl *Constructor =
8762       D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8763   return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8764 }
8765 
8766 unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8767   if (!clang_isDeclaration(C.kind))
8768     return 0;
8769 
8770   const Decl *D = cxcursor::getCursorDecl(C);
8771   const CXXConstructorDecl *Constructor =
8772       D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8773   // Passing 'false' excludes constructors marked 'explicit'.
8774   return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8775 }
8776 
8777 unsigned clang_CXXField_isMutable(CXCursor C) {
8778   if (!clang_isDeclaration(C.kind))
8779     return 0;
8780 
8781   if (const auto D = cxcursor::getCursorDecl(C))
8782     if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8783       return FD->isMutable() ? 1 : 0;
8784   return 0;
8785 }
8786 
8787 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8788   if (!clang_isDeclaration(C.kind))
8789     return 0;
8790 
8791   const Decl *D = cxcursor::getCursorDecl(C);
8792   const CXXMethodDecl *Method =
8793       D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8794   return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8795 }
8796 
8797 unsigned clang_CXXMethod_isConst(CXCursor C) {
8798   if (!clang_isDeclaration(C.kind))
8799     return 0;
8800 
8801   const Decl *D = cxcursor::getCursorDecl(C);
8802   const CXXMethodDecl *Method =
8803       D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8804   return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
8805 }
8806 
8807 unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8808   if (!clang_isDeclaration(C.kind))
8809     return 0;
8810 
8811   const Decl *D = cxcursor::getCursorDecl(C);
8812   const CXXMethodDecl *Method =
8813       D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8814   return (Method && Method->isDefaulted()) ? 1 : 0;
8815 }
8816 
8817 unsigned clang_CXXMethod_isStatic(CXCursor C) {
8818   if (!clang_isDeclaration(C.kind))
8819     return 0;
8820 
8821   const Decl *D = cxcursor::getCursorDecl(C);
8822   const CXXMethodDecl *Method =
8823       D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8824   return (Method && Method->isStatic()) ? 1 : 0;
8825 }
8826 
8827 unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8828   if (!clang_isDeclaration(C.kind))
8829     return 0;
8830 
8831   const Decl *D = cxcursor::getCursorDecl(C);
8832   const CXXMethodDecl *Method =
8833       D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8834   return (Method && Method->isVirtual()) ? 1 : 0;
8835 }
8836 
8837 unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8838   if (!clang_isDeclaration(C.kind))
8839     return 0;
8840 
8841   const auto *D = cxcursor::getCursorDecl(C);
8842   const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8843   if (RD)
8844     RD = RD->getDefinition();
8845   return (RD && RD->isAbstract()) ? 1 : 0;
8846 }
8847 
8848 unsigned clang_EnumDecl_isScoped(CXCursor C) {
8849   if (!clang_isDeclaration(C.kind))
8850     return 0;
8851 
8852   const Decl *D = cxcursor::getCursorDecl(C);
8853   auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8854   return (Enum && Enum->isScoped()) ? 1 : 0;
8855 }
8856 
8857 //===----------------------------------------------------------------------===//
8858 // Attribute introspection.
8859 //===----------------------------------------------------------------------===//
8860 
8861 CXType clang_getIBOutletCollectionType(CXCursor C) {
8862   if (C.kind != CXCursor_IBOutletCollectionAttr)
8863     return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8864 
8865   const IBOutletCollectionAttr *A =
8866       cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8867 
8868   return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8869 }
8870 
8871 //===----------------------------------------------------------------------===//
8872 // Inspecting memory usage.
8873 //===----------------------------------------------------------------------===//
8874 
8875 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8876 
8877 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8878                                                 enum CXTUResourceUsageKind k,
8879                                                 unsigned long amount) {
8880   CXTUResourceUsageEntry entry = {k, amount};
8881   entries.push_back(entry);
8882 }
8883 
8884 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8885   const char *str = "";
8886   switch (kind) {
8887   case CXTUResourceUsage_AST:
8888     str = "ASTContext: expressions, declarations, and types";
8889     break;
8890   case CXTUResourceUsage_Identifiers:
8891     str = "ASTContext: identifiers";
8892     break;
8893   case CXTUResourceUsage_Selectors:
8894     str = "ASTContext: selectors";
8895     break;
8896   case CXTUResourceUsage_GlobalCompletionResults:
8897     str = "Code completion: cached global results";
8898     break;
8899   case CXTUResourceUsage_SourceManagerContentCache:
8900     str = "SourceManager: content cache allocator";
8901     break;
8902   case CXTUResourceUsage_AST_SideTables:
8903     str = "ASTContext: side tables";
8904     break;
8905   case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8906     str = "SourceManager: malloc'ed memory buffers";
8907     break;
8908   case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8909     str = "SourceManager: mmap'ed memory buffers";
8910     break;
8911   case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8912     str = "ExternalASTSource: malloc'ed memory buffers";
8913     break;
8914   case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8915     str = "ExternalASTSource: mmap'ed memory buffers";
8916     break;
8917   case CXTUResourceUsage_Preprocessor:
8918     str = "Preprocessor: malloc'ed memory";
8919     break;
8920   case CXTUResourceUsage_PreprocessingRecord:
8921     str = "Preprocessor: PreprocessingRecord";
8922     break;
8923   case CXTUResourceUsage_SourceManager_DataStructures:
8924     str = "SourceManager: data structures and tables";
8925     break;
8926   case CXTUResourceUsage_Preprocessor_HeaderSearch:
8927     str = "Preprocessor: header search tables";
8928     break;
8929   }
8930   return str;
8931 }
8932 
8933 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
8934   if (isNotUsableTU(TU)) {
8935     LOG_BAD_TU(TU);
8936     CXTUResourceUsage usage = {(void *)nullptr, 0, nullptr};
8937     return usage;
8938   }
8939 
8940   ASTUnit *astUnit = cxtu::getASTUnit(TU);
8941   std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
8942   ASTContext &astContext = astUnit->getASTContext();
8943 
8944   // How much memory is used by AST nodes and types?
8945   createCXTUResourceUsageEntry(
8946       *entries, CXTUResourceUsage_AST,
8947       (unsigned long)astContext.getASTAllocatedMemory());
8948 
8949   // How much memory is used by identifiers?
8950   createCXTUResourceUsageEntry(
8951       *entries, CXTUResourceUsage_Identifiers,
8952       (unsigned long)astContext.Idents.getAllocator().getTotalMemory());
8953 
8954   // How much memory is used for selectors?
8955   createCXTUResourceUsageEntry(
8956       *entries, CXTUResourceUsage_Selectors,
8957       (unsigned long)astContext.Selectors.getTotalMemory());
8958 
8959   // How much memory is used by ASTContext's side tables?
8960   createCXTUResourceUsageEntry(
8961       *entries, CXTUResourceUsage_AST_SideTables,
8962       (unsigned long)astContext.getSideTableAllocatedMemory());
8963 
8964   // How much memory is used for caching global code completion results?
8965   unsigned long completionBytes = 0;
8966   if (GlobalCodeCompletionAllocator *completionAllocator =
8967           astUnit->getCachedCompletionAllocator().get()) {
8968     completionBytes = completionAllocator->getTotalMemory();
8969   }
8970   createCXTUResourceUsageEntry(
8971       *entries, CXTUResourceUsage_GlobalCompletionResults, completionBytes);
8972 
8973   // How much memory is being used by SourceManager's content cache?
8974   createCXTUResourceUsageEntry(
8975       *entries, CXTUResourceUsage_SourceManagerContentCache,
8976       (unsigned long)astContext.getSourceManager().getContentCacheSize());
8977 
8978   // How much memory is being used by the MemoryBuffer's in SourceManager?
8979   const SourceManager::MemoryBufferSizes &srcBufs =
8980       astUnit->getSourceManager().getMemoryBufferSizes();
8981 
8982   createCXTUResourceUsageEntry(*entries,
8983                                CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8984                                (unsigned long)srcBufs.malloc_bytes);
8985   createCXTUResourceUsageEntry(*entries,
8986                                CXTUResourceUsage_SourceManager_Membuffer_MMap,
8987                                (unsigned long)srcBufs.mmap_bytes);
8988   createCXTUResourceUsageEntry(
8989       *entries, CXTUResourceUsage_SourceManager_DataStructures,
8990       (unsigned long)astContext.getSourceManager().getDataStructureSizes());
8991 
8992   // How much memory is being used by the ExternalASTSource?
8993   if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8994     const ExternalASTSource::MemoryBufferSizes &sizes =
8995         esrc->getMemoryBufferSizes();
8996 
8997     createCXTUResourceUsageEntry(
8998         *entries, CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8999         (unsigned long)sizes.malloc_bytes);
9000     createCXTUResourceUsageEntry(
9001         *entries, CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
9002         (unsigned long)sizes.mmap_bytes);
9003   }
9004 
9005   // How much memory is being used by the Preprocessor?
9006   Preprocessor &pp = astUnit->getPreprocessor();
9007   createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Preprocessor,
9008                                pp.getTotalMemory());
9009 
9010   if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
9011     createCXTUResourceUsageEntry(*entries,
9012                                  CXTUResourceUsage_PreprocessingRecord,
9013                                  pRec->getTotalMemory());
9014   }
9015 
9016   createCXTUResourceUsageEntry(*entries,
9017                                CXTUResourceUsage_Preprocessor_HeaderSearch,
9018                                pp.getHeaderSearchInfo().getTotalMemory());
9019 
9020   CXTUResourceUsage usage = {(void *)entries.get(), (unsigned)entries->size(),
9021                              !entries->empty() ? &(*entries)[0] : nullptr};
9022   (void)entries.release();
9023   return usage;
9024 }
9025 
9026 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
9027   if (usage.data)
9028     delete (MemUsageEntries *)usage.data;
9029 }
9030 
9031 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
9032   CXSourceRangeList *skipped = new CXSourceRangeList;
9033   skipped->count = 0;
9034   skipped->ranges = nullptr;
9035 
9036   if (isNotUsableTU(TU)) {
9037     LOG_BAD_TU(TU);
9038     return skipped;
9039   }
9040 
9041   if (!file)
9042     return skipped;
9043 
9044   ASTUnit *astUnit = cxtu::getASTUnit(TU);
9045   PreprocessingRecord *ppRec =
9046       astUnit->getPreprocessor().getPreprocessingRecord();
9047   if (!ppRec)
9048     return skipped;
9049 
9050   ASTContext &Ctx = astUnit->getASTContext();
9051   SourceManager &sm = Ctx.getSourceManager();
9052   FileEntry *fileEntry = static_cast<FileEntry *>(file);
9053   FileID wantedFileID = sm.translateFile(fileEntry);
9054   bool isMainFile = wantedFileID == sm.getMainFileID();
9055 
9056   const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
9057   std::vector<SourceRange> wantedRanges;
9058   for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(),
9059                                                 ei = SkippedRanges.end();
9060        i != ei; ++i) {
9061     if (sm.getFileID(i->getBegin()) == wantedFileID ||
9062         sm.getFileID(i->getEnd()) == wantedFileID)
9063       wantedRanges.push_back(*i);
9064     else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) ||
9065                             astUnit->isInPreambleFileID(i->getEnd())))
9066       wantedRanges.push_back(*i);
9067   }
9068 
9069   skipped->count = wantedRanges.size();
9070   skipped->ranges = new CXSourceRange[skipped->count];
9071   for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
9072     skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
9073 
9074   return skipped;
9075 }
9076 
9077 CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
9078   CXSourceRangeList *skipped = new CXSourceRangeList;
9079   skipped->count = 0;
9080   skipped->ranges = nullptr;
9081 
9082   if (isNotUsableTU(TU)) {
9083     LOG_BAD_TU(TU);
9084     return skipped;
9085   }
9086 
9087   ASTUnit *astUnit = cxtu::getASTUnit(TU);
9088   PreprocessingRecord *ppRec =
9089       astUnit->getPreprocessor().getPreprocessingRecord();
9090   if (!ppRec)
9091     return skipped;
9092 
9093   ASTContext &Ctx = astUnit->getASTContext();
9094 
9095   const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
9096 
9097   skipped->count = SkippedRanges.size();
9098   skipped->ranges = new CXSourceRange[skipped->count];
9099   for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
9100     skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
9101 
9102   return skipped;
9103 }
9104 
9105 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
9106   if (ranges) {
9107     delete[] ranges->ranges;
9108     delete ranges;
9109   }
9110 }
9111 
9112 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
9113   CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
9114   for (unsigned I = 0; I != Usage.numEntries; ++I)
9115     fprintf(stderr, "  %s: %lu\n",
9116             clang_getTUResourceUsageName(Usage.entries[I].kind),
9117             Usage.entries[I].amount);
9118 
9119   clang_disposeCXTUResourceUsage(Usage);
9120 }
9121 
9122 CXCursor clang_Cursor_getVarDeclInitializer(CXCursor cursor) {
9123   const Decl *const D = getCursorDecl(cursor);
9124   if (!D)
9125     return clang_getNullCursor();
9126   const auto *const VD = dyn_cast<VarDecl>(D);
9127   if (!VD)
9128     return clang_getNullCursor();
9129   const Expr *const Init = VD->getInit();
9130   if (!Init)
9131     return clang_getNullCursor();
9132 
9133   return cxcursor::MakeCXCursor(Init, VD, cxcursor::getCursorTU(cursor));
9134 }
9135 
9136 int clang_Cursor_hasVarDeclGlobalStorage(CXCursor cursor) {
9137   const Decl *const D = getCursorDecl(cursor);
9138   if (!D)
9139     return -1;
9140   const auto *const VD = dyn_cast<VarDecl>(D);
9141   if (!VD)
9142     return -1;
9143 
9144   return VD->hasGlobalStorage();
9145 }
9146 
9147 int clang_Cursor_hasVarDeclExternalStorage(CXCursor cursor) {
9148   const Decl *const D = getCursorDecl(cursor);
9149   if (!D)
9150     return -1;
9151   const auto *const VD = dyn_cast<VarDecl>(D);
9152   if (!VD)
9153     return -1;
9154 
9155   return VD->hasExternalStorage();
9156 }
9157 
9158 //===----------------------------------------------------------------------===//
9159 // Misc. utility functions.
9160 //===----------------------------------------------------------------------===//
9161 
9162 /// Default to using our desired 8 MB stack size on "safety" threads.
9163 static unsigned SafetyStackThreadSize = DesiredStackSize;
9164 
9165 namespace clang {
9166 
9167 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
9168                unsigned Size) {
9169   if (!Size)
9170     Size = GetSafetyThreadStackSize();
9171   if (Size && !getenv("LIBCLANG_NOTHREADS"))
9172     return CRC.RunSafelyOnThread(Fn, Size);
9173   return CRC.RunSafely(Fn);
9174 }
9175 
9176 unsigned GetSafetyThreadStackSize() { return SafetyStackThreadSize; }
9177 
9178 void SetSafetyThreadStackSize(unsigned Value) { SafetyStackThreadSize = Value; }
9179 
9180 } // namespace clang
9181 
9182 void clang::setThreadBackgroundPriority() {
9183   if (getenv("LIBCLANG_BGPRIO_DISABLE"))
9184     return;
9185 
9186 #if LLVM_ENABLE_THREADS
9187   // The function name setThreadBackgroundPriority is for historical reasons;
9188   // Low is more appropriate.
9189   llvm::set_thread_priority(llvm::ThreadPriority::Low);
9190 #endif
9191 }
9192 
9193 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
9194   if (!Unit)
9195     return;
9196 
9197   for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
9198                                      DEnd = Unit->stored_diag_end();
9199        D != DEnd; ++D) {
9200     CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
9201     CXString Msg =
9202         clang_formatDiagnostic(&Diag, clang_defaultDiagnosticDisplayOptions());
9203     fprintf(stderr, "%s\n", clang_getCString(Msg));
9204     clang_disposeString(Msg);
9205   }
9206 #ifdef _WIN32
9207   // On Windows, force a flush, since there may be multiple copies of
9208   // stderr and stdout in the file system, all with different buffers
9209   // but writing to the same device.
9210   fflush(stderr);
9211 #endif
9212 }
9213 
9214 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
9215                                  SourceLocation MacroDefLoc,
9216                                  CXTranslationUnit TU) {
9217   if (MacroDefLoc.isInvalid() || !TU)
9218     return nullptr;
9219   if (!II.hadMacroDefinition())
9220     return nullptr;
9221 
9222   ASTUnit *Unit = cxtu::getASTUnit(TU);
9223   Preprocessor &PP = Unit->getPreprocessor();
9224   MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
9225   if (MD) {
9226     for (MacroDirective::DefInfo Def = MD->getDefinition(); Def;
9227          Def = Def.getPreviousDefinition()) {
9228       if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
9229         return Def.getMacroInfo();
9230     }
9231   }
9232 
9233   return nullptr;
9234 }
9235 
9236 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
9237                                        CXTranslationUnit TU) {
9238   if (!MacroDef || !TU)
9239     return nullptr;
9240   const IdentifierInfo *II = MacroDef->getName();
9241   if (!II)
9242     return nullptr;
9243 
9244   return getMacroInfo(*II, MacroDef->getLocation(), TU);
9245 }
9246 
9247 MacroDefinitionRecord *
9248 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
9249                                         CXTranslationUnit TU) {
9250   if (!MI || !TU)
9251     return nullptr;
9252   if (Tok.isNot(tok::raw_identifier))
9253     return nullptr;
9254 
9255   if (MI->getNumTokens() == 0)
9256     return nullptr;
9257   SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
9258                        MI->getDefinitionEndLoc());
9259   ASTUnit *Unit = cxtu::getASTUnit(TU);
9260 
9261   // Check that the token is inside the definition and not its argument list.
9262   SourceManager &SM = Unit->getSourceManager();
9263   if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
9264     return nullptr;
9265   if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
9266     return nullptr;
9267 
9268   Preprocessor &PP = Unit->getPreprocessor();
9269   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
9270   if (!PPRec)
9271     return nullptr;
9272 
9273   IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
9274   if (!II.hadMacroDefinition())
9275     return nullptr;
9276 
9277   // Check that the identifier is not one of the macro arguments.
9278   if (llvm::is_contained(MI->params(), &II))
9279     return nullptr;
9280 
9281   MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
9282   if (!InnerMD)
9283     return nullptr;
9284 
9285   return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
9286 }
9287 
9288 MacroDefinitionRecord *
9289 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
9290                                         CXTranslationUnit TU) {
9291   if (Loc.isInvalid() || !MI || !TU)
9292     return nullptr;
9293 
9294   if (MI->getNumTokens() == 0)
9295     return nullptr;
9296   ASTUnit *Unit = cxtu::getASTUnit(TU);
9297   Preprocessor &PP = Unit->getPreprocessor();
9298   if (!PP.getPreprocessingRecord())
9299     return nullptr;
9300   Loc = Unit->getSourceManager().getSpellingLoc(Loc);
9301   Token Tok;
9302   if (PP.getRawToken(Loc, Tok))
9303     return nullptr;
9304 
9305   return checkForMacroInMacroDefinition(MI, Tok, TU);
9306 }
9307 
9308 CXString clang_getClangVersion() {
9309   return cxstring::createDup(getClangFullVersion());
9310 }
9311 
9312 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
9313   if (TU) {
9314     if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
9315       LogOS << '<' << Unit->getMainFileName() << '>';
9316       if (Unit->isMainFileAST())
9317         LogOS << " (" << Unit->getASTFileName() << ')';
9318       return *this;
9319     }
9320   } else {
9321     LogOS << "<NULL TU>";
9322   }
9323   return *this;
9324 }
9325 
9326 Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
9327   *this << FE->getName();
9328   return *this;
9329 }
9330 
9331 Logger &cxindex::Logger::operator<<(CXCursor cursor) {
9332   CXString cursorName = clang_getCursorDisplayName(cursor);
9333   *this << cursorName << "@" << clang_getCursorLocation(cursor);
9334   clang_disposeString(cursorName);
9335   return *this;
9336 }
9337 
9338 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
9339   CXFile File;
9340   unsigned Line, Column;
9341   clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
9342   CXString FileName = clang_getFileName(File);
9343   *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
9344   clang_disposeString(FileName);
9345   return *this;
9346 }
9347 
9348 Logger &cxindex::Logger::operator<<(CXSourceRange range) {
9349   CXSourceLocation BLoc = clang_getRangeStart(range);
9350   CXSourceLocation ELoc = clang_getRangeEnd(range);
9351 
9352   CXFile BFile;
9353   unsigned BLine, BColumn;
9354   clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
9355 
9356   CXFile EFile;
9357   unsigned ELine, EColumn;
9358   clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
9359 
9360   CXString BFileName = clang_getFileName(BFile);
9361   if (BFile == EFile) {
9362     *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
9363                           BLine, BColumn, ELine, EColumn);
9364   } else {
9365     CXString EFileName = clang_getFileName(EFile);
9366     *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName), BLine,
9367                           BColumn)
9368           << llvm::format("%s:%d:%d]", clang_getCString(EFileName), ELine,
9369                           EColumn);
9370     clang_disposeString(EFileName);
9371   }
9372   clang_disposeString(BFileName);
9373   return *this;
9374 }
9375 
9376 Logger &cxindex::Logger::operator<<(CXString Str) {
9377   *this << clang_getCString(Str);
9378   return *this;
9379 }
9380 
9381 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
9382   LogOS << Fmt;
9383   return *this;
9384 }
9385 
9386 static llvm::ManagedStatic<std::mutex> LoggingMutex;
9387 
9388 cxindex::Logger::~Logger() {
9389   std::lock_guard<std::mutex> L(*LoggingMutex);
9390 
9391   static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
9392 
9393   raw_ostream &OS = llvm::errs();
9394   OS << "[libclang:" << Name << ':';
9395 
9396 #ifdef USE_DARWIN_THREADS
9397   // TODO: Portability.
9398   mach_port_t tid = pthread_mach_thread_np(pthread_self());
9399   OS << tid << ':';
9400 #endif
9401 
9402   llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
9403   OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
9404   OS << Msg << '\n';
9405 
9406   if (Trace) {
9407     llvm::sys::PrintStackTrace(OS);
9408     OS << "--------------------------------------------------\n";
9409   }
9410 }
9411