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