Bug Summary

File:tools/clang/tools/libclang/CIndex.cpp
Warning:line 3972, column 5
Called C++ object pointer is null

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/tools/libclang/CIndex.cpp

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