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