Bug Summary

File:tools/clang/tools/libclang/CIndex.cpp
Warning:line 7930, column 42
Dereference of null pointer

Annotated Source Code

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