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