Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CIndex.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D CLANG_TOOL_EXTRA_BUILD -D _CINDEX_LIB_ -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/tools/libclang -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/tools/libclang -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp -faddrsig
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/Stack.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/Version.h"
32#include "clang/Frontend/ASTUnit.h"
33#include "clang/Frontend/CompilerInstance.h"
34#include "clang/Frontend/FrontendDiagnostic.h"
35#include "clang/Index/CodegenNameGenerator.h"
36#include "clang/Index/CommentToXML.h"
37#include "clang/Lex/HeaderSearch.h"
38#include "clang/Lex/Lexer.h"
39#include "clang/Lex/PreprocessingRecord.h"
40#include "clang/Lex/Preprocessor.h"
41#include "clang/Serialization/SerializationDiagnostic.h"
42#include "llvm/ADT/Optional.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringSwitch.h"
45#include "llvm/Config/llvm-config.h"
46#include "llvm/Support/Compiler.h"
47#include "llvm/Support/CrashRecoveryContext.h"
48#include "llvm/Support/Format.h"
49#include "llvm/Support/ManagedStatic.h"
50#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/Mutex.h"
52#include "llvm/Support/Program.h"
53#include "llvm/Support/SaveAndRestore.h"
54#include "llvm/Support/Signals.h"
55#include "llvm/Support/TargetSelect.h"
56#include "llvm/Support/Threading.h"
57#include "llvm/Support/Timer.h"
58#include "llvm/Support/raw_ostream.h"
59
60#if LLVM_ENABLE_THREADS1 != 0 && defined(__APPLE__)
61#define USE_DARWIN_THREADS
62#endif
63
64#ifdef USE_DARWIN_THREADS
65#include <pthread.h>
66#endif
67
68using namespace clang;
69using namespace clang::cxcursor;
70using namespace clang::cxtu;
71using namespace clang::cxindex;
72
73CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
74 std::unique_ptr<ASTUnit> AU) {
75 if (!AU)
76 return nullptr;
77 assert(CIdx)((CIdx) ? static_cast<void> (0) : __assert_fail ("CIdx"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 77, __PRETTY_FUNCTION__))
;
78 CXTranslationUnit D = new CXTranslationUnitImpl();
79 D->CIdx = CIdx;
80 D->TheASTUnit = AU.release();
81 D->StringPool = new cxstring::CXStringPool();
82 D->Diagnostics = nullptr;
83 D->OverridenCursorsPool = createOverridenCXCursorsPool();
84 D->CommentToXML = nullptr;
85 D->ParsingOptions = 0;
86 D->Arguments = {};
87 return D;
88}
89
90bool cxtu::isASTReadError(ASTUnit *AU) {
91 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
92 DEnd = AU->stored_diag_end();
93 D != DEnd; ++D) {
94 if (D->getLevel() >= DiagnosticsEngine::Error &&
95 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
96 diag::DiagCat_AST_Deserialization_Issue)
97 return true;
98 }
99 return false;
100}
101
102cxtu::CXTUOwner::~CXTUOwner() {
103 if (TU)
104 clang_disposeTranslationUnit(TU);
105}
106
107/// Compare two source ranges to determine their relative position in
108/// the translation unit.
109static RangeComparisonResult RangeCompare(SourceManager &SM,
110 SourceRange R1,
111 SourceRange R2) {
112 assert(R1.isValid() && "First range is invalid?")((R1.isValid() && "First range is invalid?") ? static_cast
<void> (0) : __assert_fail ("R1.isValid() && \"First range is invalid?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 112, __PRETTY_FUNCTION__))
;
113 assert(R2.isValid() && "Second range is invalid?")((R2.isValid() && "Second range is invalid?") ? static_cast
<void> (0) : __assert_fail ("R2.isValid() && \"Second range is invalid?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 113, __PRETTY_FUNCTION__))
;
114 if (R1.getEnd() != R2.getBegin() &&
115 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
116 return RangeBefore;
117 if (R2.getEnd() != R1.getBegin() &&
118 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
119 return RangeAfter;
120 return RangeOverlap;
121}
122
123/// Determine if a source location falls within, before, or after a
124/// a given source range.
125static RangeComparisonResult LocationCompare(SourceManager &SM,
126 SourceLocation L, SourceRange R) {
127 assert(R.isValid() && "First range is invalid?")((R.isValid() && "First range is invalid?") ? static_cast
<void> (0) : __assert_fail ("R.isValid() && \"First range is invalid?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 127, __PRETTY_FUNCTION__))
;
128 assert(L.isValid() && "Second range is invalid?")((L.isValid() && "Second range is invalid?") ? static_cast
<void> (0) : __assert_fail ("L.isValid() && \"Second range is invalid?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 128, __PRETTY_FUNCTION__))
;
129 if (L == R.getBegin() || L == R.getEnd())
130 return RangeOverlap;
131 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
132 return RangeBefore;
133 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
134 return RangeAfter;
135 return RangeOverlap;
136}
137
138/// Translate a Clang source range into a CIndex source range.
139///
140/// Clang internally represents ranges where the end location points to the
141/// start of the token at the end. However, for external clients it is more
142/// useful to have a CXSourceRange be a proper half-open interval. This routine
143/// does the appropriate translation.
144CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
145 const LangOptions &LangOpts,
146 const CharSourceRange &R) {
147 // We want the last character in this location, so we will adjust the
148 // location accordingly.
149 SourceLocation EndLoc = R.getEnd();
150 bool IsTokenRange = R.isTokenRange();
151 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
152 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
153 EndLoc = Expansion.getEnd();
154 IsTokenRange = Expansion.isTokenRange();
155 }
156 if (IsTokenRange && EndLoc.isValid()) {
157 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
158 SM, LangOpts);
159 EndLoc = EndLoc.getLocWithOffset(Length);
160 }
161
162 CXSourceRange Result = {
163 { &SM, &LangOpts },
164 R.getBegin().getRawEncoding(),
165 EndLoc.getRawEncoding()
166 };
167 return Result;
168}
169
170//===----------------------------------------------------------------------===//
171// Cursor visitor.
172//===----------------------------------------------------------------------===//
173
174static SourceRange getRawCursorExtent(CXCursor C);
175static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
176
177
178RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
179 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
180}
181
182/// Visit the given cursor and, if requested by the visitor,
183/// its children.
184///
185/// \param Cursor the cursor to visit.
186///
187/// \param CheckedRegionOfInterest if true, then the caller already checked
188/// that this cursor is within the region of interest.
189///
190/// \returns true if the visitation should be aborted, false if it
191/// should continue.
192bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
193 if (clang_isInvalid(Cursor.kind))
194 return false;
195
196 if (clang_isDeclaration(Cursor.kind)) {
197 const Decl *D = getCursorDecl(Cursor);
198 if (!D) {
199 assert(0 && "Invalid declaration cursor")((0 && "Invalid declaration cursor") ? static_cast<
void> (0) : __assert_fail ("0 && \"Invalid declaration cursor\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 199, __PRETTY_FUNCTION__))
;
200 return true; // abort.
201 }
202
203 // Ignore implicit declarations, unless it's an objc method because
204 // currently we should report implicit methods for properties when indexing.
205 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
206 return false;
207 }
208
209 // If we have a range of interest, and this cursor doesn't intersect with it,
210 // we're done.
211 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
212 SourceRange Range = getRawCursorExtent(Cursor);
213 if (Range.isInvalid() || CompareRegionOfInterest(Range))
214 return false;
215 }
216
217 switch (Visitor(Cursor, Parent, ClientData)) {
218 case CXChildVisit_Break:
219 return true;
220
221 case CXChildVisit_Continue:
222 return false;
223
224 case CXChildVisit_Recurse: {
225 bool ret = VisitChildren(Cursor);
226 if (PostChildrenVisitor)
227 if (PostChildrenVisitor(Cursor, ClientData))
228 return true;
229 return ret;
230 }
231 }
232
233 llvm_unreachable("Invalid CXChildVisitResult!")::llvm::llvm_unreachable_internal("Invalid CXChildVisitResult!"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 233)
;
234}
235
236static bool visitPreprocessedEntitiesInRange(SourceRange R,
237 PreprocessingRecord &PPRec,
238 CursorVisitor &Visitor) {
239 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
240 FileID FID;
241
242 if (!Visitor.shouldVisitIncludedEntities()) {
243 // If the begin/end of the range lie in the same FileID, do the optimization
244 // where we skip preprocessed entities that do not come from the same FileID.
245 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
246 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
247 FID = FileID();
248 }
249
250 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
251 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
252 PPRec, FID);
253}
254
255bool CursorVisitor::visitFileRegion() {
256 if (RegionOfInterest.isInvalid())
257 return false;
258
259 ASTUnit *Unit = cxtu::getASTUnit(TU);
260 SourceManager &SM = Unit->getSourceManager();
261
262 std::pair<FileID, unsigned>
263 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
264 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
265
266 if (End.first != Begin.first) {
267 // If the end does not reside in the same file, try to recover by
268 // picking the end of the file of begin location.
269 End.first = Begin.first;
270 End.second = SM.getFileIDSize(Begin.first);
271 }
272
273 assert(Begin.first == End.first)((Begin.first == End.first) ? static_cast<void> (0) : __assert_fail
("Begin.first == End.first", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 273, __PRETTY_FUNCTION__))
;
274 if (Begin.second > End.second)
275 return false;
276
277 FileID File = Begin.first;
278 unsigned Offset = Begin.second;
279 unsigned Length = End.second - Begin.second;
280
281 if (!VisitDeclsOnly && !VisitPreprocessorLast)
282 if (visitPreprocessedEntitiesInRegion())
283 return true; // visitation break.
284
285 if (visitDeclsFromFileRegion(File, Offset, Length))
286 return true; // visitation break.
287
288 if (!VisitDeclsOnly && VisitPreprocessorLast)
289 return visitPreprocessedEntitiesInRegion();
290
291 return false;
292}
293
294static bool isInLexicalContext(Decl *D, DeclContext *DC) {
295 if (!DC)
296 return false;
297
298 for (DeclContext *DeclDC = D->getLexicalDeclContext();
299 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
300 if (DeclDC == DC)
301 return true;
302 }
303 return false;
304}
305
306bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
307 unsigned Offset, unsigned Length) {
308 ASTUnit *Unit = cxtu::getASTUnit(TU);
309 SourceManager &SM = Unit->getSourceManager();
310 SourceRange Range = RegionOfInterest;
311
312 SmallVector<Decl *, 16> Decls;
313 Unit->findFileRegionDecls(File, Offset, Length, Decls);
314
315 // If we didn't find any file level decls for the file, try looking at the
316 // file that it was included from.
317 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
318 bool Invalid = false;
319 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
320 if (Invalid)
321 return false;
322
323 SourceLocation Outer;
324 if (SLEntry.isFile())
325 Outer = SLEntry.getFile().getIncludeLoc();
326 else
327 Outer = SLEntry.getExpansion().getExpansionLocStart();
328 if (Outer.isInvalid())
329 return false;
330
331 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
332 Length = 0;
333 Unit->findFileRegionDecls(File, Offset, Length, Decls);
334 }
335
336 assert(!Decls.empty())((!Decls.empty()) ? static_cast<void> (0) : __assert_fail
("!Decls.empty()", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 336, __PRETTY_FUNCTION__))
;
337
338 bool VisitedAtLeastOnce = false;
339 DeclContext *CurDC = nullptr;
340 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
341 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
342 Decl *D = *DIt;
343 if (D->getSourceRange().isInvalid())
344 continue;
345
346 if (isInLexicalContext(D, CurDC))
347 continue;
348
349 CurDC = dyn_cast<DeclContext>(D);
350
351 if (TagDecl *TD = dyn_cast<TagDecl>(D))
352 if (!TD->isFreeStanding())
353 continue;
354
355 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
356 if (CompRes == RangeBefore)
357 continue;
358 if (CompRes == RangeAfter)
359 break;
360
361 assert(CompRes == RangeOverlap)((CompRes == RangeOverlap) ? static_cast<void> (0) : __assert_fail
("CompRes == RangeOverlap", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 361, __PRETTY_FUNCTION__))
;
362 VisitedAtLeastOnce = true;
363
364 if (isa<ObjCContainerDecl>(D)) {
365 FileDI_current = &DIt;
366 FileDE_current = DE;
367 } else {
368 FileDI_current = nullptr;
369 }
370
371 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
372 return true; // visitation break.
373 }
374
375 if (VisitedAtLeastOnce)
376 return false;
377
378 // No Decls overlapped with the range. Move up the lexical context until there
379 // is a context that contains the range or we reach the translation unit
380 // level.
381 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
382 : (*(DIt-1))->getLexicalDeclContext();
383
384 while (DC && !DC->isTranslationUnit()) {
385 Decl *D = cast<Decl>(DC);
386 SourceRange CurDeclRange = D->getSourceRange();
387 if (CurDeclRange.isInvalid())
388 break;
389
390 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
391 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
392 return true; // visitation break.
393 }
394
395 DC = D->getLexicalDeclContext();
396 }
397
398 return false;
399}
400
401bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
402 if (!AU->getPreprocessor().getPreprocessingRecord())
403 return false;
404
405 PreprocessingRecord &PPRec
406 = *AU->getPreprocessor().getPreprocessingRecord();
407 SourceManager &SM = AU->getSourceManager();
408
409 if (RegionOfInterest.isValid()) {
410 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
411 SourceLocation B = MappedRange.getBegin();
412 SourceLocation E = MappedRange.getEnd();
413
414 if (AU->isInPreambleFileID(B)) {
415 if (SM.isLoadedSourceLocation(E))
416 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
417 PPRec, *this);
418
419 // Beginning of range lies in the preamble but it also extends beyond
420 // it into the main file. Split the range into 2 parts, one covering
421 // the preamble and another covering the main file. This allows subsequent
422 // calls to visitPreprocessedEntitiesInRange to accept a source range that
423 // lies in the same FileID, allowing it to skip preprocessed entities that
424 // do not come from the same FileID.
425 bool breaked =
426 visitPreprocessedEntitiesInRange(
427 SourceRange(B, AU->getEndOfPreambleFileID()),
428 PPRec, *this);
429 if (breaked) return true;
430 return visitPreprocessedEntitiesInRange(
431 SourceRange(AU->getStartOfMainFileID(), E),
432 PPRec, *this);
433 }
434
435 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
436 }
437
438 bool OnlyLocalDecls
439 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
440
441 if (OnlyLocalDecls)
442 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
443 PPRec);
444
445 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
446}
447
448template<typename InputIterator>
449bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
450 InputIterator Last,
451 PreprocessingRecord &PPRec,
452 FileID FID) {
453 for (; First != Last; ++First) {
454 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
455 continue;
456
457 PreprocessedEntity *PPE = *First;
458 if (!PPE)
459 continue;
460
461 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
462 if (Visit(MakeMacroExpansionCursor(ME, TU)))
463 return true;
464
465 continue;
466 }
467
468 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
469 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
470 return true;
471
472 continue;
473 }
474
475 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
476 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
477 return true;
478
479 continue;
480 }
481 }
482
483 return false;
484}
485
486/// Visit the children of the given cursor.
487///
488/// \returns true if the visitation should be aborted, false if it
489/// should continue.
490bool CursorVisitor::VisitChildren(CXCursor Cursor) {
491 if (clang_isReference(Cursor.kind) &&
492 Cursor.kind != CXCursor_CXXBaseSpecifier) {
493 // By definition, references have no children.
494 return false;
495 }
496
497 // Set the Parent field to Cursor, then back to its old value once we're
498 // done.
499 SetParentRAII SetParent(Parent, StmtParent, Cursor);
500
501 if (clang_isDeclaration(Cursor.kind)) {
502 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
503 if (!D)
504 return false;
505
506 return VisitAttributes(D) || Visit(D);
507 }
508
509 if (clang_isStatement(Cursor.kind)) {
510 if (const Stmt *S = getCursorStmt(Cursor))
511 return Visit(S);
512
513 return false;
514 }
515
516 if (clang_isExpression(Cursor.kind)) {
517 if (const Expr *E = getCursorExpr(Cursor))
518 return Visit(E);
519
520 return false;
521 }
522
523 if (clang_isTranslationUnit(Cursor.kind)) {
524 CXTranslationUnit TU = getCursorTU(Cursor);
525 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
526
527 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
528 for (unsigned I = 0; I != 2; ++I) {
529 if (VisitOrder[I]) {
530 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
531 RegionOfInterest.isInvalid()) {
532 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
533 TLEnd = CXXUnit->top_level_end();
534 TL != TLEnd; ++TL) {
535 const Optional<bool> V = handleDeclForVisitation(*TL);
536 if (!V.hasValue())
537 continue;
538 return V.getValue();
539 }
540 } else if (VisitDeclContext(
541 CXXUnit->getASTContext().getTranslationUnitDecl()))
542 return true;
543 continue;
544 }
545
546 // Walk the preprocessing record.
547 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
548 visitPreprocessedEntitiesInRegion();
549 }
550
551 return false;
552 }
553
554 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
555 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
556 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
557 return Visit(BaseTSInfo->getTypeLoc());
558 }
559 }
560 }
561
562 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
563 const IBOutletCollectionAttr *A =
564 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
565 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
566 return Visit(cxcursor::MakeCursorObjCClassRef(
567 ObjT->getInterface(),
568 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
569 }
570
571 // If pointing inside a macro definition, check if the token is an identifier
572 // that was ever defined as a macro. In such a case, create a "pseudo" macro
573 // expansion cursor for that token.
574 SourceLocation BeginLoc = RegionOfInterest.getBegin();
575 if (Cursor.kind == CXCursor_MacroDefinition &&
576 BeginLoc == RegionOfInterest.getEnd()) {
577 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
578 const MacroInfo *MI =
579 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
580 if (MacroDefinitionRecord *MacroDef =
581 checkForMacroInMacroDefinition(MI, Loc, TU))
582 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
583 }
584
585 // Nothing to visit at the moment.
586 return false;
587}
588
589bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
590 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
591 if (Visit(TSInfo->getTypeLoc()))
592 return true;
593
594 if (Stmt *Body = B->getBody())
595 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
596
597 return false;
598}
599
600Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
601 if (RegionOfInterest.isValid()) {
602 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
603 if (Range.isInvalid())
604 return None;
605
606 switch (CompareRegionOfInterest(Range)) {
607 case RangeBefore:
608 // This declaration comes before the region of interest; skip it.
609 return None;
610
611 case RangeAfter:
612 // This declaration comes after the region of interest; we're done.
613 return false;
614
615 case RangeOverlap:
616 // This declaration overlaps the region of interest; visit it.
617 break;
618 }
619 }
620 return true;
621}
622
623bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
624 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
625
626 // FIXME: Eventually remove. This part of a hack to support proper
627 // iteration over all Decls contained lexically within an ObjC container.
628 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
629 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
630
631 for ( ; I != E; ++I) {
632 Decl *D = *I;
633 if (D->getLexicalDeclContext() != DC)
634 continue;
635 const Optional<bool> V = handleDeclForVisitation(D);
636 if (!V.hasValue())
637 continue;
638 return V.getValue();
639 }
640 return false;
641}
642
643Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
644 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
645
646 // Ignore synthesized ivars here, otherwise if we have something like:
647 // @synthesize prop = _prop;
648 // and '_prop' is not declared, we will encounter a '_prop' ivar before
649 // encountering the 'prop' synthesize declaration and we will think that
650 // we passed the region-of-interest.
651 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
652 if (ivarD->getSynthesize())
653 return None;
654 }
655
656 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
657 // declarations is a mismatch with the compiler semantics.
658 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
659 auto *ID = cast<ObjCInterfaceDecl>(D);
660 if (!ID->isThisDeclarationADefinition())
661 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
662
663 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
664 auto *PD = cast<ObjCProtocolDecl>(D);
665 if (!PD->isThisDeclarationADefinition())
666 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
667 }
668
669 const Optional<bool> V = shouldVisitCursor(Cursor);
670 if (!V.hasValue())
671 return None;
672 if (!V.getValue())
673 return false;
674 if (Visit(Cursor, true))
675 return true;
676 return None;
677}
678
679bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
680 llvm_unreachable("Translation units are visited directly by Visit()")::llvm::llvm_unreachable_internal("Translation units are visited directly by Visit()"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 680)
;
681}
682
683bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
684 if (VisitTemplateParameters(D->getTemplateParameters()))
685 return true;
686
687 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
688}
689
690bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
691 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
692 return Visit(TSInfo->getTypeLoc());
693
694 return false;
695}
696
697bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
698 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
699 return Visit(TSInfo->getTypeLoc());
700
701 return false;
702}
703
704bool CursorVisitor::VisitTagDecl(TagDecl *D) {
705 return VisitDeclContext(D);
706}
707
708bool CursorVisitor::VisitClassTemplateSpecializationDecl(
709 ClassTemplateSpecializationDecl *D) {
710 bool ShouldVisitBody = false;
711 switch (D->getSpecializationKind()) {
712 case TSK_Undeclared:
713 case TSK_ImplicitInstantiation:
714 // Nothing to visit
715 return false;
716
717 case TSK_ExplicitInstantiationDeclaration:
718 case TSK_ExplicitInstantiationDefinition:
719 break;
720
721 case TSK_ExplicitSpecialization:
722 ShouldVisitBody = true;
723 break;
724 }
725
726 // Visit the template arguments used in the specialization.
727 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
728 TypeLoc TL = SpecType->getTypeLoc();
729 if (TemplateSpecializationTypeLoc TSTLoc =
730 TL.getAs<TemplateSpecializationTypeLoc>()) {
731 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
732 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
733 return true;
734 }
735 }
736
737 return ShouldVisitBody && VisitCXXRecordDecl(D);
738}
739
740bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
741 ClassTemplatePartialSpecializationDecl *D) {
742 // FIXME: Visit the "outer" template parameter lists on the TagDecl
743 // before visiting these template parameters.
744 if (VisitTemplateParameters(D->getTemplateParameters()))
745 return true;
746
747 // Visit the partial specialization arguments.
748 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
749 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
750 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
751 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
752 return true;
753
754 return VisitCXXRecordDecl(D);
755}
756
757bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
758 // Visit the default argument.
759 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
760 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
761 if (Visit(DefArg->getTypeLoc()))
762 return true;
763
764 return false;
765}
766
767bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
768 if (Expr *Init = D->getInitExpr())
769 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
770 return false;
771}
772
773bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
774 unsigned NumParamList = DD->getNumTemplateParameterLists();
775 for (unsigned i = 0; i < NumParamList; i++) {
776 TemplateParameterList* Params = DD->getTemplateParameterList(i);
777 if (VisitTemplateParameters(Params))
778 return true;
779 }
780
781 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
782 if (Visit(TSInfo->getTypeLoc()))
783 return true;
784
785 // Visit the nested-name-specifier, if present.
786 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
787 if (VisitNestedNameSpecifierLoc(QualifierLoc))
788 return true;
789
790 return false;
791}
792
793static bool HasTrailingReturnType(FunctionDecl *ND) {
794 const QualType Ty = ND->getType();
795 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
796 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
797 return FT->hasTrailingReturn();
798 }
799
800 return false;
801}
802
803/// Compare two base or member initializers based on their source order.
804static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
805 CXXCtorInitializer *const *Y) {
806 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
807}
808
809bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
810 unsigned NumParamList = ND->getNumTemplateParameterLists();
811 for (unsigned i = 0; i < NumParamList; i++) {
812 TemplateParameterList* Params = ND->getTemplateParameterList(i);
813 if (VisitTemplateParameters(Params))
814 return true;
815 }
816
817 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
818 // Visit the function declaration's syntactic components in the order
819 // written. This requires a bit of work.
820 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
821 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
822 const bool HasTrailingRT = HasTrailingReturnType(ND);
823
824 // If we have a function declared directly (without the use of a typedef),
825 // visit just the return type. Otherwise, just visit the function's type
826 // now.
827 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
828 Visit(FTL.getReturnLoc())) ||
829 (!FTL && Visit(TL)))
830 return true;
831
832 // Visit the nested-name-specifier, if present.
833 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
834 if (VisitNestedNameSpecifierLoc(QualifierLoc))
835 return true;
836
837 // Visit the declaration name.
838 if (!isa<CXXDestructorDecl>(ND))
839 if (VisitDeclarationNameInfo(ND->getNameInfo()))
840 return true;
841
842 // FIXME: Visit explicitly-specified template arguments!
843
844 // Visit the function parameters, if we have a function type.
845 if (FTL && VisitFunctionTypeLoc(FTL, true))
846 return true;
847
848 // Visit the function's trailing return type.
849 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
850 return true;
851
852 // FIXME: Attributes?
853 }
854
855 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
856 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
857 // Find the initializers that were written in the source.
858 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
859 for (auto *I : Constructor->inits()) {
860 if (!I->isWritten())
861 continue;
862
863 WrittenInits.push_back(I);
864 }
865
866 // Sort the initializers in source order
867 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
868 &CompareCXXCtorInitializers);
869
870 // Visit the initializers in source order
871 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
872 CXXCtorInitializer *Init = WrittenInits[I];
873 if (Init->isAnyMemberInitializer()) {
874 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
875 Init->getMemberLocation(), TU)))
876 return true;
877 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
878 if (Visit(TInfo->getTypeLoc()))
879 return true;
880 }
881
882 // Visit the initializer value.
883 if (Expr *Initializer = Init->getInit())
884 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
885 return true;
886 }
887 }
888
889 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
890 return true;
891 }
892
893 return false;
894}
895
896bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
897 if (VisitDeclaratorDecl(D))
898 return true;
899
900 if (Expr *BitWidth = D->getBitWidth())
901 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
902
903 if (Expr *Init = D->getInClassInitializer())
904 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
905
906 return false;
907}
908
909bool CursorVisitor::VisitVarDecl(VarDecl *D) {
910 if (VisitDeclaratorDecl(D))
911 return true;
912
913 if (Expr *Init = D->getInit())
914 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
915
916 return false;
917}
918
919bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
920 if (VisitDeclaratorDecl(D))
921 return true;
922
923 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
924 if (Expr *DefArg = D->getDefaultArgument())
925 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
926
927 return false;
928}
929
930bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
931 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
932 // before visiting these template parameters.
933 if (VisitTemplateParameters(D->getTemplateParameters()))
934 return true;
935
936 auto* FD = D->getTemplatedDecl();
937 return VisitAttributes(FD) || VisitFunctionDecl(FD);
938}
939
940bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
941 // FIXME: Visit the "outer" template parameter lists on the TagDecl
942 // before visiting these template parameters.
943 if (VisitTemplateParameters(D->getTemplateParameters()))
944 return true;
945
946 auto* CD = D->getTemplatedDecl();
947 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
948}
949
950bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
951 if (VisitTemplateParameters(D->getTemplateParameters()))
952 return true;
953
954 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
955 VisitTemplateArgumentLoc(D->getDefaultArgument()))
956 return true;
957
958 return false;
959}
960
961bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
962 // Visit the bound, if it's explicit.
963 if (D->hasExplicitBound()) {
964 if (auto TInfo = D->getTypeSourceInfo()) {
965 if (Visit(TInfo->getTypeLoc()))
966 return true;
967 }
968 }
969
970 return false;
971}
972
973bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
974 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
975 if (Visit(TSInfo->getTypeLoc()))
976 return true;
977
978 for (const auto *P : ND->parameters()) {
979 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
980 return true;
981 }
982
983 return ND->isThisDeclarationADefinition() &&
984 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
985}
986
987template <typename DeclIt>
988static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
989 SourceManager &SM, SourceLocation EndLoc,
990 SmallVectorImpl<Decl *> &Decls) {
991 DeclIt next = *DI_current;
992 while (++next != DE_current) {
993 Decl *D_next = *next;
994 if (!D_next)
995 break;
996 SourceLocation L = D_next->getBeginLoc();
997 if (!L.isValid())
998 break;
999 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1000 *DI_current = next;
1001 Decls.push_back(D_next);
1002 continue;
1003 }
1004 break;
1005 }
1006}
1007
1008bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1009 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1010 // an @implementation can lexically contain Decls that are not properly
1011 // nested in the AST. When we identify such cases, we need to retrofit
1012 // this nesting here.
1013 if (!DI_current && !FileDI_current)
1014 return VisitDeclContext(D);
1015
1016 // Scan the Decls that immediately come after the container
1017 // in the current DeclContext. If any fall within the
1018 // container's lexical region, stash them into a vector
1019 // for later processing.
1020 SmallVector<Decl *, 24> DeclsInContainer;
1021 SourceLocation EndLoc = D->getSourceRange().getEnd();
1022 SourceManager &SM = AU->getSourceManager();
1023 if (EndLoc.isValid()) {
1024 if (DI_current) {
1025 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1026 DeclsInContainer);
1027 } else {
1028 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1029 DeclsInContainer);
1030 }
1031 }
1032
1033 // The common case.
1034 if (DeclsInContainer.empty())
1035 return VisitDeclContext(D);
1036
1037 // Get all the Decls in the DeclContext, and sort them with the
1038 // additional ones we've collected. Then visit them.
1039 for (auto *SubDecl : D->decls()) {
1040 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1041 SubDecl->getBeginLoc().isInvalid())
1042 continue;
1043 DeclsInContainer.push_back(SubDecl);
1044 }
1045
1046 // Now sort the Decls so that they appear in lexical order.
1047 llvm::sort(DeclsInContainer,
1048 [&SM](Decl *A, Decl *B) {
1049 SourceLocation L_A = A->getBeginLoc();
1050 SourceLocation L_B = B->getBeginLoc();
1051 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
1052 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1053 B->getEndLoc());
1054 });
1055
1056 // Now visit the decls.
1057 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1058 E = DeclsInContainer.end(); I != E; ++I) {
1059 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1060 const Optional<bool> &V = shouldVisitCursor(Cursor);
1061 if (!V.hasValue())
1062 continue;
1063 if (!V.getValue())
1064 return false;
1065 if (Visit(Cursor, true))
1066 return true;
1067 }
1068 return false;
1069}
1070
1071bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1072 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1073 TU)))
1074 return true;
1075
1076 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1077 return true;
1078
1079 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1080 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1081 E = ND->protocol_end(); I != E; ++I, ++PL)
1082 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1083 return true;
1084
1085 return VisitObjCContainerDecl(ND);
1086}
1087
1088bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1089 if (!PID->isThisDeclarationADefinition())
1090 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1091
1092 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1093 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1094 E = PID->protocol_end(); I != E; ++I, ++PL)
1095 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1096 return true;
1097
1098 return VisitObjCContainerDecl(PID);
1099}
1100
1101bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1102 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1103 return true;
1104
1105 // FIXME: This implements a workaround with @property declarations also being
1106 // installed in the DeclContext for the @interface. Eventually this code
1107 // should be removed.
1108 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1109 if (!CDecl || !CDecl->IsClassExtension())
1110 return false;
1111
1112 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1113 if (!ID)
1114 return false;
1115
1116 IdentifierInfo *PropertyId = PD->getIdentifier();
1117 ObjCPropertyDecl *prevDecl =
1118 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1119 PD->getQueryKind());
1120
1121 if (!prevDecl)
1122 return false;
1123
1124 // Visit synthesized methods since they will be skipped when visiting
1125 // the @interface.
1126 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1127 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1128 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1129 return true;
1130
1131 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1132 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1133 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1134 return true;
1135
1136 return false;
1137}
1138
1139bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1140 if (!typeParamList)
1141 return false;
1142
1143 for (auto *typeParam : *typeParamList) {
1144 // Visit the type parameter.
1145 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1146 return true;
1147 }
1148
1149 return false;
1150}
1151
1152bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1153 if (!D->isThisDeclarationADefinition()) {
1154 // Forward declaration is treated like a reference.
1155 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1156 }
1157
1158 // Objective-C type parameters.
1159 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1160 return true;
1161
1162 // Issue callbacks for super class.
1163 if (D->getSuperClass() &&
1164 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1165 D->getSuperClassLoc(),
1166 TU)))
1167 return true;
1168
1169 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1170 if (Visit(SuperClassTInfo->getTypeLoc()))
1171 return true;
1172
1173 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1174 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1175 E = D->protocol_end(); I != E; ++I, ++PL)
1176 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1177 return true;
1178
1179 return VisitObjCContainerDecl(D);
1180}
1181
1182bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1183 return VisitObjCContainerDecl(D);
1184}
1185
1186bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1187 // 'ID' could be null when dealing with invalid code.
1188 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1189 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1190 return true;
1191
1192 return VisitObjCImplDecl(D);
1193}
1194
1195bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1196#if 0
1197 // Issue callbacks for super class.
1198 // FIXME: No source location information!
1199 if (D->getSuperClass() &&
1200 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1201 D->getSuperClassLoc(),
1202 TU)))
1203 return true;
1204#endif
1205
1206 return VisitObjCImplDecl(D);
1207}
1208
1209bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1210 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1211 if (PD->isIvarNameSpecified())
1212 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1213
1214 return false;
1215}
1216
1217bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1218 return VisitDeclContext(D);
1219}
1220
1221bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1222 // Visit nested-name-specifier.
1223 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1224 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1225 return true;
1226
1227 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1228 D->getTargetNameLoc(), TU));
1229}
1230
1231bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1232 // Visit nested-name-specifier.
1233 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1234 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1235 return true;
1236 }
1237
1238 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1239 return true;
1240
1241 return VisitDeclarationNameInfo(D->getNameInfo());
1242}
1243
1244bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1245 // Visit nested-name-specifier.
1246 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1247 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1248 return true;
1249
1250 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1251 D->getIdentLocation(), TU));
1252}
1253
1254bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1255 // Visit nested-name-specifier.
1256 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1257 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1258 return true;
1259 }
1260
1261 return VisitDeclarationNameInfo(D->getNameInfo());
1262}
1263
1264bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1265 UnresolvedUsingTypenameDecl *D) {
1266 // Visit nested-name-specifier.
1267 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1268 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1269 return true;
1270
1271 return false;
1272}
1273
1274bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1275 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1276 return true;
1277 if (StringLiteral *Message = D->getMessage())
1278 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1279 return true;
1280 return false;
1281}
1282
1283bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1284 if (NamedDecl *FriendD = D->getFriendDecl()) {
1285 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1286 return true;
1287 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1288 if (Visit(TI->getTypeLoc()))
1289 return true;
1290 }
1291 return false;
1292}
1293
1294bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1295 switch (Name.getName().getNameKind()) {
1296 case clang::DeclarationName::Identifier:
1297 case clang::DeclarationName::CXXLiteralOperatorName:
1298 case clang::DeclarationName::CXXDeductionGuideName:
1299 case clang::DeclarationName::CXXOperatorName:
1300 case clang::DeclarationName::CXXUsingDirective:
1301 return false;
1302
1303 case clang::DeclarationName::CXXConstructorName:
1304 case clang::DeclarationName::CXXDestructorName:
1305 case clang::DeclarationName::CXXConversionFunctionName:
1306 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1307 return Visit(TSInfo->getTypeLoc());
1308 return false;
1309
1310 case clang::DeclarationName::ObjCZeroArgSelector:
1311 case clang::DeclarationName::ObjCOneArgSelector:
1312 case clang::DeclarationName::ObjCMultiArgSelector:
1313 // FIXME: Per-identifier location info?
1314 return false;
1315 }
1316
1317 llvm_unreachable("Invalid DeclarationName::Kind!")::llvm::llvm_unreachable_internal("Invalid DeclarationName::Kind!"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 1317)
;
1318}
1319
1320bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1321 SourceRange Range) {
1322 // FIXME: This whole routine is a hack to work around the lack of proper
1323 // source information in nested-name-specifiers (PR5791). Since we do have
1324 // a beginning source location, we can visit the first component of the
1325 // nested-name-specifier, if it's a single-token component.
1326 if (!NNS)
1327 return false;
1328
1329 // Get the first component in the nested-name-specifier.
1330 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1331 NNS = Prefix;
1332
1333 switch (NNS->getKind()) {
1334 case NestedNameSpecifier::Namespace:
1335 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1336 TU));
1337
1338 case NestedNameSpecifier::NamespaceAlias:
1339 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1340 Range.getBegin(), TU));
1341
1342 case NestedNameSpecifier::TypeSpec: {
1343 // If the type has a form where we know that the beginning of the source
1344 // range matches up with a reference cursor. Visit the appropriate reference
1345 // cursor.
1346 const Type *T = NNS->getAsType();
1347 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1348 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1349 if (const TagType *Tag = dyn_cast<TagType>(T))
1350 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1351 if (const TemplateSpecializationType *TST
1352 = dyn_cast<TemplateSpecializationType>(T))
1353 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1354 break;
1355 }
1356
1357 case NestedNameSpecifier::TypeSpecWithTemplate:
1358 case NestedNameSpecifier::Global:
1359 case NestedNameSpecifier::Identifier:
1360 case NestedNameSpecifier::Super:
1361 break;
1362 }
1363
1364 return false;
1365}
1366
1367bool
1368CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1369 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1370 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1371 Qualifiers.push_back(Qualifier);
1372
1373 while (!Qualifiers.empty()) {
1374 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1375 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1376 switch (NNS->getKind()) {
1377 case NestedNameSpecifier::Namespace:
1378 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1379 Q.getLocalBeginLoc(),
1380 TU)))
1381 return true;
1382
1383 break;
1384
1385 case NestedNameSpecifier::NamespaceAlias:
1386 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1387 Q.getLocalBeginLoc(),
1388 TU)))
1389 return true;
1390
1391 break;
1392
1393 case NestedNameSpecifier::TypeSpec:
1394 case NestedNameSpecifier::TypeSpecWithTemplate:
1395 if (Visit(Q.getTypeLoc()))
1396 return true;
1397
1398 break;
1399
1400 case NestedNameSpecifier::Global:
1401 case NestedNameSpecifier::Identifier:
1402 case NestedNameSpecifier::Super:
1403 break;
1404 }
1405 }
1406
1407 return false;
1408}
1409
1410bool CursorVisitor::VisitTemplateParameters(
1411 const TemplateParameterList *Params) {
1412 if (!Params)
1413 return false;
1414
1415 for (TemplateParameterList::const_iterator P = Params->begin(),
1416 PEnd = Params->end();
1417 P != PEnd; ++P) {
1418 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1419 return true;
1420 }
1421
1422 return false;
1423}
1424
1425bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1426 switch (Name.getKind()) {
1427 case TemplateName::Template:
1428 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1429
1430 case TemplateName::OverloadedTemplate:
1431 // Visit the overloaded template set.
1432 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1433 return true;
1434
1435 return false;
1436
1437 case TemplateName::DependentTemplate:
1438 // FIXME: Visit nested-name-specifier.
1439 return false;
1440
1441 case TemplateName::QualifiedTemplate:
1442 // FIXME: Visit nested-name-specifier.
1443 return Visit(MakeCursorTemplateRef(
1444 Name.getAsQualifiedTemplateName()->getDecl(),
1445 Loc, TU));
1446
1447 case TemplateName::SubstTemplateTemplateParm:
1448 return Visit(MakeCursorTemplateRef(
1449 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1450 Loc, TU));
1451
1452 case TemplateName::SubstTemplateTemplateParmPack:
1453 return Visit(MakeCursorTemplateRef(
1454 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1455 Loc, TU));
1456 }
1457
1458 llvm_unreachable("Invalid TemplateName::Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateName::Kind!"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 1458)
;
1459}
1460
1461bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1462 switch (TAL.getArgument().getKind()) {
1463 case TemplateArgument::Null:
1464 case TemplateArgument::Integral:
1465 case TemplateArgument::Pack:
1466 return false;
1467
1468 case TemplateArgument::Type:
1469 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1470 return Visit(TSInfo->getTypeLoc());
1471 return false;
1472
1473 case TemplateArgument::Declaration:
1474 if (Expr *E = TAL.getSourceDeclExpression())
1475 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1476 return false;
1477
1478 case TemplateArgument::NullPtr:
1479 if (Expr *E = TAL.getSourceNullPtrExpression())
1480 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1481 return false;
1482
1483 case TemplateArgument::Expression:
1484 if (Expr *E = TAL.getSourceExpression())
1485 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1486 return false;
1487
1488 case TemplateArgument::Template:
1489 case TemplateArgument::TemplateExpansion:
1490 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1491 return true;
1492
1493 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1494 TAL.getTemplateNameLoc());
1495 }
1496
1497 llvm_unreachable("Invalid TemplateArgument::Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument::Kind!"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 1497)
;
1498}
1499
1500bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1501 return VisitDeclContext(D);
1502}
1503
1504bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1505 return Visit(TL.getUnqualifiedLoc());
1506}
1507
1508bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1509 ASTContext &Context = AU->getASTContext();
1510
1511 // Some builtin types (such as Objective-C's "id", "sel", and
1512 // "Class") have associated declarations. Create cursors for those.
1513 QualType VisitType;
1514 switch (TL.getTypePtr()->getKind()) {
1515
1516 case BuiltinType::Void:
1517 case BuiltinType::NullPtr:
1518 case BuiltinType::Dependent:
1519#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1520 case BuiltinType::Id:
1521#include "clang/Basic/OpenCLImageTypes.def"
1522 case BuiltinType::OCLSampler:
1523 case BuiltinType::OCLEvent:
1524 case BuiltinType::OCLClkEvent:
1525 case BuiltinType::OCLQueue:
1526 case BuiltinType::OCLReserveID:
1527#define BUILTIN_TYPE(Id, SingletonId)
1528#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1529#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1530#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1531#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1532#include "clang/AST/BuiltinTypes.def"
1533 break;
1534
1535 case BuiltinType::ObjCId:
1536 VisitType = Context.getObjCIdType();
1537 break;
1538
1539 case BuiltinType::ObjCClass:
1540 VisitType = Context.getObjCClassType();
1541 break;
1542
1543 case BuiltinType::ObjCSel:
1544 VisitType = Context.getObjCSelType();
1545 break;
1546 }
1547
1548 if (!VisitType.isNull()) {
1549 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1550 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1551 TU));
1552 }
1553
1554 return false;
1555}
1556
1557bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1558 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1559}
1560
1561bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1562 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1563}
1564
1565bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1566 if (TL.isDefinition())
1567 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1568
1569 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1570}
1571
1572bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1573 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1574}
1575
1576bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1577 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1578}
1579
1580bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1581 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
1582 return true;
1583 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1584 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1585 TU)))
1586 return true;
1587 }
1588
1589 return false;
1590}
1591
1592bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1593 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1594 return true;
1595
1596 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1597 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1598 return true;
1599 }
1600
1601 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1602 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1603 TU)))
1604 return true;
1605 }
1606
1607 return false;
1608}
1609
1610bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1611 return Visit(TL.getPointeeLoc());
1612}
1613
1614bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1615 return Visit(TL.getInnerLoc());
1616}
1617
1618bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1619 return Visit(TL.getPointeeLoc());
1620}
1621
1622bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1623 return Visit(TL.getPointeeLoc());
1624}
1625
1626bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1627 return Visit(TL.getPointeeLoc());
1628}
1629
1630bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1631 return Visit(TL.getPointeeLoc());
1632}
1633
1634bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1635 return Visit(TL.getPointeeLoc());
1636}
1637
1638bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1639 return Visit(TL.getModifiedLoc());
1640}
1641
1642bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1643 bool SkipResultType) {
1644 if (!SkipResultType && Visit(TL.getReturnLoc()))
1645 return true;
1646
1647 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1648 if (Decl *D = TL.getParam(I))
1649 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1650 return true;
1651
1652 return false;
1653}
1654
1655bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1656 if (Visit(TL.getElementLoc()))
1657 return true;
1658
1659 if (Expr *Size = TL.getSizeExpr())
1660 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1661
1662 return false;
1663}
1664
1665bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1666 return Visit(TL.getOriginalLoc());
1667}
1668
1669bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1670 return Visit(TL.getOriginalLoc());
1671}
1672
1673bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1674 DeducedTemplateSpecializationTypeLoc TL) {
1675 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1676 TL.getTemplateNameLoc()))
1677 return true;
1678
1679 return false;
1680}
1681
1682bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1683 TemplateSpecializationTypeLoc TL) {
1684 // Visit the template name.
1685 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1686 TL.getTemplateNameLoc()))
1687 return true;
1688
1689 // Visit the template arguments.
1690 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1691 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1692 return true;
1693
1694 return false;
1695}
1696
1697bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1698 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1699}
1700
1701bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1702 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1703 return Visit(TSInfo->getTypeLoc());
1704
1705 return false;
1706}
1707
1708bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1709 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1710 return Visit(TSInfo->getTypeLoc());
1711
1712 return false;
1713}
1714
1715bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1716 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1717}
1718
1719bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1720 DependentTemplateSpecializationTypeLoc TL) {
1721 // Visit the nested-name-specifier, if there is one.
1722 if (TL.getQualifierLoc() &&
1723 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1724 return true;
1725
1726 // Visit the template arguments.
1727 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1728 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1729 return true;
1730
1731 return false;
1732}
1733
1734bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1735 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1736 return true;
1737
1738 return Visit(TL.getNamedTypeLoc());
1739}
1740
1741bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1742 return Visit(TL.getPatternLoc());
1743}
1744
1745bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1746 if (Expr *E = TL.getUnderlyingExpr())
1747 return Visit(MakeCXCursor(E, StmtParent, TU));
1748
1749 return false;
1750}
1751
1752bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1753 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1754}
1755
1756bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1757 return Visit(TL.getValueLoc());
1758}
1759
1760bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1761 return Visit(TL.getValueLoc());
1762}
1763
1764#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT)bool CursorVisitor::VisitCLASSTypeLoc(CLASSTypeLoc TL) { return
VisitPARENTLoc(TL); }
\
1765bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1766 return Visit##PARENT##Loc(TL); \
1767}
1768
1769DEFAULT_TYPELOC_IMPL(Complex, Type)bool CursorVisitor::VisitComplexTypeLoc(ComplexTypeLoc TL) { return
VisitTypeLoc(TL); }
1770DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)bool CursorVisitor::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc
TL) { return VisitArrayTypeLoc(TL); }
1771DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)bool CursorVisitor::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc
TL) { return VisitArrayTypeLoc(TL); }
1772DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)bool CursorVisitor::VisitVariableArrayTypeLoc(VariableArrayTypeLoc
TL) { return VisitArrayTypeLoc(TL); }
1773DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)bool CursorVisitor::VisitDependentSizedArrayTypeLoc(DependentSizedArrayTypeLoc
TL) { return VisitArrayTypeLoc(TL); }
1774DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)bool CursorVisitor::VisitDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc
TL) { return VisitTypeLoc(TL); }
1775DEFAULT_TYPELOC_IMPL(DependentVector, Type)bool CursorVisitor::VisitDependentVectorTypeLoc(DependentVectorTypeLoc
TL) { return VisitTypeLoc(TL); }
1776DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)bool CursorVisitor::VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc
TL) { return VisitTypeLoc(TL); }
1777DEFAULT_TYPELOC_IMPL(Vector, Type)bool CursorVisitor::VisitVectorTypeLoc(VectorTypeLoc TL) { return
VisitTypeLoc(TL); }
1778DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)bool CursorVisitor::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL
) { return VisitVectorTypeLoc(TL); }
1779DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)bool CursorVisitor::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc
TL) { return VisitFunctionTypeLoc(TL); }
1780DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)bool CursorVisitor::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc
TL) { return VisitFunctionTypeLoc(TL); }
1781DEFAULT_TYPELOC_IMPL(Record, TagType)bool CursorVisitor::VisitRecordTypeLoc(RecordTypeLoc TL) { return
VisitTagTypeLoc(TL); }
1782DEFAULT_TYPELOC_IMPL(Enum, TagType)bool CursorVisitor::VisitEnumTypeLoc(EnumTypeLoc TL) { return
VisitTagTypeLoc(TL); }
1783DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)bool CursorVisitor::VisitSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc
TL) { return VisitTypeLoc(TL); }
1784DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)bool CursorVisitor::VisitSubstTemplateTypeParmPackTypeLoc(SubstTemplateTypeParmPackTypeLoc
TL) { return VisitTypeLoc(TL); }
1785DEFAULT_TYPELOC_IMPL(Auto, Type)bool CursorVisitor::VisitAutoTypeLoc(AutoTypeLoc TL) { return
VisitTypeLoc(TL); }
1786
1787bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1788 // Visit the nested-name-specifier, if present.
1789 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1790 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1791 return true;
1792
1793 if (D->isCompleteDefinition()) {
1794 for (const auto &I : D->bases()) {
1795 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1796 return true;
1797 }
1798 }
1799
1800 return VisitTagDecl(D);
1801}
1802
1803bool CursorVisitor::VisitAttributes(Decl *D) {
1804 for (const auto *I : D->attrs())
1805 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1806 !I->isImplicit()) &&
1807 Visit(MakeCXCursor(I, D, TU)))
1808 return true;
1809
1810 return false;
1811}
1812
1813//===----------------------------------------------------------------------===//
1814// Data-recursive visitor methods.
1815//===----------------------------------------------------------------------===//
1816
1817namespace {
1818#define DEF_JOB(NAME, DATA, KIND)\
1819class NAME : public VisitorJob {\
1820public:\
1821 NAME(const DATA *d, CXCursor parent) : \
1822 VisitorJob(parent, VisitorJob::KIND, d) {} \
1823 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1824 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
1825};
1826
1827DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1828DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1829DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1830DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1831DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1832DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1833DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1834#undef DEF_JOB
1835
1836class ExplicitTemplateArgsVisit : public VisitorJob {
1837public:
1838 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1839 const TemplateArgumentLoc *End, CXCursor parent)
1840 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1841 End) {}
1842 static bool classof(const VisitorJob *VJ) {
1843 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1844 }
1845 const TemplateArgumentLoc *begin() const {
1846 return static_cast<const TemplateArgumentLoc *>(data[0]);
1847 }
1848 const TemplateArgumentLoc *end() {
1849 return static_cast<const TemplateArgumentLoc *>(data[1]);
1850 }
1851};
1852class DeclVisit : public VisitorJob {
1853public:
1854 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
1855 VisitorJob(parent, VisitorJob::DeclVisitKind,
1856 D, isFirst ? (void*) 1 : (void*) nullptr) {}
1857 static bool classof(const VisitorJob *VJ) {
1858 return VJ->getKind() == DeclVisitKind;
1859 }
1860 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
1861 bool isFirst() const { return data[1] != nullptr; }
1862};
1863class TypeLocVisit : public VisitorJob {
1864public:
1865 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1866 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1867 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1868
1869 static bool classof(const VisitorJob *VJ) {
1870 return VJ->getKind() == TypeLocVisitKind;
1871 }
1872
1873 TypeLoc get() const {
1874 QualType T = QualType::getFromOpaquePtr(data[0]);
1875 return TypeLoc(T, const_cast<void *>(data[1]));
1876 }
1877};
1878
1879class LabelRefVisit : public VisitorJob {
1880public:
1881 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1882 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1883 labelLoc.getPtrEncoding()) {}
1884
1885 static bool classof(const VisitorJob *VJ) {
1886 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1887 }
1888 const LabelDecl *get() const {
1889 return static_cast<const LabelDecl *>(data[0]);
1890 }
1891 SourceLocation getLoc() const {
1892 return SourceLocation::getFromPtrEncoding(data[1]); }
1893};
1894
1895class NestedNameSpecifierLocVisit : public VisitorJob {
1896public:
1897 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1898 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1899 Qualifier.getNestedNameSpecifier(),
1900 Qualifier.getOpaqueData()) { }
1901
1902 static bool classof(const VisitorJob *VJ) {
1903 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1904 }
1905
1906 NestedNameSpecifierLoc get() const {
1907 return NestedNameSpecifierLoc(
1908 const_cast<NestedNameSpecifier *>(
1909 static_cast<const NestedNameSpecifier *>(data[0])),
1910 const_cast<void *>(data[1]));
1911 }
1912};
1913
1914class DeclarationNameInfoVisit : public VisitorJob {
1915public:
1916 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
1917 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1918 static bool classof(const VisitorJob *VJ) {
1919 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1920 }
1921 DeclarationNameInfo get() const {
1922 const Stmt *S = static_cast<const Stmt *>(data[0]);
1923 switch (S->getStmtClass()) {
1924 default:
1925 llvm_unreachable("Unhandled Stmt")::llvm::llvm_unreachable_internal("Unhandled Stmt", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 1925)
;
1926 case clang::Stmt::MSDependentExistsStmtClass:
1927 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1928 case Stmt::CXXDependentScopeMemberExprClass:
1929 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1930 case Stmt::DependentScopeDeclRefExprClass:
1931 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1932 case Stmt::OMPCriticalDirectiveClass:
1933 return cast<OMPCriticalDirective>(S)->getDirectiveName();
1934 }
1935 }
1936};
1937class MemberRefVisit : public VisitorJob {
1938public:
1939 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
1940 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1941 L.getPtrEncoding()) {}
1942 static bool classof(const VisitorJob *VJ) {
1943 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1944 }
1945 const FieldDecl *get() const {
1946 return static_cast<const FieldDecl *>(data[0]);
1947 }
1948 SourceLocation getLoc() const {
1949 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1950 }
1951};
1952class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
1953 friend class OMPClauseEnqueue;
1954 VisitorWorkList &WL;
1955 CXCursor Parent;
1956public:
1957 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1958 : WL(wl), Parent(parent) {}
1959
1960 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1961 void VisitBlockExpr(const BlockExpr *B);
1962 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1963 void VisitCompoundStmt(const CompoundStmt *S);
1964 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1965 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1966 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1967 void VisitCXXNewExpr(const CXXNewExpr *E);
1968 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1969 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1970 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1971 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1972 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1973 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1974 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1975 void VisitCXXCatchStmt(const CXXCatchStmt *S);
1976 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
1977 void VisitDeclRefExpr(const DeclRefExpr *D);
1978 void VisitDeclStmt(const DeclStmt *S);
1979 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1980 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1981 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1982 void VisitForStmt(const ForStmt *FS);
1983 void VisitGotoStmt(const GotoStmt *GS);
1984 void VisitIfStmt(const IfStmt *If);
1985 void VisitInitListExpr(const InitListExpr *IE);
1986 void VisitMemberExpr(const MemberExpr *M);
1987 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1988 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1989 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1990 void VisitOverloadExpr(const OverloadExpr *E);
1991 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1992 void VisitStmt(const Stmt *S);
1993 void VisitSwitchStmt(const SwitchStmt *S);
1994 void VisitWhileStmt(const WhileStmt *W);
1995 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1996 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1997 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1998 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1999 void VisitVAArgExpr(const VAArgExpr *E);
2000 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2001 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2002 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2003 void VisitLambdaExpr(const LambdaExpr *E);
2004 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
2005 void VisitOMPLoopDirective(const OMPLoopDirective *D);
2006 void VisitOMPParallelDirective(const OMPParallelDirective *D);
2007 void VisitOMPSimdDirective(const OMPSimdDirective *D);
2008 void VisitOMPForDirective(const OMPForDirective *D);
2009 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
2010 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
2011 void VisitOMPSectionDirective(const OMPSectionDirective *D);
2012 void VisitOMPSingleDirective(const OMPSingleDirective *D);
2013 void VisitOMPMasterDirective(const OMPMasterDirective *D);
2014 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
2015 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
2016 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
2017 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
2018 void VisitOMPTaskDirective(const OMPTaskDirective *D);
2019 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
2020 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
2021 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
2022 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
2023 void
2024 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
2025 void VisitOMPCancelDirective(const OMPCancelDirective *D);
2026 void VisitOMPFlushDirective(const OMPFlushDirective *D);
2027 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
2028 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
2029 void VisitOMPTargetDirective(const OMPTargetDirective *D);
2030 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
2031 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
2032 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
2033 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
2034 void
2035 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
2036 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
2037 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
2038 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
2039 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
2040 void VisitOMPDistributeParallelForDirective(
2041 const OMPDistributeParallelForDirective *D);
2042 void VisitOMPDistributeParallelForSimdDirective(
2043 const OMPDistributeParallelForSimdDirective *D);
2044 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
2045 void VisitOMPTargetParallelForSimdDirective(
2046 const OMPTargetParallelForSimdDirective *D);
2047 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
2048 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
2049 void VisitOMPTeamsDistributeSimdDirective(
2050 const OMPTeamsDistributeSimdDirective *D);
2051 void VisitOMPTeamsDistributeParallelForSimdDirective(
2052 const OMPTeamsDistributeParallelForSimdDirective *D);
2053 void VisitOMPTeamsDistributeParallelForDirective(
2054 const OMPTeamsDistributeParallelForDirective *D);
2055 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
2056 void VisitOMPTargetTeamsDistributeDirective(
2057 const OMPTargetTeamsDistributeDirective *D);
2058 void VisitOMPTargetTeamsDistributeParallelForDirective(
2059 const OMPTargetTeamsDistributeParallelForDirective *D);
2060 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2061 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
2062 void VisitOMPTargetTeamsDistributeSimdDirective(
2063 const OMPTargetTeamsDistributeSimdDirective *D);
2064
2065private:
2066 void AddDeclarationNameInfo(const Stmt *S);
2067 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
2068 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2069 unsigned NumTemplateArgs);
2070 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2071 void AddStmt(const Stmt *S);
2072 void AddDecl(const Decl *D, bool isFirst = true);
2073 void AddTypeLoc(TypeSourceInfo *TI);
2074 void EnqueueChildren(const Stmt *S);
2075 void EnqueueChildren(const OMPClause *S);
2076};
2077} // end anonyous namespace
2078
2079void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
2080 // 'S' should always be non-null, since it comes from the
2081 // statement we are visiting.
2082 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2083}
2084
2085void
2086EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2087 if (Qualifier)
2088 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2089}
2090
2091void EnqueueVisitor::AddStmt(const Stmt *S) {
2092 if (S)
2093 WL.push_back(StmtVisit(S, Parent));
2094}
2095void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
2096 if (D)
2097 WL.push_back(DeclVisit(D, Parent, isFirst));
2098}
2099void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2100 unsigned NumTemplateArgs) {
2101 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
2102}
2103void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
2104 if (D)
2105 WL.push_back(MemberRefVisit(D, L, Parent));
2106}
2107void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2108 if (TI)
2109 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2110 }
2111void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
2112 unsigned size = WL.size();
2113 for (const Stmt *SubStmt : S->children()) {
2114 AddStmt(SubStmt);
2115 }
2116 if (size == WL.size())
2117 return;
2118 // Now reverse the entries we just added. This will match the DFS
2119 // ordering performed by the worklist.
2120 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2121 std::reverse(I, E);
2122}
2123namespace {
2124class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2125 EnqueueVisitor *Visitor;
2126 /// Process clauses with list of variables.
2127 template <typename T>
2128 void VisitOMPClauseList(T *Node);
2129public:
2130 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2131#define OPENMP_CLAUSE(Name, Class) \
2132 void Visit##Class(const Class *C);
2133#include "clang/Basic/OpenMPKinds.def"
2134 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
2135 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
2136};
2137
2138void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2139 const OMPClauseWithPreInit *C) {
2140 Visitor->AddStmt(C->getPreInitStmt());
2141}
2142
2143void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2144 const OMPClauseWithPostUpdate *C) {
2145 VisitOMPClauseWithPreInit(C);
2146 Visitor->AddStmt(C->getPostUpdateExpr());
2147}
2148
2149void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2150 VisitOMPClauseWithPreInit(C);
2151 Visitor->AddStmt(C->getCondition());
2152}
2153
2154void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2155 Visitor->AddStmt(C->getCondition());
2156}
2157
2158void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2159 VisitOMPClauseWithPreInit(C);
2160 Visitor->AddStmt(C->getNumThreads());
2161}
2162
2163void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2164 Visitor->AddStmt(C->getSafelen());
2165}
2166
2167void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2168 Visitor->AddStmt(C->getSimdlen());
2169}
2170
2171void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2172 Visitor->AddStmt(C->getNumForLoops());
2173}
2174
2175void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
2176
2177void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2178
2179void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2180 VisitOMPClauseWithPreInit(C);
2181 Visitor->AddStmt(C->getChunkSize());
2182}
2183
2184void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2185 Visitor->AddStmt(C->getNumForLoops());
2186}
2187
2188void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2189
2190void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2191
2192void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2193
2194void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2195
2196void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2197
2198void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2199
2200void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2201
2202void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2203
2204void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2205
2206void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2207
2208void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2209
2210void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2211 const OMPUnifiedAddressClause *) {}
2212
2213void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2214 const OMPUnifiedSharedMemoryClause *) {}
2215
2216void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2217 const OMPReverseOffloadClause *) {}
2218
2219void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2220 const OMPDynamicAllocatorsClause *) {}
2221
2222void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2223 Visitor->AddStmt(C->getDevice());
2224}
2225
2226void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2227 VisitOMPClauseWithPreInit(C);
2228 Visitor->AddStmt(C->getNumTeams());
2229}
2230
2231void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2232 VisitOMPClauseWithPreInit(C);
2233 Visitor->AddStmt(C->getThreadLimit());
2234}
2235
2236void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2237 Visitor->AddStmt(C->getPriority());
2238}
2239
2240void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2241 Visitor->AddStmt(C->getGrainsize());
2242}
2243
2244void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2245 Visitor->AddStmt(C->getNumTasks());
2246}
2247
2248void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2249 Visitor->AddStmt(C->getHint());
2250}
2251
2252template<typename T>
2253void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2254 for (const auto *I : Node->varlists()) {
2255 Visitor->AddStmt(I);
2256 }
2257}
2258
2259void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2260 VisitOMPClauseList(C);
2261 for (const auto *E : C->private_copies()) {
2262 Visitor->AddStmt(E);
2263 }
2264}
2265void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2266 const OMPFirstprivateClause *C) {
2267 VisitOMPClauseList(C);
2268 VisitOMPClauseWithPreInit(C);
2269 for (const auto *E : C->private_copies()) {
2270 Visitor->AddStmt(E);
2271 }
2272 for (const auto *E : C->inits()) {
2273 Visitor->AddStmt(E);
2274 }
2275}
2276void OMPClauseEnqueue::VisitOMPLastprivateClause(
2277 const OMPLastprivateClause *C) {
2278 VisitOMPClauseList(C);
2279 VisitOMPClauseWithPostUpdate(C);
2280 for (auto *E : C->private_copies()) {
2281 Visitor->AddStmt(E);
2282 }
2283 for (auto *E : C->source_exprs()) {
2284 Visitor->AddStmt(E);
2285 }
2286 for (auto *E : C->destination_exprs()) {
2287 Visitor->AddStmt(E);
2288 }
2289 for (auto *E : C->assignment_ops()) {
2290 Visitor->AddStmt(E);
2291 }
2292}
2293void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2294 VisitOMPClauseList(C);
2295}
2296void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2297 VisitOMPClauseList(C);
2298 VisitOMPClauseWithPostUpdate(C);
2299 for (auto *E : C->privates()) {
2300 Visitor->AddStmt(E);
2301 }
2302 for (auto *E : C->lhs_exprs()) {
2303 Visitor->AddStmt(E);
2304 }
2305 for (auto *E : C->rhs_exprs()) {
2306 Visitor->AddStmt(E);
2307 }
2308 for (auto *E : C->reduction_ops()) {
2309 Visitor->AddStmt(E);
2310 }
2311}
2312void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2313 const OMPTaskReductionClause *C) {
2314 VisitOMPClauseList(C);
2315 VisitOMPClauseWithPostUpdate(C);
2316 for (auto *E : C->privates()) {
2317 Visitor->AddStmt(E);
2318 }
2319 for (auto *E : C->lhs_exprs()) {
2320 Visitor->AddStmt(E);
2321 }
2322 for (auto *E : C->rhs_exprs()) {
2323 Visitor->AddStmt(E);
2324 }
2325 for (auto *E : C->reduction_ops()) {
2326 Visitor->AddStmt(E);
2327 }
2328}
2329void OMPClauseEnqueue::VisitOMPInReductionClause(
2330 const OMPInReductionClause *C) {
2331 VisitOMPClauseList(C);
2332 VisitOMPClauseWithPostUpdate(C);
2333 for (auto *E : C->privates()) {
2334 Visitor->AddStmt(E);
2335 }
2336 for (auto *E : C->lhs_exprs()) {
2337 Visitor->AddStmt(E);
2338 }
2339 for (auto *E : C->rhs_exprs()) {
2340 Visitor->AddStmt(E);
2341 }
2342 for (auto *E : C->reduction_ops()) {
2343 Visitor->AddStmt(E);
2344 }
2345 for (auto *E : C->taskgroup_descriptors())
2346 Visitor->AddStmt(E);
2347}
2348void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2349 VisitOMPClauseList(C);
2350 VisitOMPClauseWithPostUpdate(C);
2351 for (const auto *E : C->privates()) {
2352 Visitor->AddStmt(E);
2353 }
2354 for (const auto *E : C->inits()) {
2355 Visitor->AddStmt(E);
2356 }
2357 for (const auto *E : C->updates()) {
2358 Visitor->AddStmt(E);
2359 }
2360 for (const auto *E : C->finals()) {
2361 Visitor->AddStmt(E);
2362 }
2363 Visitor->AddStmt(C->getStep());
2364 Visitor->AddStmt(C->getCalcStep());
2365}
2366void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2367 VisitOMPClauseList(C);
2368 Visitor->AddStmt(C->getAlignment());
2369}
2370void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2371 VisitOMPClauseList(C);
2372 for (auto *E : C->source_exprs()) {
2373 Visitor->AddStmt(E);
2374 }
2375 for (auto *E : C->destination_exprs()) {
2376 Visitor->AddStmt(E);
2377 }
2378 for (auto *E : C->assignment_ops()) {
2379 Visitor->AddStmt(E);
2380 }
2381}
2382void
2383OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2384 VisitOMPClauseList(C);
2385 for (auto *E : C->source_exprs()) {
2386 Visitor->AddStmt(E);
2387 }
2388 for (auto *E : C->destination_exprs()) {
2389 Visitor->AddStmt(E);
2390 }
2391 for (auto *E : C->assignment_ops()) {
2392 Visitor->AddStmt(E);
2393 }
2394}
2395void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2396 VisitOMPClauseList(C);
2397}
2398void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2399 VisitOMPClauseList(C);
2400}
2401void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2402 VisitOMPClauseList(C);
2403}
2404void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2405 const OMPDistScheduleClause *C) {
2406 VisitOMPClauseWithPreInit(C);
2407 Visitor->AddStmt(C->getChunkSize());
2408}
2409void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2410 const OMPDefaultmapClause * /*C*/) {}
2411void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2412 VisitOMPClauseList(C);
2413}
2414void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2415 VisitOMPClauseList(C);
2416}
2417void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2418 VisitOMPClauseList(C);
2419}
2420void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2421 VisitOMPClauseList(C);
2422}
2423}
2424
2425void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2426 unsigned size = WL.size();
2427 OMPClauseEnqueue Visitor(this);
2428 Visitor.Visit(S);
2429 if (size == WL.size())
2430 return;
2431 // Now reverse the entries we just added. This will match the DFS
2432 // ordering performed by the worklist.
2433 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2434 std::reverse(I, E);
2435}
2436void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2437 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2438}
2439void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2440 AddDecl(B->getBlockDecl());
2441}
2442void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2443 EnqueueChildren(E);
2444 AddTypeLoc(E->getTypeSourceInfo());
2445}
2446void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2447 for (auto &I : llvm::reverse(S->body()))
2448 AddStmt(I);
2449}
2450void EnqueueVisitor::
2451VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
2452 AddStmt(S->getSubStmt());
2453 AddDeclarationNameInfo(S);
2454 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2455 AddNestedNameSpecifierLoc(QualifierLoc);
2456}
2457
2458void EnqueueVisitor::
2459VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
2460 if (E->hasExplicitTemplateArgs())
2461 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2462 AddDeclarationNameInfo(E);
2463 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2464 AddNestedNameSpecifierLoc(QualifierLoc);
2465 if (!E->isImplicitAccess())
2466 AddStmt(E->getBase());
2467}
2468void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2469 // Enqueue the initializer , if any.
2470 AddStmt(E->getInitializer());
2471 // Enqueue the array size, if any.
2472 AddStmt(E->getArraySize());
2473 // Enqueue the allocated type.
2474 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2475 // Enqueue the placement arguments.
2476 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2477 AddStmt(E->getPlacementArg(I-1));
2478}
2479void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2480 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2481 AddStmt(CE->getArg(I-1));
2482 AddStmt(CE->getCallee());
2483 AddStmt(CE->getArg(0));
2484}
2485void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2486 const CXXPseudoDestructorExpr *E) {
2487 // Visit the name of the type being destroyed.
2488 AddTypeLoc(E->getDestroyedTypeInfo());
2489 // Visit the scope type that looks disturbingly like the nested-name-specifier
2490 // but isn't.
2491 AddTypeLoc(E->getScopeTypeInfo());
2492 // Visit the nested-name-specifier.
2493 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2494 AddNestedNameSpecifierLoc(QualifierLoc);
2495 // Visit base expression.
2496 AddStmt(E->getBase());
2497}
2498void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2499 const CXXScalarValueInitExpr *E) {
2500 AddTypeLoc(E->getTypeSourceInfo());
2501}
2502void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2503 const CXXTemporaryObjectExpr *E) {
2504 EnqueueChildren(E);
2505 AddTypeLoc(E->getTypeSourceInfo());
2506}
2507void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2508 EnqueueChildren(E);
2509 if (E->isTypeOperand())
2510 AddTypeLoc(E->getTypeOperandSourceInfo());
2511}
2512
2513void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2514 const CXXUnresolvedConstructExpr *E) {
2515 EnqueueChildren(E);
2516 AddTypeLoc(E->getTypeSourceInfo());
2517}
2518void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2519 EnqueueChildren(E);
2520 if (E->isTypeOperand())
2521 AddTypeLoc(E->getTypeOperandSourceInfo());
2522}
2523
2524void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2525 EnqueueChildren(S);
2526 AddDecl(S->getExceptionDecl());
2527}
2528
2529void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2530 AddStmt(S->getBody());
2531 AddStmt(S->getRangeInit());
2532 AddDecl(S->getLoopVariable());
2533}
2534
2535void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2536 if (DR->hasExplicitTemplateArgs())
2537 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
2538 WL.push_back(DeclRefExprParts(DR, Parent));
2539}
2540void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2541 const DependentScopeDeclRefExpr *E) {
2542 if (E->hasExplicitTemplateArgs())
2543 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2544 AddDeclarationNameInfo(E);
2545 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2546}
2547void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2548 unsigned size = WL.size();
2549 bool isFirst = true;
2550 for (const auto *D : S->decls()) {
2551 AddDecl(D, isFirst);
2552 isFirst = false;
2553 }
2554 if (size == WL.size())
2555 return;
2556 // Now reverse the entries we just added. This will match the DFS
2557 // ordering performed by the worklist.
2558 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2559 std::reverse(I, E);
2560}
2561void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2562 AddStmt(E->getInit());
2563 for (const DesignatedInitExpr::Designator &D :
2564 llvm::reverse(E->designators())) {
2565 if (D.isFieldDesignator()) {
2566 if (FieldDecl *Field = D.getField())
2567 AddMemberRef(Field, D.getFieldLoc());
2568 continue;
2569 }
2570 if (D.isArrayDesignator()) {
2571 AddStmt(E->getArrayIndex(D));
2572 continue;
2573 }
2574 assert(D.isArrayRangeDesignator() && "Unknown designator kind")((D.isArrayRangeDesignator() && "Unknown designator kind"
) ? static_cast<void> (0) : __assert_fail ("D.isArrayRangeDesignator() && \"Unknown designator kind\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 2574, __PRETTY_FUNCTION__))
;
2575 AddStmt(E->getArrayRangeEnd(D));
2576 AddStmt(E->getArrayRangeStart(D));
2577 }
2578}
2579void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2580 EnqueueChildren(E);
2581 AddTypeLoc(E->getTypeInfoAsWritten());
2582}
2583void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2584 AddStmt(FS->getBody());
2585 AddStmt(FS->getInc());
2586 AddStmt(FS->getCond());
2587 AddDecl(FS->getConditionVariable());
2588 AddStmt(FS->getInit());
2589}
2590void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2591 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2592}
2593void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2594 AddStmt(If->getElse());
2595 AddStmt(If->getThen());
2596 AddStmt(If->getCond());
2597 AddDecl(If->getConditionVariable());
2598}
2599void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2600 // We care about the syntactic form of the initializer list, only.
2601 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2602 IE = Syntactic;
2603 EnqueueChildren(IE);
2604}
2605void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2606 WL.push_back(MemberExprParts(M, Parent));
2607
2608 // If the base of the member access expression is an implicit 'this', don't
2609 // visit it.
2610 // FIXME: If we ever want to show these implicit accesses, this will be
2611 // unfortunate. However, clang_getCursor() relies on this behavior.
2612 if (M->isImplicitAccess())
2613 return;
2614
2615 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2616 // real field that we are interested in.
2617 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2618 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2619 if (FD->isAnonymousStructOrUnion()) {
2620 AddStmt(SubME->getBase());
2621 return;
2622 }
2623 }
2624 }
2625
2626 AddStmt(M->getBase());
2627}
2628void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2629 AddTypeLoc(E->getEncodedTypeSourceInfo());
2630}
2631void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2632 EnqueueChildren(M);
2633 AddTypeLoc(M->getClassReceiverTypeInfo());
2634}
2635void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2636 // Visit the components of the offsetof expression.
2637 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2638 const OffsetOfNode &Node = E->getComponent(I-1);
2639 switch (Node.getKind()) {
2640 case OffsetOfNode::Array:
2641 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2642 break;
2643 case OffsetOfNode::Field:
2644 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2645 break;
2646 case OffsetOfNode::Identifier:
2647 case OffsetOfNode::Base:
2648 continue;
2649 }
2650 }
2651 // Visit the type into which we're computing the offset.
2652 AddTypeLoc(E->getTypeSourceInfo());
2653}
2654void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2655 if (E->hasExplicitTemplateArgs())
2656 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2657 WL.push_back(OverloadExprParts(E, Parent));
2658}
2659void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2660 const UnaryExprOrTypeTraitExpr *E) {
2661 EnqueueChildren(E);
2662 if (E->isArgumentType())
2663 AddTypeLoc(E->getArgumentTypeInfo());
2664}
2665void EnqueueVisitor::VisitStmt(const Stmt *S) {
2666 EnqueueChildren(S);
2667}
2668void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2669 AddStmt(S->getBody());
2670 AddStmt(S->getCond());
2671 AddDecl(S->getConditionVariable());
2672}
2673
2674void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2675 AddStmt(W->getBody());
2676 AddStmt(W->getCond());
2677 AddDecl(W->getConditionVariable());
2678}
2679
2680void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2681 for (unsigned I = E->getNumArgs(); I > 0; --I)
2682 AddTypeLoc(E->getArg(I-1));
2683}
2684
2685void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2686 AddTypeLoc(E->getQueriedTypeSourceInfo());
2687}
2688
2689void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2690 EnqueueChildren(E);
2691}
2692
2693void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2694 VisitOverloadExpr(U);
2695 if (!U->isImplicitAccess())
2696 AddStmt(U->getBase());
2697}
2698void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2699 AddStmt(E->getSubExpr());
2700 AddTypeLoc(E->getWrittenTypeInfo());
2701}
2702void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2703 WL.push_back(SizeOfPackExprParts(E, Parent));
2704}
2705void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2706 // If the opaque value has a source expression, just transparently
2707 // visit that. This is useful for (e.g.) pseudo-object expressions.
2708 if (Expr *SourceExpr = E->getSourceExpr())
2709 return Visit(SourceExpr);
2710}
2711void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2712 AddStmt(E->getBody());
2713 WL.push_back(LambdaExprParts(E, Parent));
2714}
2715void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2716 // Treat the expression like its syntactic form.
2717 Visit(E->getSyntacticForm());
2718}
2719
2720void EnqueueVisitor::VisitOMPExecutableDirective(
2721 const OMPExecutableDirective *D) {
2722 EnqueueChildren(D);
2723 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2724 E = D->clauses().end();
2725 I != E; ++I)
2726 EnqueueChildren(*I);
2727}
2728
2729void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2730 VisitOMPExecutableDirective(D);
2731}
2732
2733void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2734 VisitOMPExecutableDirective(D);
2735}
2736
2737void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2738 VisitOMPLoopDirective(D);
2739}
2740
2741void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2742 VisitOMPLoopDirective(D);
2743}
2744
2745void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2746 VisitOMPLoopDirective(D);
2747}
2748
2749void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2750 VisitOMPExecutableDirective(D);
2751}
2752
2753void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2754 VisitOMPExecutableDirective(D);
2755}
2756
2757void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2758 VisitOMPExecutableDirective(D);
2759}
2760
2761void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2762 VisitOMPExecutableDirective(D);
2763}
2764
2765void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2766 VisitOMPExecutableDirective(D);
2767 AddDeclarationNameInfo(D);
2768}
2769
2770void
2771EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
2772 VisitOMPLoopDirective(D);
2773}
2774
2775void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2776 const OMPParallelForSimdDirective *D) {
2777 VisitOMPLoopDirective(D);
2778}
2779
2780void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2781 const OMPParallelSectionsDirective *D) {
2782 VisitOMPExecutableDirective(D);
2783}
2784
2785void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2786 VisitOMPExecutableDirective(D);
2787}
2788
2789void
2790EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2791 VisitOMPExecutableDirective(D);
2792}
2793
2794void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2795 VisitOMPExecutableDirective(D);
2796}
2797
2798void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2799 VisitOMPExecutableDirective(D);
2800}
2801
2802void EnqueueVisitor::VisitOMPTaskgroupDirective(
2803 const OMPTaskgroupDirective *D) {
2804 VisitOMPExecutableDirective(D);
2805 if (const Expr *E = D->getReductionRef())
2806 VisitStmt(E);
2807}
2808
2809void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2810 VisitOMPExecutableDirective(D);
2811}
2812
2813void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2814 VisitOMPExecutableDirective(D);
2815}
2816
2817void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2818 VisitOMPExecutableDirective(D);
2819}
2820
2821void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2822 VisitOMPExecutableDirective(D);
2823}
2824
2825void EnqueueVisitor::VisitOMPTargetDataDirective(const
2826 OMPTargetDataDirective *D) {
2827 VisitOMPExecutableDirective(D);
2828}
2829
2830void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2831 const OMPTargetEnterDataDirective *D) {
2832 VisitOMPExecutableDirective(D);
2833}
2834
2835void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2836 const OMPTargetExitDataDirective *D) {
2837 VisitOMPExecutableDirective(D);
2838}
2839
2840void EnqueueVisitor::VisitOMPTargetParallelDirective(
2841 const OMPTargetParallelDirective *D) {
2842 VisitOMPExecutableDirective(D);
2843}
2844
2845void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2846 const OMPTargetParallelForDirective *D) {
2847 VisitOMPLoopDirective(D);
2848}
2849
2850void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2851 VisitOMPExecutableDirective(D);
2852}
2853
2854void EnqueueVisitor::VisitOMPCancellationPointDirective(
2855 const OMPCancellationPointDirective *D) {
2856 VisitOMPExecutableDirective(D);
2857}
2858
2859void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2860 VisitOMPExecutableDirective(D);
2861}
2862
2863void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2864 VisitOMPLoopDirective(D);
2865}
2866
2867void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2868 const OMPTaskLoopSimdDirective *D) {
2869 VisitOMPLoopDirective(D);
2870}
2871
2872void EnqueueVisitor::VisitOMPDistributeDirective(
2873 const OMPDistributeDirective *D) {
2874 VisitOMPLoopDirective(D);
2875}
2876
2877void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2878 const OMPDistributeParallelForDirective *D) {
2879 VisitOMPLoopDirective(D);
2880}
2881
2882void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2883 const OMPDistributeParallelForSimdDirective *D) {
2884 VisitOMPLoopDirective(D);
2885}
2886
2887void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2888 const OMPDistributeSimdDirective *D) {
2889 VisitOMPLoopDirective(D);
2890}
2891
2892void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2893 const OMPTargetParallelForSimdDirective *D) {
2894 VisitOMPLoopDirective(D);
2895}
2896
2897void EnqueueVisitor::VisitOMPTargetSimdDirective(
2898 const OMPTargetSimdDirective *D) {
2899 VisitOMPLoopDirective(D);
2900}
2901
2902void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2903 const OMPTeamsDistributeDirective *D) {
2904 VisitOMPLoopDirective(D);
2905}
2906
2907void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2908 const OMPTeamsDistributeSimdDirective *D) {
2909 VisitOMPLoopDirective(D);
2910}
2911
2912void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2913 const OMPTeamsDistributeParallelForSimdDirective *D) {
2914 VisitOMPLoopDirective(D);
2915}
2916
2917void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2918 const OMPTeamsDistributeParallelForDirective *D) {
2919 VisitOMPLoopDirective(D);
2920}
2921
2922void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2923 const OMPTargetTeamsDirective *D) {
2924 VisitOMPExecutableDirective(D);
2925}
2926
2927void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2928 const OMPTargetTeamsDistributeDirective *D) {
2929 VisitOMPLoopDirective(D);
2930}
2931
2932void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2933 const OMPTargetTeamsDistributeParallelForDirective *D) {
2934 VisitOMPLoopDirective(D);
2935}
2936
2937void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2938 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2939 VisitOMPLoopDirective(D);
2940}
2941
2942void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2943 const OMPTargetTeamsDistributeSimdDirective *D) {
2944 VisitOMPLoopDirective(D);
2945}
2946
2947void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
2948 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2949}
2950
2951bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2952 if (RegionOfInterest.isValid()) {
2953 SourceRange Range = getRawCursorExtent(C);
2954 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2955 return false;
2956 }
2957 return true;
2958}
2959
2960bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2961 while (!WL.empty()) {
2962 // Dequeue the worklist item.
2963 VisitorJob LI = WL.pop_back_val();
2964
2965 // Set the Parent field, then back to its old value once we're done.
2966 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2967
2968 switch (LI.getKind()) {
2969 case VisitorJob::DeclVisitKind: {
2970 const Decl *D = cast<DeclVisit>(&LI)->get();
2971 if (!D)
2972 continue;
2973
2974 // For now, perform default visitation for Decls.
2975 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2976 cast<DeclVisit>(&LI)->isFirst())))
2977 return true;
2978
2979 continue;
2980 }
2981 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2982 for (const TemplateArgumentLoc &Arg :
2983 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2984 if (VisitTemplateArgumentLoc(Arg))
2985 return true;
2986 }
2987 continue;
2988 }
2989 case VisitorJob::TypeLocVisitKind: {
2990 // Perform default visitation for TypeLocs.
2991 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2992 return true;
2993 continue;
2994 }
2995 case VisitorJob::LabelRefVisitKind: {
2996 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2997 if (LabelStmt *stmt = LS->getStmt()) {
2998 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2999 TU))) {
3000 return true;
3001 }
3002 }
3003 continue;
3004 }
3005
3006 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3007 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3008 if (VisitNestedNameSpecifierLoc(V->get()))
3009 return true;
3010 continue;
3011 }
3012
3013 case VisitorJob::DeclarationNameInfoVisitKind: {
3014 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3015 ->get()))
3016 return true;
3017 continue;
3018 }
3019 case VisitorJob::MemberRefVisitKind: {
3020 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3021 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3022 return true;
3023 continue;
3024 }
3025 case VisitorJob::StmtVisitKind: {
3026 const Stmt *S = cast<StmtVisit>(&LI)->get();
3027 if (!S)
3028 continue;
3029
3030 // Update the current cursor.
3031 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3032 if (!IsInRegionOfInterest(Cursor))
3033 continue;
3034 switch (Visitor(Cursor, Parent, ClientData)) {
3035 case CXChildVisit_Break: return true;
3036 case CXChildVisit_Continue: break;
3037 case CXChildVisit_Recurse:
3038 if (PostChildrenVisitor)
3039 WL.push_back(PostChildrenVisit(nullptr, Cursor));
3040 EnqueueWorkList(WL, S);
3041 break;
3042 }
3043 continue;
3044 }
3045 case VisitorJob::MemberExprPartsKind: {
3046 // Handle the other pieces in the MemberExpr besides the base.
3047 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
3048
3049 // Visit the nested-name-specifier
3050 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3051 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3052 return true;
3053
3054 // Visit the declaration name.
3055 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3056 return true;
3057
3058 // Visit the explicitly-specified template arguments, if any.
3059 if (M->hasExplicitTemplateArgs()) {
3060 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3061 *ArgEnd = Arg + M->getNumTemplateArgs();
3062 Arg != ArgEnd; ++Arg) {
3063 if (VisitTemplateArgumentLoc(*Arg))
3064 return true;
3065 }
3066 }
3067 continue;
3068 }
3069 case VisitorJob::DeclRefExprPartsKind: {
3070 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
3071 // Visit nested-name-specifier, if present.
3072 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3073 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3074 return true;
3075 // Visit declaration name.
3076 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3077 return true;
3078 continue;
3079 }
3080 case VisitorJob::OverloadExprPartsKind: {
3081 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
3082 // Visit the nested-name-specifier.
3083 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3084 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3085 return true;
3086 // Visit the declaration name.
3087 if (VisitDeclarationNameInfo(O->getNameInfo()))
3088 return true;
3089 // Visit the overloaded declaration reference.
3090 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3091 return true;
3092 continue;
3093 }
3094 case VisitorJob::SizeOfPackExprPartsKind: {
3095 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
3096 NamedDecl *Pack = E->getPack();
3097 if (isa<TemplateTypeParmDecl>(Pack)) {
3098 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3099 E->getPackLoc(), TU)))
3100 return true;
3101
3102 continue;
3103 }
3104
3105 if (isa<TemplateTemplateParmDecl>(Pack)) {
3106 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3107 E->getPackLoc(), TU)))
3108 return true;
3109
3110 continue;
3111 }
3112
3113 // Non-type template parameter packs and function parameter packs are
3114 // treated like DeclRefExpr cursors.
3115 continue;
3116 }
3117
3118 case VisitorJob::LambdaExprPartsKind: {
3119 // Visit captures.
3120 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
3121 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3122 CEnd = E->explicit_capture_end();
3123 C != CEnd; ++C) {
3124 // FIXME: Lambda init-captures.
3125 if (!C->capturesVariable())
3126 continue;
3127
3128 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3129 C->getLocation(),
3130 TU)))
3131 return true;
3132 }
3133
3134 // Visit parameters and return type, if present.
3135 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3136 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3137 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3138 // Visit the whole type.
3139 if (Visit(TL))
3140 return true;
3141 } else if (FunctionProtoTypeLoc Proto =
3142 TL.getAs<FunctionProtoTypeLoc>()) {
3143 if (E->hasExplicitParameters()) {
3144 // Visit parameters.
3145 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3146 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
3147 return true;
3148 } else {
3149 // Visit result type.
3150 if (Visit(Proto.getReturnLoc()))
3151 return true;
3152 }
3153 }
3154 }
3155 break;
3156 }
3157
3158 case VisitorJob::PostChildrenVisitKind:
3159 if (PostChildrenVisitor(Parent, ClientData))
3160 return true;
3161 break;
3162 }
3163 }
3164 return false;
3165}
3166
3167bool CursorVisitor::Visit(const Stmt *S) {
3168 VisitorWorkList *WL = nullptr;
3169 if (!WorkListFreeList.empty()) {
3170 WL = WorkListFreeList.back();
3171 WL->clear();
3172 WorkListFreeList.pop_back();
3173 }
3174 else {
3175 WL = new VisitorWorkList();
3176 WorkListCache.push_back(WL);
3177 }
3178 EnqueueWorkList(*WL, S);
3179 bool result = RunVisitorWorkList(*WL);
3180 WorkListFreeList.push_back(WL);
3181 return result;
3182}
3183
3184namespace {
3185typedef SmallVector<SourceRange, 4> RefNamePieces;
3186RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3187 const DeclarationNameInfo &NI, SourceRange QLoc,
3188 const SourceRange *TemplateArgsLoc = nullptr) {
3189 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3190 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3191 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3192
3193 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3194
3195 RefNamePieces Pieces;
3196
3197 if (WantQualifier && QLoc.isValid())
3198 Pieces.push_back(QLoc);
3199
3200 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3201 Pieces.push_back(NI.getLoc());
3202
3203 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3204 Pieces.push_back(*TemplateArgsLoc);
3205
3206 if (Kind == DeclarationName::CXXOperatorName) {
3207 Pieces.push_back(SourceLocation::getFromRawEncoding(
3208 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3209 Pieces.push_back(SourceLocation::getFromRawEncoding(
3210 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3211 }
3212
3213 if (WantSinglePiece) {
3214 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3215 Pieces.clear();
3216 Pieces.push_back(R);
3217 }
3218
3219 return Pieces;
3220}
3221}
3222
3223//===----------------------------------------------------------------------===//
3224// Misc. API hooks.
3225//===----------------------------------------------------------------------===//
3226
3227static void fatal_error_handler(void *user_data, const std::string& reason,
3228 bool gen_crash_diag) {
3229 // Write the result out to stderr avoiding errs() because raw_ostreams can
3230 // call report_fatal_error.
3231 fprintf(stderrstderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3232 ::abort();
3233}
3234
3235namespace {
3236struct RegisterFatalErrorHandler {
3237 RegisterFatalErrorHandler() {
3238 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3239 }
3240};
3241}
3242
3243static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3244
3245CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3246 int displayDiagnostics) {
3247 // We use crash recovery to make some of our APIs more reliable, implicitly
3248 // enable it.
3249 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3250 llvm::CrashRecoveryContext::Enable();
3251
3252 // Look through the managed static to trigger construction of the managed
3253 // static which registers our fatal error handler. This ensures it is only
3254 // registered once.
3255 (void)*RegisterFatalErrorHandlerOnce;
3256
3257 // Initialize targets for clang module support.
3258 llvm::InitializeAllTargets();
3259 llvm::InitializeAllTargetMCs();
3260 llvm::InitializeAllAsmPrinters();
3261 llvm::InitializeAllAsmParsers();
3262
3263 CIndexer *CIdxr = new CIndexer();
3264
3265 if (excludeDeclarationsFromPCH)
3266 CIdxr->setOnlyLocalDecls();
3267 if (displayDiagnostics)
3268 CIdxr->setDisplayDiagnostics();
3269
3270 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3271 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3272 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3273 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3274 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3275 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3276
3277 return CIdxr;
3278}
3279
3280void clang_disposeIndex(CXIndex CIdx) {
3281 if (CIdx)
3282 delete static_cast<CIndexer *>(CIdx);
3283}
3284
3285void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3286 if (CIdx)
3287 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3288}
3289
3290unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3291 if (CIdx)
3292 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3293 return 0;
3294}
3295
3296void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3297 const char *Path) {
3298 if (CIdx)
3299 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3300}
3301
3302void clang_toggleCrashRecovery(unsigned isEnabled) {
3303 if (isEnabled)
3304 llvm::CrashRecoveryContext::Enable();
3305 else
3306 llvm::CrashRecoveryContext::Disable();
3307}
3308
3309CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3310 const char *ast_filename) {
3311 CXTranslationUnit TU;
3312 enum CXErrorCode Result =
3313 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
3314 (void)Result;
3315 assert((TU && Result == CXError_Success) ||(((TU && Result == CXError_Success) || (!TU &&
Result != CXError_Success)) ? static_cast<void> (0) : __assert_fail
("(TU && Result == CXError_Success) || (!TU && Result != CXError_Success)"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 3316, __PRETTY_FUNCTION__))
3316 (!TU && Result != CXError_Success))(((TU && Result == CXError_Success) || (!TU &&
Result != CXError_Success)) ? static_cast<void> (0) : __assert_fail
("(TU && Result == CXError_Success) || (!TU && Result != CXError_Success)"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 3316, __PRETTY_FUNCTION__))
;
3317 return TU;
3318}
3319
3320enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3321 const char *ast_filename,
3322 CXTranslationUnit *out_TU) {
3323 if (out_TU)
3324 *out_TU = nullptr;
3325
3326 if (!CIdx || !ast_filename || !out_TU)
3327 return CXError_InvalidArguments;
3328
3329 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
3330 *Log << ast_filename;
3331 }
3332
3333 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3334 FileSystemOptions FileSystemOpts;
3335
3336 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3337 CompilerInstance::createDiagnostics(new DiagnosticOptions());
3338 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
3339 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3340 ASTUnit::LoadEverything, Diags,
3341 FileSystemOpts, /*UseDebugInfo=*/false,
3342 CXXIdx->getOnlyLocalDecls(), None,
3343 /*CaptureDiagnostics=*/true,
3344 /*AllowPCHWithCompilerErrors=*/true,
3345 /*UserFilesAreVolatile=*/true);
3346 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
3347 return *out_TU ? CXError_Success : CXError_Failure;
3348}
3349
3350unsigned clang_defaultEditingTranslationUnitOptions() {
3351 return CXTranslationUnit_PrecompiledPreamble |
3352 CXTranslationUnit_CacheCompletionResults;
3353}
3354
3355CXTranslationUnit
3356clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3357 const char *source_filename,
3358 int num_command_line_args,
3359 const char * const *command_line_args,
3360 unsigned num_unsaved_files,
3361 struct CXUnsavedFile *unsaved_files) {
3362 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3363 return clang_parseTranslationUnit(CIdx, source_filename,
3364 command_line_args, num_command_line_args,
3365 unsaved_files, num_unsaved_files,
3366 Options);
3367}
3368
3369static CXErrorCode
3370clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3371 const char *const *command_line_args,
3372 int num_command_line_args,
3373 ArrayRef<CXUnsavedFile> unsaved_files,
3374 unsigned options, CXTranslationUnit *out_TU) {
3375 // Set up the initial return values.
3376 if (out_TU)
3377 *out_TU = nullptr;
3378
3379 // Check arguments.
3380 if (!CIdx || !out_TU)
3381 return CXError_InvalidArguments;
3382
3383 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3384
3385 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3386 setThreadBackgroundPriority();
3387
3388 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3389 bool CreatePreambleOnFirstParse =
3390 options & CXTranslationUnit_CreatePreambleOnFirstParse;
3391 // FIXME: Add a flag for modules.
3392 TranslationUnitKind TUKind
3393 = (options & (CXTranslationUnit_Incomplete |
3394 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
3395 bool CacheCodeCompletionResults
3396 = options & CXTranslationUnit_CacheCompletionResults;
3397 bool IncludeBriefCommentsInCodeCompletion
3398 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3399 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3400 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3401 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3402 if (options & CXTranslationUnit_SkipFunctionBodies) {
3403 SkipFunctionBodies =
3404 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3405 ? SkipFunctionBodiesScope::Preamble
3406 : SkipFunctionBodiesScope::PreambleAndMainFile;
3407 }
3408
3409 // Configure the diagnostics.
3410 IntrusiveRefCntPtr<DiagnosticsEngine>
3411 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
3412
3413 if (options & CXTranslationUnit_KeepGoing)
3414 Diags->setSuppressAfterFatalError(false);
3415
3416 // Recover resources if we crash before exiting this function.
3417 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3418 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
3419 DiagCleanup(Diags.get());
3420
3421 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3422 new std::vector<ASTUnit::RemappedFile>());
3423
3424 // Recover resources if we crash before exiting this function.
3425 llvm::CrashRecoveryContextCleanupRegistrar<
3426 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3427
3428 for (auto &UF : unsaved_files) {
3429 std::unique_ptr<llvm::MemoryBuffer> MB =
3430 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3431 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3432 }
3433
3434 std::unique_ptr<std::vector<const char *>> Args(
3435 new std::vector<const char *>());
3436
3437 // Recover resources if we crash before exiting this method.
3438 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3439 ArgsCleanup(Args.get());
3440
3441 // Since the Clang C library is primarily used by batch tools dealing with
3442 // (often very broken) source code, where spell-checking can have a
3443 // significant negative impact on performance (particularly when
3444 // precompiled headers are involved), we disable it by default.
3445 // Only do this if we haven't found a spell-checking-related argument.
3446 bool FoundSpellCheckingArgument = false;
3447 for (int I = 0; I != num_command_line_args; ++I) {
3448 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3449 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3450 FoundSpellCheckingArgument = true;
3451 break;
3452 }
3453 }
3454 Args->insert(Args->end(), command_line_args,
3455 command_line_args + num_command_line_args);
3456
3457 if (!FoundSpellCheckingArgument)
3458 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3459
3460 // The 'source_filename' argument is optional. If the caller does not
3461 // specify it then it is assumed that the source file is specified
3462 // in the actual argument list.
3463 // Put the source file after command_line_args otherwise if '-x' flag is
3464 // present it will be unused.
3465 if (source_filename)
3466 Args->push_back(source_filename);
3467
3468 // Do we need the detailed preprocessing record?
3469 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3470 Args->push_back("-Xclang");
3471 Args->push_back("-detailed-preprocessing-record");
3472 }
3473
3474 // Suppress any editor placeholder diagnostics.
3475 Args->push_back("-fallow-editor-placeholders");
3476
3477 unsigned NumErrors = Diags->getClient()->getNumErrors();
3478 std::unique_ptr<ASTUnit> ErrUnit;
3479 // Unless the user specified that they want the preamble on the first parse
3480 // set it up to be created on the first reparse. This makes the first parse
3481 // faster, trading for a slower (first) reparse.
3482 unsigned PrecompilePreambleAfterNParses =
3483 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
3484
3485 LibclangInvocationReporter InvocationReporter(
3486 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
3487 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3488 unsaved_files);
3489 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3490 Args->data(), Args->data() + Args->size(),
3491 CXXIdx->getPCHContainerOperations(), Diags,
3492 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3493 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
3494 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3495 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3496 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
3497 /*UserFilesAreVolatile=*/true, ForSerialization,
3498 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3499 &ErrUnit));
3500
3501 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3502 if (!Unit && !ErrUnit)
3503 return CXError_ASTReadError;
3504
3505 if (NumErrors != Diags->getClient()->getNumErrors()) {
3506 // Make sure to check that 'Unit' is non-NULL.
3507 if (CXXIdx->getDisplayDiagnostics())
3508 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3509 }
3510
3511 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3512 return CXError_ASTReadError;
3513
3514 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
3515 if (CXTranslationUnitImpl *TU = *out_TU) {
3516 TU->ParsingOptions = options;
3517 TU->Arguments.reserve(Args->size());
3518 for (const char *Arg : *Args)
3519 TU->Arguments.push_back(Arg);
3520 return CXError_Success;
3521 }
3522 return CXError_Failure;
3523}
3524
3525CXTranslationUnit
3526clang_parseTranslationUnit(CXIndex CIdx,
3527 const char *source_filename,
3528 const char *const *command_line_args,
3529 int num_command_line_args,
3530 struct CXUnsavedFile *unsaved_files,
3531 unsigned num_unsaved_files,
3532 unsigned options) {
3533 CXTranslationUnit TU;
3534 enum CXErrorCode Result = clang_parseTranslationUnit2(
3535 CIdx, source_filename, command_line_args, num_command_line_args,
3536 unsaved_files, num_unsaved_files, options, &TU);
3537 (void)Result;
3538 assert((TU && Result == CXError_Success) ||(((TU && Result == CXError_Success) || (!TU &&
Result != CXError_Success)) ? static_cast<void> (0) : __assert_fail
("(TU && Result == CXError_Success) || (!TU && Result != CXError_Success)"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 3539, __PRETTY_FUNCTION__))
3539 (!TU && Result != CXError_Success))(((TU && Result == CXError_Success) || (!TU &&
Result != CXError_Success)) ? static_cast<void> (0) : __assert_fail
("(TU && Result == CXError_Success) || (!TU && Result != CXError_Success)"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 3539, __PRETTY_FUNCTION__))
;
3540 return TU;
3541}
3542
3543enum CXErrorCode clang_parseTranslationUnit2(
3544 CXIndex CIdx, const char *source_filename,
3545 const char *const *command_line_args, int num_command_line_args,
3546 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3547 unsigned options, CXTranslationUnit *out_TU) {
3548 SmallVector<const char *, 4> Args;
3549 Args.push_back("clang");
3550 Args.append(command_line_args, command_line_args + num_command_line_args);
3551 return clang_parseTranslationUnit2FullArgv(
3552 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3553 num_unsaved_files, options, out_TU);
3554}
3555
3556enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3557 CXIndex CIdx, const char *source_filename,
3558 const char *const *command_line_args, int num_command_line_args,
3559 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3560 unsigned options, CXTranslationUnit *out_TU) {
3561 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
3562 *Log << source_filename << ": ";
3563 for (int i = 0; i != num_command_line_args; ++i)
3564 *Log << command_line_args[i] << " ";
3565 }
3566
3567 if (num_unsaved_files && !unsaved_files)
3568 return CXError_InvalidArguments;
3569
3570 CXErrorCode result = CXError_Failure;
3571 auto ParseTranslationUnitImpl = [=, &result] {
3572 result = clang_parseTranslationUnit_Impl(
3573 CIdx, source_filename, command_line_args, num_command_line_args,
3574 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3575 };
3576
3577 llvm::CrashRecoveryContext CRC;
3578
3579 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3580 fprintf(stderrstderr, "libclang: crash detected during parsing: {\n");
3581 fprintf(stderrstderr, " 'source_filename' : '%s'\n", source_filename);
3582 fprintf(stderrstderr, " 'command_line_args' : [");
3583 for (int i = 0; i != num_command_line_args; ++i) {
3584 if (i)
3585 fprintf(stderrstderr, ", ");
3586 fprintf(stderrstderr, "'%s'", command_line_args[i]);
3587 }
3588 fprintf(stderrstderr, "],\n");
3589 fprintf(stderrstderr, " 'unsaved_files' : [");
3590 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3591 if (i)
3592 fprintf(stderrstderr, ", ");
3593 fprintf(stderrstderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3594 unsaved_files[i].Length);
3595 }
3596 fprintf(stderrstderr, "],\n");
3597 fprintf(stderrstderr, " 'options' : %d,\n", options);
3598 fprintf(stderrstderr, "}\n");
3599
3600 return CXError_Crashed;
3601 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3602 if (CXTranslationUnit *TU = out_TU)
3603 PrintLibclangResourceUsage(*TU);
3604 }
3605
3606 return result;
3607}
3608
3609CXString clang_Type_getObjCEncoding(CXType CT) {
3610 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3611 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3612 std::string encoding;
3613 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3614 encoding);
3615
3616 return cxstring::createDup(encoding);
3617}
3618
3619static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3620 if (C.kind == CXCursor_MacroDefinition) {
3621 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3622 return MDR->getName();
3623 } else if (C.kind == CXCursor_MacroExpansion) {
3624 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3625 return ME.getName();
3626 }
3627 return nullptr;
3628}
3629
3630unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3631 const IdentifierInfo *II = getMacroIdentifier(C);
3632 if (!II) {
3633 return false;
3634 }
3635 ASTUnit *ASTU = getCursorASTUnit(C);
3636 Preprocessor &PP = ASTU->getPreprocessor();
3637 if (const MacroInfo *MI = PP.getMacroInfo(II))
3638 return MI->isFunctionLike();
3639 return false;
3640}
3641
3642unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3643 const IdentifierInfo *II = getMacroIdentifier(C);
3644 if (!II) {
3645 return false;
3646 }
3647 ASTUnit *ASTU = getCursorASTUnit(C);
3648 Preprocessor &PP = ASTU->getPreprocessor();
3649 if (const MacroInfo *MI = PP.getMacroInfo(II))
3650 return MI->isBuiltinMacro();
3651 return false;
3652}
3653
3654unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3655 const Decl *D = getCursorDecl(C);
3656 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3657 if (!FD) {
3658 return false;
3659 }
3660 return FD->isInlined();
3661}
3662
3663static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3664 if (callExpr->getNumArgs() != 1) {
3665 return nullptr;
3666 }
3667
3668 StringLiteral *S = nullptr;
3669 auto *arg = callExpr->getArg(0);
3670 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3671 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3672 auto *subExpr = I->getSubExprAsWritten();
3673
3674 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3675 return nullptr;
3676 }
3677
3678 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3679 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3680 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3681 } else {
3682 return nullptr;
3683 }
3684 return S;
3685}
3686
3687struct ExprEvalResult {
3688 CXEvalResultKind EvalType;
3689 union {
3690 unsigned long long unsignedVal;
3691 long long intVal;
3692 double floatVal;
3693 char *stringVal;
3694 } EvalData;
3695 bool IsUnsignedInt;
3696 ~ExprEvalResult() {
3697 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3698 EvalType != CXEval_Int) {
3699 delete EvalData.stringVal;
3700 }
3701 }
3702};
3703
3704void clang_EvalResult_dispose(CXEvalResult E) {
3705 delete static_cast<ExprEvalResult *>(E);
3706}
3707
3708CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3709 if (!E) {
3710 return CXEval_UnExposed;
3711 }
3712 return ((ExprEvalResult *)E)->EvalType;
3713}
3714
3715int clang_EvalResult_getAsInt(CXEvalResult E) {
3716 return clang_EvalResult_getAsLongLong(E);
3717}
3718
3719long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
3720 if (!E) {
3721 return 0;
3722 }
3723 ExprEvalResult *Result = (ExprEvalResult*)E;
3724 if (Result->IsUnsignedInt)
3725 return Result->EvalData.unsignedVal;
3726 return Result->EvalData.intVal;
3727}
3728
3729unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3730 return ((ExprEvalResult *)E)->IsUnsignedInt;
3731}
3732
3733unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3734 if (!E) {
3735 return 0;
3736 }
3737
3738 ExprEvalResult *Result = (ExprEvalResult*)E;
3739 if (Result->IsUnsignedInt)
3740 return Result->EvalData.unsignedVal;
3741 return Result->EvalData.intVal;
3742}
3743
3744double clang_EvalResult_getAsDouble(CXEvalResult E) {
3745 if (!E) {
3746 return 0;
3747 }
3748 return ((ExprEvalResult *)E)->EvalData.floatVal;
3749}
3750
3751const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3752 if (!E) {
3753 return nullptr;
3754 }
3755 return ((ExprEvalResult *)E)->EvalData.stringVal;
3756}
3757
3758static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3759 Expr::EvalResult ER;
3760 ASTContext &ctx = getCursorContext(C);
3761 if (!expr)
3762 return nullptr;
3763
3764 expr = expr->IgnoreParens();
3765 if (!expr->EvaluateAsRValue(ER, ctx))
3766 return nullptr;
3767
3768 QualType rettype;
3769 CallExpr *callExpr;
3770 auto result = llvm::make_unique<ExprEvalResult>();
3771 result->EvalType = CXEval_UnExposed;
3772 result->IsUnsignedInt = false;
3773
3774 if (ER.Val.isInt()) {
3775 result->EvalType = CXEval_Int;
3776
3777 auto& val = ER.Val.getInt();
3778 if (val.isUnsigned()) {
3779 result->IsUnsignedInt = true;
3780 result->EvalData.unsignedVal = val.getZExtValue();
3781 } else {
3782 result->EvalData.intVal = val.getExtValue();
3783 }
3784
3785 return result.release();
3786 }
3787
3788 if (ER.Val.isFloat()) {
3789 llvm::SmallVector<char, 100> Buffer;
3790 ER.Val.getFloat().toString(Buffer);
3791 std::string floatStr(Buffer.data(), Buffer.size());
3792 result->EvalType = CXEval_Float;
3793 bool ignored;
3794 llvm::APFloat apFloat = ER.Val.getFloat();
3795 apFloat.convert(llvm::APFloat::IEEEdouble(),
3796 llvm::APFloat::rmNearestTiesToEven, &ignored);
3797 result->EvalData.floatVal = apFloat.convertToDouble();
3798 return result.release();
3799 }
3800
3801 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3802 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3803 auto *subExpr = I->getSubExprAsWritten();
3804 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3805 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
3806 const StringLiteral *StrE = nullptr;
3807 const ObjCStringLiteral *ObjCExpr;
3808 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
3809
3810 if (ObjCExpr) {
3811 StrE = ObjCExpr->getString();
3812 result->EvalType = CXEval_ObjCStrLiteral;
3813 } else {
3814 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
3815 result->EvalType = CXEval_StrLiteral;
3816 }
3817
3818 std::string strRef(StrE->getString().str());
3819 result->EvalData.stringVal = new char[strRef.size() + 1];
3820 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3821 strRef.size());
3822 result->EvalData.stringVal[strRef.size()] = '\0';
3823 return result.release();
3824 }
3825 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3826 expr->getStmtClass() == Stmt::StringLiteralClass) {
3827 const StringLiteral *StrE = nullptr;
3828 const ObjCStringLiteral *ObjCExpr;
3829 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
3830
3831 if (ObjCExpr) {
3832 StrE = ObjCExpr->getString();
3833 result->EvalType = CXEval_ObjCStrLiteral;
3834 } else {
3835 StrE = cast<StringLiteral>(expr);
3836 result->EvalType = CXEval_StrLiteral;
3837 }
3838
3839 std::string strRef(StrE->getString().str());
3840 result->EvalData.stringVal = new char[strRef.size() + 1];
3841 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3842 result->EvalData.stringVal[strRef.size()] = '\0';
3843 return result.release();
3844 }
3845
3846 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3847 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
3848
3849 rettype = CC->getType();
3850 if (rettype.getAsString() == "CFStringRef" &&
3851 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
3852
3853 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3854 StringLiteral *S = getCFSTR_value(callExpr);
3855 if (S) {
3856 std::string strLiteral(S->getString().str());
3857 result->EvalType = CXEval_CFStr;
3858
3859 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3860 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3861 strLiteral.size());
3862 result->EvalData.stringVal[strLiteral.size()] = '\0';
3863 return result.release();
3864 }
3865 }
3866
3867 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3868 callExpr = static_cast<CallExpr *>(expr);
3869 rettype = callExpr->getCallReturnType(ctx);
3870
3871 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3872 return nullptr;
3873
3874 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3875 if (callExpr->getNumArgs() == 1 &&
3876 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3877 return nullptr;
3878 } else if (rettype.getAsString() == "CFStringRef") {
3879
3880 StringLiteral *S = getCFSTR_value(callExpr);
3881 if (S) {
3882 std::string strLiteral(S->getString().str());
3883 result->EvalType = CXEval_CFStr;
3884 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3885 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3886 strLiteral.size());
3887 result->EvalData.stringVal[strLiteral.size()] = '\0';
3888 return result.release();
3889 }
3890 }
3891 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3892 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3893 ValueDecl *V = D->getDecl();
3894 if (V->getKind() == Decl::Function) {
3895 std::string strName = V->getNameAsString();
3896 result->EvalType = CXEval_Other;
3897 result->EvalData.stringVal = new char[strName.size() + 1];
3898 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3899 result->EvalData.stringVal[strName.size()] = '\0';
3900 return result.release();
3901 }
3902 }
3903
3904 return nullptr;
3905}
3906
3907CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3908 const Decl *D = getCursorDecl(C);
3909 if (D) {
3910 const Expr *expr = nullptr;
3911 if (auto *Var = dyn_cast<VarDecl>(D)) {
3912 expr = Var->getInit();
3913 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3914 expr = Field->getInClassInitializer();
3915 }
3916 if (expr)
3917 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3918 evaluateExpr(const_cast<Expr *>(expr), C)));
3919 return nullptr;
3920 }
3921
3922 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3923 if (compoundStmt) {
3924 Expr *expr = nullptr;
3925 for (auto *bodyIterator : compoundStmt->body()) {
3926 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3927 break;
3928 }
3929 }
3930 if (expr)
3931 return const_cast<CXEvalResult>(
3932 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
3933 }
3934 return nullptr;
3935}
3936
3937unsigned clang_Cursor_hasAttrs(CXCursor C) {
3938 const Decl *D = getCursorDecl(C);
3939 if (!D) {
3940 return 0;
3941 }
3942
3943 if (D->hasAttrs()) {
3944 return 1;
3945 }
3946
3947 return 0;
3948}
3949unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3950 return CXSaveTranslationUnit_None;
3951}
3952
3953static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3954 const char *FileName,
3955 unsigned options) {
3956 CIndexer *CXXIdx = TU->CIdx;
3957 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3958 setThreadBackgroundPriority();
3959
3960 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3961 return hadError ? CXSaveError_Unknown : CXSaveError_None;
3962}
3963
3964int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3965 unsigned options) {
3966 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
3967 *Log << TU << ' ' << FileName;
3968 }
3969
3970 if (isNotUsableTU(TU)) {
3971 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
3972 return CXSaveError_InvalidTU;
3973 }
3974
3975 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3976 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3977 if (!CXXUnit->hasSema())
3978 return CXSaveError_InvalidTU;
3979
3980 CXSaveError result;
3981 auto SaveTranslationUnitImpl = [=, &result]() {
3982 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3983 };
3984
3985 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
3986 SaveTranslationUnitImpl();
3987
3988 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3989 PrintLibclangResourceUsage(TU);
3990
3991 return result;
3992 }
3993
3994 // We have an AST that has invalid nodes due to compiler errors.
3995 // Use a crash recovery thread for protection.
3996
3997 llvm::CrashRecoveryContext CRC;
3998
3999 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
4000 fprintf(stderrstderr, "libclang: crash detected during AST saving: {\n");
4001 fprintf(stderrstderr, " 'filename' : '%s'\n", FileName);
4002 fprintf(stderrstderr, " 'options' : %d,\n", options);
4003 fprintf(stderrstderr, "}\n");
4004
4005 return CXSaveError_Unknown;
4006
4007 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4008 PrintLibclangResourceUsage(TU);
4009 }
4010
4011 return result;
4012}
4013
4014void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4015 if (CTUnit) {
4016 // If the translation unit has been marked as unsafe to free, just discard
4017 // it.
4018 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4019 if (Unit && Unit->isUnsafeToFree())
4020 return;
4021
4022 delete cxtu::getASTUnit(CTUnit);
4023 delete CTUnit->StringPool;
4024 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4025 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
4026 delete CTUnit->CommentToXML;
4027 delete CTUnit;
4028 }
4029}
4030
4031unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4032 if (CTUnit) {
4033 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4034
4035 if (Unit && Unit->isUnsafeToFree())
4036 return false;
4037
4038 Unit->ResetForParse();
4039 return true;
4040 }
4041
4042 return false;
4043}
4044
4045unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4046 return CXReparse_None;
4047}
4048
4049static CXErrorCode
4050clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4051 ArrayRef<CXUnsavedFile> unsaved_files,
4052 unsigned options) {
4053 // Check arguments.
4054 if (isNotUsableTU(TU)) {
4055 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4056 return CXError_InvalidArguments;
4057 }
4058
4059 // Reset the associated diagnostics.
4060 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
4061 TU->Diagnostics = nullptr;
4062
4063 CIndexer *CXXIdx = TU->CIdx;
4064 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4065 setThreadBackgroundPriority();
4066
4067 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4068 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4069
4070 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4071 new std::vector<ASTUnit::RemappedFile>());
4072
4073 // Recover resources if we crash before exiting this function.
4074 llvm::CrashRecoveryContextCleanupRegistrar<
4075 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
4076
4077 for (auto &UF : unsaved_files) {
4078 std::unique_ptr<llvm::MemoryBuffer> MB =
4079 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
4080 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
4081 }
4082
4083 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4084 *RemappedFiles.get()))
4085 return CXError_Success;
4086 if (isASTReadError(CXXUnit))
4087 return CXError_ASTReadError;
4088 return CXError_Failure;
4089}
4090
4091int clang_reparseTranslationUnit(CXTranslationUnit TU,
4092 unsigned num_unsaved_files,
4093 struct CXUnsavedFile *unsaved_files,
4094 unsigned options) {
4095 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
4096 *Log << TU;
4097 }
4098
4099 if (num_unsaved_files && !unsaved_files)
1
Assuming 'num_unsaved_files' is 0
4100 return CXError_InvalidArguments;
4101
4102 CXErrorCode result;
4103 auto ReparseTranslationUnitImpl = [=, &result]() {
4104 result = clang_reparseTranslationUnit_Impl(
4105 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4106 };
4107
4108 llvm::CrashRecoveryContext CRC;
4109
4110 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
2
Assuming the condition is false
3
Taking false branch
4111 fprintf(stderrstderr, "libclang: crash detected during reparsing\n");
4112 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
4113 return CXError_Crashed;
4114 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4
Assuming the condition is true
5
Taking true branch
4115 PrintLibclangResourceUsage(TU);
6
Calling 'PrintLibclangResourceUsage'
4116
4117 return result;
4118}
4119
4120
4121CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
4122 if (isNotUsableTU(CTUnit)) {
4123 LOG_BAD_TU(CTUnit)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
CTUnit; } } while(false)
;
4124 return cxstring::createEmpty();
4125 }
4126
4127 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4128 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
4129}
4130
4131CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
4132 if (isNotUsableTU(TU)) {
4133 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4134 return clang_getNullCursor();
4135 }
4136
4137 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4138 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4139}
4140
4141CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4142 if (isNotUsableTU(CTUnit)) {
4143 LOG_BAD_TU(CTUnit)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
CTUnit; } } while(false)
;
4144 return nullptr;
4145 }
4146
4147 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4148 impl->TranslationUnit = CTUnit;
4149 return impl;
4150}
4151
4152CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4153 if (!TargetInfo)
4154 return cxstring::createEmpty();
4155
4156 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4157 assert(!isNotUsableTU(CTUnit) &&((!isNotUsableTU(CTUnit) && "Unexpected unusable translation unit in TargetInfo"
) ? static_cast<void> (0) : __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4158, __PRETTY_FUNCTION__))
4158 "Unexpected unusable translation unit in TargetInfo")((!isNotUsableTU(CTUnit) && "Unexpected unusable translation unit in TargetInfo"
) ? static_cast<void> (0) : __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4158, __PRETTY_FUNCTION__))
;
4159
4160 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4161 std::string Triple =
4162 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4163 return cxstring::createDup(Triple);
4164}
4165
4166int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4167 if (!TargetInfo)
4168 return -1;
4169
4170 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4171 assert(!isNotUsableTU(CTUnit) &&((!isNotUsableTU(CTUnit) && "Unexpected unusable translation unit in TargetInfo"
) ? static_cast<void> (0) : __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4172, __PRETTY_FUNCTION__))
4172 "Unexpected unusable translation unit in TargetInfo")((!isNotUsableTU(CTUnit) && "Unexpected unusable translation unit in TargetInfo"
) ? static_cast<void> (0) : __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4172, __PRETTY_FUNCTION__))
;
4173
4174 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4175 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4176}
4177
4178void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4179 if (!TargetInfo)
4180 return;
4181
4182 delete TargetInfo;
4183}
4184
4185//===----------------------------------------------------------------------===//
4186// CXFile Operations.
4187//===----------------------------------------------------------------------===//
4188
4189CXString clang_getFileName(CXFile SFile) {
4190 if (!SFile)
4191 return cxstring::createNull();
4192
4193 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4194 return cxstring::createRef(FEnt->getName());
4195}
4196
4197time_t clang_getFileTime(CXFile SFile) {
4198 if (!SFile)
4199 return 0;
4200
4201 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4202 return FEnt->getModificationTime();
4203}
4204
4205CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
4206 if (isNotUsableTU(TU)) {
4207 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4208 return nullptr;
4209 }
4210
4211 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4212
4213 FileManager &FMgr = CXXUnit->getFileManager();
4214 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4215}
4216
4217const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4218 size_t *size) {
4219 if (isNotUsableTU(TU)) {
4220 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4221 return nullptr;
4222 }
4223
4224 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4225 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4226 bool Invalid = true;
4227 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4228 if (Invalid) {
4229 if (size)
4230 *size = 0;
4231 return nullptr;
4232 }
4233 if (size)
4234 *size = buf->getBufferSize();
4235 return buf->getBufferStart();
4236}
4237
4238unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4239 CXFile file) {
4240 if (isNotUsableTU(TU)) {
4241 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4242 return 0;
4243 }
4244
4245 if (!file)
4246 return 0;
4247
4248 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4249 FileEntry *FEnt = static_cast<FileEntry *>(file);
4250 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4251 .isFileMultipleIncludeGuarded(FEnt);
4252}
4253
4254int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4255 if (!file || !outID)
4256 return 1;
4257
4258 FileEntry *FEnt = static_cast<FileEntry *>(file);
4259 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4260 outID->data[0] = ID.getDevice();
4261 outID->data[1] = ID.getFile();
4262 outID->data[2] = FEnt->getModificationTime();
4263 return 0;
4264}
4265
4266int clang_File_isEqual(CXFile file1, CXFile file2) {
4267 if (file1 == file2)
4268 return true;
4269
4270 if (!file1 || !file2)
4271 return false;
4272
4273 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4274 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4275 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4276}
4277
4278CXString clang_File_tryGetRealPathName(CXFile SFile) {
4279 if (!SFile)
4280 return cxstring::createNull();
4281
4282 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4283 return cxstring::createRef(FEnt->tryGetRealPathName());
4284}
4285
4286//===----------------------------------------------------------------------===//
4287// CXCursor Operations.
4288//===----------------------------------------------------------------------===//
4289
4290static const Decl *getDeclFromExpr(const Stmt *E) {
4291 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4292 return getDeclFromExpr(CE->getSubExpr());
4293
4294 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
4295 return RefExpr->getDecl();
4296 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4297 return ME->getMemberDecl();
4298 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
4299 return RE->getDecl();
4300 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
4301 if (PRE->isExplicitProperty())
4302 return PRE->getExplicitProperty();
4303 // It could be messaging both getter and setter as in:
4304 // ++myobj.myprop;
4305 // in which case prefer to associate the setter since it is less obvious
4306 // from inspecting the source that the setter is going to get called.
4307 if (PRE->isMessagingSetter())
4308 return PRE->getImplicitPropertySetter();
4309 return PRE->getImplicitPropertyGetter();
4310 }
4311 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
4312 return getDeclFromExpr(POE->getSyntacticForm());
4313 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4314 if (Expr *Src = OVE->getSourceExpr())
4315 return getDeclFromExpr(Src);
4316
4317 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
4318 return getDeclFromExpr(CE->getCallee());
4319 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
4320 if (!CE->isElidable())
4321 return CE->getConstructor();
4322 if (const CXXInheritedCtorInitExpr *CE =
4323 dyn_cast<CXXInheritedCtorInitExpr>(E))
4324 return CE->getConstructor();
4325 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
4326 return OME->getMethodDecl();
4327
4328 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
4329 return PE->getProtocol();
4330 if (const SubstNonTypeTemplateParmPackExpr *NTTP
4331 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4332 return NTTP->getParameterPack();
4333 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4334 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4335 isa<ParmVarDecl>(SizeOfPack->getPack()))
4336 return SizeOfPack->getPack();
4337
4338 return nullptr;
4339}
4340
4341static SourceLocation getLocationFromExpr(const Expr *E) {
4342 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4343 return getLocationFromExpr(CE->getSubExpr());
4344
4345 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
4346 return /*FIXME:*/Msg->getLeftLoc();
4347 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4348 return DRE->getLocation();
4349 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
4350 return Member->getMemberLoc();
4351 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
4352 return Ivar->getLocation();
4353 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4354 return SizeOfPack->getPackLoc();
4355 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
4356 return PropRef->getLocation();
4357
4358 return E->getBeginLoc();
4359}
4360
4361extern "C" {
4362
4363unsigned clang_visitChildren(CXCursor parent,
4364 CXCursorVisitor visitor,
4365 CXClientData client_data) {
4366 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4367 /*VisitPreprocessorLast=*/false);
4368 return CursorVis.VisitChildren(parent);
4369}
4370
4371#ifndef __has_feature
4372#define0 __has_feature(x)0 0
4373#endif
4374#if __has_feature(blocks)0
4375typedef enum CXChildVisitResult
4376 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4377
4378static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4379 CXClientData client_data) {
4380 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4381 return block(cursor, parent);
4382}
4383#else
4384// If we are compiled with a compiler that doesn't have native blocks support,
4385// define and call the block manually, so the
4386typedef struct _CXChildVisitResult
4387{
4388 void *isa;
4389 int flags;
4390 int reserved;
4391 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4392 CXCursor);
4393} *CXCursorVisitorBlock;
4394
4395static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4396 CXClientData client_data) {
4397 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4398 return block->invoke(block, cursor, parent);
4399}
4400#endif
4401
4402
4403unsigned clang_visitChildrenWithBlock(CXCursor parent,
4404 CXCursorVisitorBlock block) {
4405 return clang_visitChildren(parent, visitWithBlock, block);
4406}
4407
4408static CXString getDeclSpelling(const Decl *D) {
4409 if (!D)
4410 return cxstring::createEmpty();
4411
4412 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
4413 if (!ND) {
4414 if (const ObjCPropertyImplDecl *PropImpl =
4415 dyn_cast<ObjCPropertyImplDecl>(D))
4416 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4417 return cxstring::createDup(Property->getIdentifier()->getName());
4418
4419 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
4420 if (Module *Mod = ImportD->getImportedModule())
4421 return cxstring::createDup(Mod->getFullModuleName());
4422
4423 return cxstring::createEmpty();
4424 }
4425
4426 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
4427 return cxstring::createDup(OMD->getSelector().getAsString());
4428
4429 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
4430 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4431 // and returns different names. NamedDecl returns the class name and
4432 // ObjCCategoryImplDecl returns the category name.
4433 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
4434
4435 if (isa<UsingDirectiveDecl>(D))
4436 return cxstring::createEmpty();
4437
4438 SmallString<1024> S;
4439 llvm::raw_svector_ostream os(S);
4440 ND->printName(os);
4441
4442 return cxstring::createDup(os.str());
4443}
4444
4445CXString clang_getCursorSpelling(CXCursor C) {
4446 if (clang_isTranslationUnit(C.kind))
4447 return clang_getTranslationUnitSpelling(getCursorTU(C));
4448
4449 if (clang_isReference(C.kind)) {
4450 switch (C.kind) {
4451 case CXCursor_ObjCSuperClassRef: {
4452 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
4453 return cxstring::createRef(Super->getIdentifier()->getNameStart());
4454 }
4455 case CXCursor_ObjCClassRef: {
4456 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4457 return cxstring::createRef(Class->getIdentifier()->getNameStart());
4458 }
4459 case CXCursor_ObjCProtocolRef: {
4460 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
4461 assert(OID && "getCursorSpelling(): Missing protocol decl")((OID && "getCursorSpelling(): Missing protocol decl"
) ? static_cast<void> (0) : __assert_fail ("OID && \"getCursorSpelling(): Missing protocol decl\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4461, __PRETTY_FUNCTION__))
;
4462 return cxstring::createRef(OID->getIdentifier()->getNameStart());
4463 }
4464 case CXCursor_CXXBaseSpecifier: {
4465 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
4466 return cxstring::createDup(B->getType().getAsString());
4467 }
4468 case CXCursor_TypeRef: {
4469 const TypeDecl *Type = getCursorTypeRef(C).first;
4470 assert(Type && "Missing type decl")((Type && "Missing type decl") ? static_cast<void>
(0) : __assert_fail ("Type && \"Missing type decl\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4470, __PRETTY_FUNCTION__))
;
4471
4472 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
4473 getAsString());
4474 }
4475 case CXCursor_TemplateRef: {
4476 const TemplateDecl *Template = getCursorTemplateRef(C).first;
4477 assert(Template && "Missing template decl")((Template && "Missing template decl") ? static_cast<
void> (0) : __assert_fail ("Template && \"Missing template decl\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4477, __PRETTY_FUNCTION__))
;
4478
4479 return cxstring::createDup(Template->getNameAsString());
4480 }
4481
4482 case CXCursor_NamespaceRef: {
4483 const NamedDecl *NS = getCursorNamespaceRef(C).first;
4484 assert(NS && "Missing namespace decl")((NS && "Missing namespace decl") ? static_cast<void
> (0) : __assert_fail ("NS && \"Missing namespace decl\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4484, __PRETTY_FUNCTION__))
;
4485
4486 return cxstring::createDup(NS->getNameAsString());
4487 }
4488
4489 case CXCursor_MemberRef: {
4490 const FieldDecl *Field = getCursorMemberRef(C).first;
4491 assert(Field && "Missing member decl")((Field && "Missing member decl") ? static_cast<void
> (0) : __assert_fail ("Field && \"Missing member decl\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4491, __PRETTY_FUNCTION__))
;
4492
4493 return cxstring::createDup(Field->getNameAsString());
4494 }
4495
4496 case CXCursor_LabelRef: {
4497 const LabelStmt *Label = getCursorLabelRef(C).first;
4498 assert(Label && "Missing label")((Label && "Missing label") ? static_cast<void>
(0) : __assert_fail ("Label && \"Missing label\"", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4498, __PRETTY_FUNCTION__))
;
4499
4500 return cxstring::createRef(Label->getName());
4501 }
4502
4503 case CXCursor_OverloadedDeclRef: {
4504 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4505 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4506 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
4507 return cxstring::createDup(ND->getNameAsString());
4508 return cxstring::createEmpty();
4509 }
4510 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4511 return cxstring::createDup(E->getName().getAsString());
4512 OverloadedTemplateStorage *Ovl
4513 = Storage.get<OverloadedTemplateStorage*>();
4514 if (Ovl->size() == 0)
4515 return cxstring::createEmpty();
4516 return cxstring::createDup((*Ovl->begin())->getNameAsString());
4517 }
4518
4519 case CXCursor_VariableRef: {
4520 const VarDecl *Var = getCursorVariableRef(C).first;
4521 assert(Var && "Missing variable decl")((Var && "Missing variable decl") ? static_cast<void
> (0) : __assert_fail ("Var && \"Missing variable decl\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4521, __PRETTY_FUNCTION__))
;
4522
4523 return cxstring::createDup(Var->getNameAsString());
4524 }
4525
4526 default:
4527 return cxstring::createRef("<not implemented>");
4528 }
4529 }
4530
4531 if (clang_isExpression(C.kind)) {
4532 const Expr *E = getCursorExpr(C);
4533
4534 if (C.kind == CXCursor_ObjCStringLiteral ||
4535 C.kind == CXCursor_StringLiteral) {
4536 const StringLiteral *SLit;
4537 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4538 SLit = OSL->getString();
4539 } else {
4540 SLit = cast<StringLiteral>(E);
4541 }
4542 SmallString<256> Buf;
4543 llvm::raw_svector_ostream OS(Buf);
4544 SLit->outputString(OS);
4545 return cxstring::createDup(OS.str());
4546 }
4547
4548 const Decl *D = getDeclFromExpr(getCursorExpr(C));
4549 if (D)
4550 return getDeclSpelling(D);
4551 return cxstring::createEmpty();
4552 }
4553
4554 if (clang_isStatement(C.kind)) {
4555 const Stmt *S = getCursorStmt(C);
4556 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
4557 return cxstring::createRef(Label->getName());
4558
4559 return cxstring::createEmpty();
4560 }
4561
4562 if (C.kind == CXCursor_MacroExpansion)
4563 return cxstring::createRef(getCursorMacroExpansion(C).getName()
4564 ->getNameStart());
4565
4566 if (C.kind == CXCursor_MacroDefinition)
4567 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
4568 ->getNameStart());
4569
4570 if (C.kind == CXCursor_InclusionDirective)
4571 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
4572
4573 if (clang_isDeclaration(C.kind))
4574 return getDeclSpelling(getCursorDecl(C));
4575
4576 if (C.kind == CXCursor_AnnotateAttr) {
4577 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
4578 return cxstring::createDup(AA->getAnnotation());
4579 }
4580
4581 if (C.kind == CXCursor_AsmLabelAttr) {
4582 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
4583 return cxstring::createDup(AA->getLabel());
4584 }
4585
4586 if (C.kind == CXCursor_PackedAttr) {
4587 return cxstring::createRef("packed");
4588 }
4589
4590 if (C.kind == CXCursor_VisibilityAttr) {
4591 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4592 switch (AA->getVisibility()) {
4593 case VisibilityAttr::VisibilityType::Default:
4594 return cxstring::createRef("default");
4595 case VisibilityAttr::VisibilityType::Hidden:
4596 return cxstring::createRef("hidden");
4597 case VisibilityAttr::VisibilityType::Protected:
4598 return cxstring::createRef("protected");
4599 }
4600 llvm_unreachable("unknown visibility type")::llvm::llvm_unreachable_internal("unknown visibility type", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4600)
;
4601 }
4602
4603 return cxstring::createEmpty();
4604}
4605
4606CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4607 unsigned pieceIndex,
4608 unsigned options) {
4609 if (clang_Cursor_isNull(C))
4610 return clang_getNullRange();
4611
4612 ASTContext &Ctx = getCursorContext(C);
4613
4614 if (clang_isStatement(C.kind)) {
4615 const Stmt *S = getCursorStmt(C);
4616 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
4617 if (pieceIndex > 0)
4618 return clang_getNullRange();
4619 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4620 }
4621
4622 return clang_getNullRange();
4623 }
4624
4625 if (C.kind == CXCursor_ObjCMessageExpr) {
4626 if (const ObjCMessageExpr *
4627 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4628 if (pieceIndex >= ME->getNumSelectorLocs())
4629 return clang_getNullRange();
4630 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4631 }
4632 }
4633
4634 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4635 C.kind == CXCursor_ObjCClassMethodDecl) {
4636 if (const ObjCMethodDecl *
4637 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4638 if (pieceIndex >= MD->getNumSelectorLocs())
4639 return clang_getNullRange();
4640 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4641 }
4642 }
4643
4644 if (C.kind == CXCursor_ObjCCategoryDecl ||
4645 C.kind == CXCursor_ObjCCategoryImplDecl) {
4646 if (pieceIndex > 0)
4647 return clang_getNullRange();
4648 if (const ObjCCategoryDecl *
4649 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4650 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
4651 if (const ObjCCategoryImplDecl *
4652 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4653 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4654 }
4655
4656 if (C.kind == CXCursor_ModuleImportDecl) {
4657 if (pieceIndex > 0)
4658 return clang_getNullRange();
4659 if (const ImportDecl *ImportD =
4660 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
4661 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4662 if (!Locs.empty())
4663 return cxloc::translateSourceRange(Ctx,
4664 SourceRange(Locs.front(), Locs.back()));
4665 }
4666 return clang_getNullRange();
4667 }
4668
4669 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
4670 C.kind == CXCursor_ConversionFunction ||
4671 C.kind == CXCursor_FunctionDecl) {
4672 if (pieceIndex > 0)
4673 return clang_getNullRange();
4674 if (const FunctionDecl *FD =
4675 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4676 DeclarationNameInfo FunctionName = FD->getNameInfo();
4677 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4678 }
4679 return clang_getNullRange();
4680 }
4681
4682 // FIXME: A CXCursor_InclusionDirective should give the location of the
4683 // filename, but we don't keep track of this.
4684
4685 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4686 // but we don't keep track of this.
4687
4688 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4689 // but we don't keep track of this.
4690
4691 // Default handling, give the location of the cursor.
4692
4693 if (pieceIndex > 0)
4694 return clang_getNullRange();
4695
4696 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4697 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4698 return cxloc::translateSourceRange(Ctx, Loc);
4699}
4700
4701CXString clang_Cursor_getMangling(CXCursor C) {
4702 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4703 return cxstring::createEmpty();
4704
4705 // Mangling only works for functions and variables.
4706 const Decl *D = getCursorDecl(C);
4707 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4708 return cxstring::createEmpty();
4709
4710 ASTContext &Ctx = D->getASTContext();
4711 index::CodegenNameGenerator CGNameGen(Ctx);
4712 return cxstring::createDup(CGNameGen.getName(D));
4713}
4714
4715CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4716 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4717 return nullptr;
4718
4719 const Decl *D = getCursorDecl(C);
4720 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4721 return nullptr;
4722
4723 ASTContext &Ctx = D->getASTContext();
4724 index::CodegenNameGenerator CGNameGen(Ctx);
4725 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4726 return cxstring::createSet(Manglings);
4727}
4728
4729CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4730 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4731 return nullptr;
4732
4733 const Decl *D = getCursorDecl(C);
4734 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4735 return nullptr;
4736
4737 ASTContext &Ctx = D->getASTContext();
4738 index::CodegenNameGenerator CGNameGen(Ctx);
4739 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4740 return cxstring::createSet(Manglings);
4741}
4742
4743CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4744 if (clang_Cursor_isNull(C))
4745 return 0;
4746 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4747}
4748
4749void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4750 if (Policy)
4751 delete static_cast<PrintingPolicy *>(Policy);
4752}
4753
4754unsigned
4755clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4756 enum CXPrintingPolicyProperty Property) {
4757 if (!Policy)
4758 return 0;
4759
4760 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4761 switch (Property) {
4762 case CXPrintingPolicy_Indentation:
4763 return P->Indentation;
4764 case CXPrintingPolicy_SuppressSpecifiers:
4765 return P->SuppressSpecifiers;
4766 case CXPrintingPolicy_SuppressTagKeyword:
4767 return P->SuppressTagKeyword;
4768 case CXPrintingPolicy_IncludeTagDefinition:
4769 return P->IncludeTagDefinition;
4770 case CXPrintingPolicy_SuppressScope:
4771 return P->SuppressScope;
4772 case CXPrintingPolicy_SuppressUnwrittenScope:
4773 return P->SuppressUnwrittenScope;
4774 case CXPrintingPolicy_SuppressInitializers:
4775 return P->SuppressInitializers;
4776 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4777 return P->ConstantArraySizeAsWritten;
4778 case CXPrintingPolicy_AnonymousTagLocations:
4779 return P->AnonymousTagLocations;
4780 case CXPrintingPolicy_SuppressStrongLifetime:
4781 return P->SuppressStrongLifetime;
4782 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4783 return P->SuppressLifetimeQualifiers;
4784 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4785 return P->SuppressTemplateArgsInCXXConstructors;
4786 case CXPrintingPolicy_Bool:
4787 return P->Bool;
4788 case CXPrintingPolicy_Restrict:
4789 return P->Restrict;
4790 case CXPrintingPolicy_Alignof:
4791 return P->Alignof;
4792 case CXPrintingPolicy_UnderscoreAlignof:
4793 return P->UnderscoreAlignof;
4794 case CXPrintingPolicy_UseVoidForZeroParams:
4795 return P->UseVoidForZeroParams;
4796 case CXPrintingPolicy_TerseOutput:
4797 return P->TerseOutput;
4798 case CXPrintingPolicy_PolishForDeclaration:
4799 return P->PolishForDeclaration;
4800 case CXPrintingPolicy_Half:
4801 return P->Half;
4802 case CXPrintingPolicy_MSWChar:
4803 return P->MSWChar;
4804 case CXPrintingPolicy_IncludeNewlines:
4805 return P->IncludeNewlines;
4806 case CXPrintingPolicy_MSVCFormatting:
4807 return P->MSVCFormatting;
4808 case CXPrintingPolicy_ConstantsAsWritten:
4809 return P->ConstantsAsWritten;
4810 case CXPrintingPolicy_SuppressImplicitBase:
4811 return P->SuppressImplicitBase;
4812 case CXPrintingPolicy_FullyQualifiedName:
4813 return P->FullyQualifiedName;
4814 }
4815
4816 assert(false && "Invalid CXPrintingPolicyProperty")((false && "Invalid CXPrintingPolicyProperty") ? static_cast
<void> (0) : __assert_fail ("false && \"Invalid CXPrintingPolicyProperty\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4816, __PRETTY_FUNCTION__))
;
4817 return 0;
4818}
4819
4820void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4821 enum CXPrintingPolicyProperty Property,
4822 unsigned Value) {
4823 if (!Policy)
4824 return;
4825
4826 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4827 switch (Property) {
4828 case CXPrintingPolicy_Indentation:
4829 P->Indentation = Value;
4830 return;
4831 case CXPrintingPolicy_SuppressSpecifiers:
4832 P->SuppressSpecifiers = Value;
4833 return;
4834 case CXPrintingPolicy_SuppressTagKeyword:
4835 P->SuppressTagKeyword = Value;
4836 return;
4837 case CXPrintingPolicy_IncludeTagDefinition:
4838 P->IncludeTagDefinition = Value;
4839 return;
4840 case CXPrintingPolicy_SuppressScope:
4841 P->SuppressScope = Value;
4842 return;
4843 case CXPrintingPolicy_SuppressUnwrittenScope:
4844 P->SuppressUnwrittenScope = Value;
4845 return;
4846 case CXPrintingPolicy_SuppressInitializers:
4847 P->SuppressInitializers = Value;
4848 return;
4849 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4850 P->ConstantArraySizeAsWritten = Value;
4851 return;
4852 case CXPrintingPolicy_AnonymousTagLocations:
4853 P->AnonymousTagLocations = Value;
4854 return;
4855 case CXPrintingPolicy_SuppressStrongLifetime:
4856 P->SuppressStrongLifetime = Value;
4857 return;
4858 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4859 P->SuppressLifetimeQualifiers = Value;
4860 return;
4861 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4862 P->SuppressTemplateArgsInCXXConstructors = Value;
4863 return;
4864 case CXPrintingPolicy_Bool:
4865 P->Bool = Value;
4866 return;
4867 case CXPrintingPolicy_Restrict:
4868 P->Restrict = Value;
4869 return;
4870 case CXPrintingPolicy_Alignof:
4871 P->Alignof = Value;
4872 return;
4873 case CXPrintingPolicy_UnderscoreAlignof:
4874 P->UnderscoreAlignof = Value;
4875 return;
4876 case CXPrintingPolicy_UseVoidForZeroParams:
4877 P->UseVoidForZeroParams = Value;
4878 return;
4879 case CXPrintingPolicy_TerseOutput:
4880 P->TerseOutput = Value;
4881 return;
4882 case CXPrintingPolicy_PolishForDeclaration:
4883 P->PolishForDeclaration = Value;
4884 return;
4885 case CXPrintingPolicy_Half:
4886 P->Half = Value;
4887 return;
4888 case CXPrintingPolicy_MSWChar:
4889 P->MSWChar = Value;
4890 return;
4891 case CXPrintingPolicy_IncludeNewlines:
4892 P->IncludeNewlines = Value;
4893 return;
4894 case CXPrintingPolicy_MSVCFormatting:
4895 P->MSVCFormatting = Value;
4896 return;
4897 case CXPrintingPolicy_ConstantsAsWritten:
4898 P->ConstantsAsWritten = Value;
4899 return;
4900 case CXPrintingPolicy_SuppressImplicitBase:
4901 P->SuppressImplicitBase = Value;
4902 return;
4903 case CXPrintingPolicy_FullyQualifiedName:
4904 P->FullyQualifiedName = Value;
4905 return;
4906 }
4907
4908 assert(false && "Invalid CXPrintingPolicyProperty")((false && "Invalid CXPrintingPolicyProperty") ? static_cast
<void> (0) : __assert_fail ("false && \"Invalid CXPrintingPolicyProperty\""
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 4908, __PRETTY_FUNCTION__))
;
4909}
4910
4911CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4912 if (clang_Cursor_isNull(C))
4913 return cxstring::createEmpty();
4914
4915 if (clang_isDeclaration(C.kind)) {
4916 const Decl *D = getCursorDecl(C);
4917 if (!D)
4918 return cxstring::createEmpty();
4919
4920 SmallString<128> Str;
4921 llvm::raw_svector_ostream OS(Str);
4922 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4923 D->print(OS, UserPolicy ? *UserPolicy
4924 : getCursorContext(C).getPrintingPolicy());
4925
4926 return cxstring::createDup(OS.str());
4927 }
4928
4929 return cxstring::createEmpty();
4930}
4931
4932CXString clang_getCursorDisplayName(CXCursor C) {
4933 if (!clang_isDeclaration(C.kind))
4934 return clang_getCursorSpelling(C);
4935
4936 const Decl *D = getCursorDecl(C);
4937 if (!D)
4938 return cxstring::createEmpty();
4939
4940 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
4941 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
4942 D = FunTmpl->getTemplatedDecl();
4943
4944 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
4945 SmallString<64> Str;
4946 llvm::raw_svector_ostream OS(Str);
4947 OS << *Function;
4948 if (Function->getPrimaryTemplate())
4949 OS << "<>";
4950 OS << "(";
4951 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4952 if (I)
4953 OS << ", ";
4954 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4955 }
4956
4957 if (Function->isVariadic()) {
4958 if (Function->getNumParams())
4959 OS << ", ";
4960 OS << "...";
4961 }
4962 OS << ")";
4963 return cxstring::createDup(OS.str());
4964 }
4965
4966 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
4967 SmallString<64> Str;
4968 llvm::raw_svector_ostream OS(Str);
4969 OS << *ClassTemplate;
4970 OS << "<";
4971 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4972 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4973 if (I)
4974 OS << ", ";
4975
4976 NamedDecl *Param = Params->getParam(I);
4977 if (Param->getIdentifier()) {
4978 OS << Param->getIdentifier()->getName();
4979 continue;
4980 }
4981
4982 // There is no parameter name, which makes this tricky. Try to come up
4983 // with something useful that isn't too long.
4984 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4985 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4986 else if (NonTypeTemplateParmDecl *NTTP
4987 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4988 OS << NTTP->getType().getAsString(Policy);
4989 else
4990 OS << "template<...> class";
4991 }
4992
4993 OS << ">";
4994 return cxstring::createDup(OS.str());
4995 }
4996
4997 if (const ClassTemplateSpecializationDecl *ClassSpec
4998 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4999 // If the type was explicitly written, use that.
5000 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
5001 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
5002
5003 SmallString<128> Str;
5004 llvm::raw_svector_ostream OS(Str);
5005 OS << *ClassSpec;
5006 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5007 Policy);
5008 return cxstring::createDup(OS.str());
5009 }
5010
5011 return clang_getCursorSpelling(C);
5012}
5013
5014CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5015 switch (Kind) {
5016 case CXCursor_FunctionDecl:
5017 return cxstring::createRef("FunctionDecl");
5018 case CXCursor_TypedefDecl:
5019 return cxstring::createRef("TypedefDecl");
5020 case CXCursor_EnumDecl:
5021 return cxstring::createRef("EnumDecl");
5022 case CXCursor_EnumConstantDecl:
5023 return cxstring::createRef("EnumConstantDecl");
5024 case CXCursor_StructDecl:
5025 return cxstring::createRef("StructDecl");
5026 case CXCursor_UnionDecl:
5027 return cxstring::createRef("UnionDecl");
5028 case CXCursor_ClassDecl:
5029 return cxstring::createRef("ClassDecl");
5030 case CXCursor_FieldDecl:
5031 return cxstring::createRef("FieldDecl");
5032 case CXCursor_VarDecl:
5033 return cxstring::createRef("VarDecl");
5034 case CXCursor_ParmDecl:
5035 return cxstring::createRef("ParmDecl");
5036 case CXCursor_ObjCInterfaceDecl:
5037 return cxstring::createRef("ObjCInterfaceDecl");
5038 case CXCursor_ObjCCategoryDecl:
5039 return cxstring::createRef("ObjCCategoryDecl");
5040 case CXCursor_ObjCProtocolDecl:
5041 return cxstring::createRef("ObjCProtocolDecl");
5042 case CXCursor_ObjCPropertyDecl:
5043 return cxstring::createRef("ObjCPropertyDecl");
5044 case CXCursor_ObjCIvarDecl:
5045 return cxstring::createRef("ObjCIvarDecl");
5046 case CXCursor_ObjCInstanceMethodDecl:
5047 return cxstring::createRef("ObjCInstanceMethodDecl");
5048 case CXCursor_ObjCClassMethodDecl:
5049 return cxstring::createRef("ObjCClassMethodDecl");
5050 case CXCursor_ObjCImplementationDecl:
5051 return cxstring::createRef("ObjCImplementationDecl");
5052 case CXCursor_ObjCCategoryImplDecl:
5053 return cxstring::createRef("ObjCCategoryImplDecl");
5054 case CXCursor_CXXMethod:
5055 return cxstring::createRef("CXXMethod");
5056 case CXCursor_UnexposedDecl:
5057 return cxstring::createRef("UnexposedDecl");
5058 case CXCursor_ObjCSuperClassRef:
5059 return cxstring::createRef("ObjCSuperClassRef");
5060 case CXCursor_ObjCProtocolRef:
5061 return cxstring::createRef("ObjCProtocolRef");
5062 case CXCursor_ObjCClassRef:
5063 return cxstring::createRef("ObjCClassRef");
5064 case CXCursor_TypeRef:
5065 return cxstring::createRef("TypeRef");
5066 case CXCursor_TemplateRef:
5067 return cxstring::createRef("TemplateRef");
5068 case CXCursor_NamespaceRef:
5069 return cxstring::createRef("NamespaceRef");
5070 case CXCursor_MemberRef:
5071 return cxstring::createRef("MemberRef");
5072 case CXCursor_LabelRef:
5073 return cxstring::createRef("LabelRef");
5074 case CXCursor_OverloadedDeclRef:
5075 return cxstring::createRef("OverloadedDeclRef");
5076 case CXCursor_VariableRef:
5077 return cxstring::createRef("VariableRef");
5078 case CXCursor_IntegerLiteral:
5079 return cxstring::createRef("IntegerLiteral");
5080 case CXCursor_FixedPointLiteral:
5081 return cxstring::createRef("FixedPointLiteral");
5082 case CXCursor_FloatingLiteral:
5083 return cxstring::createRef("FloatingLiteral");
5084 case CXCursor_ImaginaryLiteral:
5085 return cxstring::createRef("ImaginaryLiteral");
5086 case CXCursor_StringLiteral:
5087 return cxstring::createRef("StringLiteral");
5088 case CXCursor_CharacterLiteral:
5089 return cxstring::createRef("CharacterLiteral");
5090 case CXCursor_ParenExpr:
5091 return cxstring::createRef("ParenExpr");
5092 case CXCursor_UnaryOperator:
5093 return cxstring::createRef("UnaryOperator");
5094 case CXCursor_ArraySubscriptExpr:
5095 return cxstring::createRef("ArraySubscriptExpr");
5096 case CXCursor_OMPArraySectionExpr:
5097 return cxstring::createRef("OMPArraySectionExpr");
5098 case CXCursor_BinaryOperator:
5099 return cxstring::createRef("BinaryOperator");
5100 case CXCursor_CompoundAssignOperator:
5101 return cxstring::createRef("CompoundAssignOperator");
5102 case CXCursor_ConditionalOperator:
5103 return cxstring::createRef("ConditionalOperator");
5104 case CXCursor_CStyleCastExpr:
5105 return cxstring::createRef("CStyleCastExpr");
5106 case CXCursor_CompoundLiteralExpr:
5107 return cxstring::createRef("CompoundLiteralExpr");
5108 case CXCursor_InitListExpr:
5109 return cxstring::createRef("InitListExpr");
5110 case CXCursor_AddrLabelExpr:
5111 return cxstring::createRef("AddrLabelExpr");
5112 case CXCursor_StmtExpr:
5113 return cxstring::createRef("StmtExpr");
5114 case CXCursor_GenericSelectionExpr:
5115 return cxstring::createRef("GenericSelectionExpr");
5116 case CXCursor_GNUNullExpr:
5117 return cxstring::createRef("GNUNullExpr");
5118 case CXCursor_CXXStaticCastExpr:
5119 return cxstring::createRef("CXXStaticCastExpr");
5120 case CXCursor_CXXDynamicCastExpr:
5121 return cxstring::createRef("CXXDynamicCastExpr");
5122 case CXCursor_CXXReinterpretCastExpr:
5123 return cxstring::createRef("CXXReinterpretCastExpr");
5124 case CXCursor_CXXConstCastExpr:
5125 return cxstring::createRef("CXXConstCastExpr");
5126 case CXCursor_CXXFunctionalCastExpr:
5127 return cxstring::createRef("CXXFunctionalCastExpr");
5128 case CXCursor_CXXTypeidExpr:
5129 return cxstring::createRef("CXXTypeidExpr");
5130 case CXCursor_CXXBoolLiteralExpr:
5131 return cxstring::createRef("CXXBoolLiteralExpr");
5132 case CXCursor_CXXNullPtrLiteralExpr:
5133 return cxstring::createRef("CXXNullPtrLiteralExpr");
5134 case CXCursor_CXXThisExpr:
5135 return cxstring::createRef("CXXThisExpr");
5136 case CXCursor_CXXThrowExpr:
5137 return cxstring::createRef("CXXThrowExpr");
5138 case CXCursor_CXXNewExpr:
5139 return cxstring::createRef("CXXNewExpr");
5140 case CXCursor_CXXDeleteExpr:
5141 return cxstring::createRef("CXXDeleteExpr");
5142 case CXCursor_UnaryExpr:
5143 return cxstring::createRef("UnaryExpr");
5144 case CXCursor_ObjCStringLiteral:
5145 return cxstring::createRef("ObjCStringLiteral");
5146 case CXCursor_ObjCBoolLiteralExpr:
5147 return cxstring::createRef("ObjCBoolLiteralExpr");
5148 case CXCursor_ObjCAvailabilityCheckExpr:
5149 return cxstring::createRef("ObjCAvailabilityCheckExpr");
5150 case CXCursor_ObjCSelfExpr:
5151 return cxstring::createRef("ObjCSelfExpr");
5152 case CXCursor_ObjCEncodeExpr:
5153 return cxstring::createRef("ObjCEncodeExpr");
5154 case CXCursor_ObjCSelectorExpr:
5155 return cxstring::createRef("ObjCSelectorExpr");
5156 case CXCursor_ObjCProtocolExpr:
5157 return cxstring::createRef("ObjCProtocolExpr");
5158 case CXCursor_ObjCBridgedCastExpr:
5159 return cxstring::createRef("ObjCBridgedCastExpr");
5160 case CXCursor_BlockExpr:
5161 return cxstring::createRef("BlockExpr");
5162 case CXCursor_PackExpansionExpr:
5163 return cxstring::createRef("PackExpansionExpr");
5164 case CXCursor_SizeOfPackExpr:
5165 return cxstring::createRef("SizeOfPackExpr");
5166 case CXCursor_LambdaExpr:
5167 return cxstring::createRef("LambdaExpr");
5168 case CXCursor_UnexposedExpr:
5169 return cxstring::createRef("UnexposedExpr");
5170 case CXCursor_DeclRefExpr:
5171 return cxstring::createRef("DeclRefExpr");
5172 case CXCursor_MemberRefExpr:
5173 return cxstring::createRef("MemberRefExpr");
5174 case CXCursor_CallExpr:
5175 return cxstring::createRef("CallExpr");
5176 case CXCursor_ObjCMessageExpr:
5177 return cxstring::createRef("ObjCMessageExpr");
5178 case CXCursor_UnexposedStmt:
5179 return cxstring::createRef("UnexposedStmt");
5180 case CXCursor_DeclStmt:
5181 return cxstring::createRef("DeclStmt");
5182 case CXCursor_LabelStmt:
5183 return cxstring::createRef("LabelStmt");
5184 case CXCursor_CompoundStmt:
5185 return cxstring::createRef("CompoundStmt");
5186 case CXCursor_CaseStmt:
5187 return cxstring::createRef("CaseStmt");
5188 case CXCursor_DefaultStmt:
5189 return cxstring::createRef("DefaultStmt");
5190 case CXCursor_IfStmt:
5191 return cxstring::createRef("IfStmt");
5192 case CXCursor_SwitchStmt:
5193 return cxstring::createRef("SwitchStmt");
5194 case CXCursor_WhileStmt:
5195 return cxstring::createRef("WhileStmt");
5196 case CXCursor_DoStmt:
5197 return cxstring::createRef("DoStmt");
5198 case CXCursor_ForStmt:
5199 return cxstring::createRef("ForStmt");
5200 case CXCursor_GotoStmt:
5201 return cxstring::createRef("GotoStmt");
5202 case CXCursor_IndirectGotoStmt:
5203 return cxstring::createRef("IndirectGotoStmt");
5204 case CXCursor_ContinueStmt:
5205 return cxstring::createRef("ContinueStmt");
5206 case CXCursor_BreakStmt:
5207 return cxstring::createRef("BreakStmt");
5208 case CXCursor_ReturnStmt:
5209 return cxstring::createRef("ReturnStmt");
5210 case CXCursor_GCCAsmStmt:
5211 return cxstring::createRef("GCCAsmStmt");
5212 case CXCursor_MSAsmStmt:
5213 return cxstring::createRef("MSAsmStmt");
5214 case CXCursor_ObjCAtTryStmt:
5215 return cxstring::createRef("ObjCAtTryStmt");
5216 case CXCursor_ObjCAtCatchStmt:
5217 return cxstring::createRef("ObjCAtCatchStmt");
5218 case CXCursor_ObjCAtFinallyStmt:
5219 return cxstring::createRef("ObjCAtFinallyStmt");
5220 case CXCursor_ObjCAtThrowStmt:
5221 return cxstring::createRef("ObjCAtThrowStmt");
5222 case CXCursor_ObjCAtSynchronizedStmt:
5223 return cxstring::createRef("ObjCAtSynchronizedStmt");
5224 case CXCursor_ObjCAutoreleasePoolStmt:
5225 return cxstring::createRef("ObjCAutoreleasePoolStmt");
5226 case CXCursor_ObjCForCollectionStmt:
5227 return cxstring::createRef("ObjCForCollectionStmt");
5228 case CXCursor_CXXCatchStmt:
5229 return cxstring::createRef("CXXCatchStmt");
5230 case CXCursor_CXXTryStmt:
5231 return cxstring::createRef("CXXTryStmt");
5232 case CXCursor_CXXForRangeStmt:
5233 return cxstring::createRef("CXXForRangeStmt");
5234 case CXCursor_SEHTryStmt:
5235 return cxstring::createRef("SEHTryStmt");
5236 case CXCursor_SEHExceptStmt:
5237 return cxstring::createRef("SEHExceptStmt");
5238 case CXCursor_SEHFinallyStmt:
5239 return cxstring::createRef("SEHFinallyStmt");
5240 case CXCursor_SEHLeaveStmt:
5241 return cxstring::createRef("SEHLeaveStmt");
5242 case CXCursor_NullStmt:
5243 return cxstring::createRef("NullStmt");
5244 case CXCursor_InvalidFile:
5245 return cxstring::createRef("InvalidFile");
5246 case CXCursor_InvalidCode:
5247 return cxstring::createRef("InvalidCode");
5248 case CXCursor_NoDeclFound:
5249 return cxstring::createRef("NoDeclFound");
5250 case CXCursor_NotImplemented:
5251 return cxstring::createRef("NotImplemented");
5252 case CXCursor_TranslationUnit:
5253 return cxstring::createRef("TranslationUnit");
5254 case CXCursor_UnexposedAttr:
5255 return cxstring::createRef("UnexposedAttr");
5256 case CXCursor_IBActionAttr:
5257 return cxstring::createRef("attribute(ibaction)");
5258 case CXCursor_IBOutletAttr:
5259 return cxstring::createRef("attribute(iboutlet)");
5260 case CXCursor_IBOutletCollectionAttr:
5261 return cxstring::createRef("attribute(iboutletcollection)");
5262 case CXCursor_CXXFinalAttr:
5263 return cxstring::createRef("attribute(final)");
5264 case CXCursor_CXXOverrideAttr:
5265 return cxstring::createRef("attribute(override)");
5266 case CXCursor_AnnotateAttr:
5267 return cxstring::createRef("attribute(annotate)");
5268 case CXCursor_AsmLabelAttr:
5269 return cxstring::createRef("asm label");
5270 case CXCursor_PackedAttr:
5271 return cxstring::createRef("attribute(packed)");
5272 case CXCursor_PureAttr:
5273 return cxstring::createRef("attribute(pure)");
5274 case CXCursor_ConstAttr:
5275 return cxstring::createRef("attribute(const)");
5276 case CXCursor_NoDuplicateAttr:
5277 return cxstring::createRef("attribute(noduplicate)");
5278 case CXCursor_CUDAConstantAttr:
5279 return cxstring::createRef("attribute(constant)");
5280 case CXCursor_CUDADeviceAttr:
5281 return cxstring::createRef("attribute(device)");
5282 case CXCursor_CUDAGlobalAttr:
5283 return cxstring::createRef("attribute(global)");
5284 case CXCursor_CUDAHostAttr:
5285 return cxstring::createRef("attribute(host)");
5286 case CXCursor_CUDASharedAttr:
5287 return cxstring::createRef("attribute(shared)");
5288 case CXCursor_VisibilityAttr:
5289 return cxstring::createRef("attribute(visibility)");
5290 case CXCursor_DLLExport:
5291 return cxstring::createRef("attribute(dllexport)");
5292 case CXCursor_DLLImport:
5293 return cxstring::createRef("attribute(dllimport)");
5294 case CXCursor_NSReturnsRetained:
5295 return cxstring::createRef("attribute(ns_returns_retained)");
5296 case CXCursor_NSReturnsNotRetained:
5297 return cxstring::createRef("attribute(ns_returns_not_retained)");
5298 case CXCursor_NSReturnsAutoreleased:
5299 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5300 case CXCursor_NSConsumesSelf:
5301 return cxstring::createRef("attribute(ns_consumes_self)");
5302 case CXCursor_NSConsumed:
5303 return cxstring::createRef("attribute(ns_consumed)");
5304 case CXCursor_ObjCException:
5305 return cxstring::createRef("attribute(objc_exception)");
5306 case CXCursor_ObjCNSObject:
5307 return cxstring::createRef("attribute(NSObject)");
5308 case CXCursor_ObjCIndependentClass:
5309 return cxstring::createRef("attribute(objc_independent_class)");
5310 case CXCursor_ObjCPreciseLifetime:
5311 return cxstring::createRef("attribute(objc_precise_lifetime)");
5312 case CXCursor_ObjCReturnsInnerPointer:
5313 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5314 case CXCursor_ObjCRequiresSuper:
5315 return cxstring::createRef("attribute(objc_requires_super)");
5316 case CXCursor_ObjCRootClass:
5317 return cxstring::createRef("attribute(objc_root_class)");
5318 case CXCursor_ObjCSubclassingRestricted:
5319 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5320 case CXCursor_ObjCExplicitProtocolImpl:
5321 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5322 case CXCursor_ObjCDesignatedInitializer:
5323 return cxstring::createRef("attribute(objc_designated_initializer)");
5324 case CXCursor_ObjCRuntimeVisible:
5325 return cxstring::createRef("attribute(objc_runtime_visible)");
5326 case CXCursor_ObjCBoxable:
5327 return cxstring::createRef("attribute(objc_boxable)");
5328 case CXCursor_FlagEnum:
5329 return cxstring::createRef("attribute(flag_enum)");
5330 case CXCursor_PreprocessingDirective:
5331 return cxstring::createRef("preprocessing directive");
5332 case CXCursor_MacroDefinition:
5333 return cxstring::createRef("macro definition");
5334 case CXCursor_MacroExpansion:
5335 return cxstring::createRef("macro expansion");
5336 case CXCursor_InclusionDirective:
5337 return cxstring::createRef("inclusion directive");
5338 case CXCursor_Namespace:
5339 return cxstring::createRef("Namespace");
5340 case CXCursor_LinkageSpec:
5341 return cxstring::createRef("LinkageSpec");
5342 case CXCursor_CXXBaseSpecifier:
5343 return cxstring::createRef("C++ base class specifier");
5344 case CXCursor_Constructor:
5345 return cxstring::createRef("CXXConstructor");
5346 case CXCursor_Destructor:
5347 return cxstring::createRef("CXXDestructor");
5348 case CXCursor_ConversionFunction:
5349 return cxstring::createRef("CXXConversion");
5350 case CXCursor_TemplateTypeParameter:
5351 return cxstring::createRef("TemplateTypeParameter");
5352 case CXCursor_NonTypeTemplateParameter:
5353 return cxstring::createRef("NonTypeTemplateParameter");
5354 case CXCursor_TemplateTemplateParameter:
5355 return cxstring::createRef("TemplateTemplateParameter");
5356 case CXCursor_FunctionTemplate:
5357 return cxstring::createRef("FunctionTemplate");
5358 case CXCursor_ClassTemplate:
5359 return cxstring::createRef("ClassTemplate");
5360 case CXCursor_ClassTemplatePartialSpecialization:
5361 return cxstring::createRef("ClassTemplatePartialSpecialization");
5362 case CXCursor_NamespaceAlias:
5363 return cxstring::createRef("NamespaceAlias");
5364 case CXCursor_UsingDirective:
5365 return cxstring::createRef("UsingDirective");
5366 case CXCursor_UsingDeclaration:
5367 return cxstring::createRef("UsingDeclaration");
5368 case CXCursor_TypeAliasDecl:
5369 return cxstring::createRef("TypeAliasDecl");
5370 case CXCursor_ObjCSynthesizeDecl:
5371 return cxstring::createRef("ObjCSynthesizeDecl");
5372 case CXCursor_ObjCDynamicDecl:
5373 return cxstring::createRef("ObjCDynamicDecl");
5374 case CXCursor_CXXAccessSpecifier:
5375 return cxstring::createRef("CXXAccessSpecifier");
5376 case CXCursor_ModuleImportDecl:
5377 return cxstring::createRef("ModuleImport");
5378 case CXCursor_OMPParallelDirective:
5379 return cxstring::createRef("OMPParallelDirective");
5380 case CXCursor_OMPSimdDirective:
5381 return cxstring::createRef("OMPSimdDirective");
5382 case CXCursor_OMPForDirective:
5383 return cxstring::createRef("OMPForDirective");
5384 case CXCursor_OMPForSimdDirective:
5385 return cxstring::createRef("OMPForSimdDirective");
5386 case CXCursor_OMPSectionsDirective:
5387 return cxstring::createRef("OMPSectionsDirective");
5388 case CXCursor_OMPSectionDirective:
5389 return cxstring::createRef("OMPSectionDirective");
5390 case CXCursor_OMPSingleDirective:
5391 return cxstring::createRef("OMPSingleDirective");
5392 case CXCursor_OMPMasterDirective:
5393 return cxstring::createRef("OMPMasterDirective");
5394 case CXCursor_OMPCriticalDirective:
5395 return cxstring::createRef("OMPCriticalDirective");
5396 case CXCursor_OMPParallelForDirective:
5397 return cxstring::createRef("OMPParallelForDirective");
5398 case CXCursor_OMPParallelForSimdDirective:
5399 return cxstring::createRef("OMPParallelForSimdDirective");
5400 case CXCursor_OMPParallelSectionsDirective:
5401 return cxstring::createRef("OMPParallelSectionsDirective");
5402 case CXCursor_OMPTaskDirective:
5403 return cxstring::createRef("OMPTaskDirective");
5404 case CXCursor_OMPTaskyieldDirective:
5405 return cxstring::createRef("OMPTaskyieldDirective");
5406 case CXCursor_OMPBarrierDirective:
5407 return cxstring::createRef("OMPBarrierDirective");
5408 case CXCursor_OMPTaskwaitDirective:
5409 return cxstring::createRef("OMPTaskwaitDirective");
5410 case CXCursor_OMPTaskgroupDirective:
5411 return cxstring::createRef("OMPTaskgroupDirective");
5412 case CXCursor_OMPFlushDirective:
5413 return cxstring::createRef("OMPFlushDirective");
5414 case CXCursor_OMPOrderedDirective:
5415 return cxstring::createRef("OMPOrderedDirective");
5416 case CXCursor_OMPAtomicDirective:
5417 return cxstring::createRef("OMPAtomicDirective");
5418 case CXCursor_OMPTargetDirective:
5419 return cxstring::createRef("OMPTargetDirective");
5420 case CXCursor_OMPTargetDataDirective:
5421 return cxstring::createRef("OMPTargetDataDirective");
5422 case CXCursor_OMPTargetEnterDataDirective:
5423 return cxstring::createRef("OMPTargetEnterDataDirective");
5424 case CXCursor_OMPTargetExitDataDirective:
5425 return cxstring::createRef("OMPTargetExitDataDirective");
5426 case CXCursor_OMPTargetParallelDirective:
5427 return cxstring::createRef("OMPTargetParallelDirective");
5428 case CXCursor_OMPTargetParallelForDirective:
5429 return cxstring::createRef("OMPTargetParallelForDirective");
5430 case CXCursor_OMPTargetUpdateDirective:
5431 return cxstring::createRef("OMPTargetUpdateDirective");
5432 case CXCursor_OMPTeamsDirective:
5433 return cxstring::createRef("OMPTeamsDirective");
5434 case CXCursor_OMPCancellationPointDirective:
5435 return cxstring::createRef("OMPCancellationPointDirective");
5436 case CXCursor_OMPCancelDirective:
5437 return cxstring::createRef("OMPCancelDirective");
5438 case CXCursor_OMPTaskLoopDirective:
5439 return cxstring::createRef("OMPTaskLoopDirective");
5440 case CXCursor_OMPTaskLoopSimdDirective:
5441 return cxstring::createRef("OMPTaskLoopSimdDirective");
5442 case CXCursor_OMPDistributeDirective:
5443 return cxstring::createRef("OMPDistributeDirective");
5444 case CXCursor_OMPDistributeParallelForDirective:
5445 return cxstring::createRef("OMPDistributeParallelForDirective");
5446 case CXCursor_OMPDistributeParallelForSimdDirective:
5447 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
5448 case CXCursor_OMPDistributeSimdDirective:
5449 return cxstring::createRef("OMPDistributeSimdDirective");
5450 case CXCursor_OMPTargetParallelForSimdDirective:
5451 return cxstring::createRef("OMPTargetParallelForSimdDirective");
5452 case CXCursor_OMPTargetSimdDirective:
5453 return cxstring::createRef("OMPTargetSimdDirective");
5454 case CXCursor_OMPTeamsDistributeDirective:
5455 return cxstring::createRef("OMPTeamsDistributeDirective");
5456 case CXCursor_OMPTeamsDistributeSimdDirective:
5457 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
5458 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5459 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
5460 case CXCursor_OMPTeamsDistributeParallelForDirective:
5461 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
5462 case CXCursor_OMPTargetTeamsDirective:
5463 return cxstring::createRef("OMPTargetTeamsDirective");
5464 case CXCursor_OMPTargetTeamsDistributeDirective:
5465 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
5466 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5467 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
5468 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5469 return cxstring::createRef(
5470 "OMPTargetTeamsDistributeParallelForSimdDirective");
5471 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5472 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
5473 case CXCursor_OverloadCandidate:
5474 return cxstring::createRef("OverloadCandidate");
5475 case CXCursor_TypeAliasTemplateDecl:
5476 return cxstring::createRef("TypeAliasTemplateDecl");
5477 case CXCursor_StaticAssert:
5478 return cxstring::createRef("StaticAssert");
5479 case CXCursor_FriendDecl:
5480 return cxstring::createRef("FriendDecl");
5481 }
5482
5483 llvm_unreachable("Unhandled CXCursorKind")::llvm::llvm_unreachable_internal("Unhandled CXCursorKind", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 5483)
;
5484}
5485
5486struct GetCursorData {
5487 SourceLocation TokenBeginLoc;
5488 bool PointsAtMacroArgExpansion;
5489 bool VisitedObjCPropertyImplDecl;
5490 SourceLocation VisitedDeclaratorDeclStartLoc;
5491 CXCursor &BestCursor;
5492
5493 GetCursorData(SourceManager &SM,
5494 SourceLocation tokenBegin, CXCursor &outputCursor)
5495 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5496 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5497 VisitedObjCPropertyImplDecl = false;
5498 }
5499};
5500
5501static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5502 CXCursor parent,
5503 CXClientData client_data) {
5504 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5505 CXCursor *BestCursor = &Data->BestCursor;
5506
5507 // If we point inside a macro argument we should provide info of what the
5508 // token is so use the actual cursor, don't replace it with a macro expansion
5509 // cursor.
5510 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5511 return CXChildVisit_Recurse;
5512
5513 if (clang_isDeclaration(cursor.kind)) {
5514 // Avoid having the implicit methods override the property decls.
5515 if (const ObjCMethodDecl *MD
5516 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5517 if (MD->isImplicit())
5518 return CXChildVisit_Break;
5519
5520 } else if (const ObjCInterfaceDecl *ID
5521 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5522 // Check that when we have multiple @class references in the same line,
5523 // that later ones do not override the previous ones.
5524 // If we have:
5525 // @class Foo, Bar;
5526 // source ranges for both start at '@', so 'Bar' will end up overriding
5527 // 'Foo' even though the cursor location was at 'Foo'.
5528 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5529 BestCursor->kind == CXCursor_ObjCClassRef)
5530 if (const ObjCInterfaceDecl *PrevID
5531 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5532 if (PrevID != ID &&
5533 !PrevID->isThisDeclarationADefinition() &&
5534 !ID->isThisDeclarationADefinition())
5535 return CXChildVisit_Break;
5536 }
5537
5538 } else if (const DeclaratorDecl *DD
5539 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5540 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5541 // Check that when we have multiple declarators in the same line,
5542 // that later ones do not override the previous ones.
5543 // If we have:
5544 // int Foo, Bar;
5545 // source ranges for both start at 'int', so 'Bar' will end up overriding
5546 // 'Foo' even though the cursor location was at 'Foo'.
5547 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5548 return CXChildVisit_Break;
5549 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5550
5551 } else if (const ObjCPropertyImplDecl *PropImp
5552 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5553 (void)PropImp;
5554 // Check that when we have multiple @synthesize in the same line,
5555 // that later ones do not override the previous ones.
5556 // If we have:
5557 // @synthesize Foo, Bar;
5558 // source ranges for both start at '@', so 'Bar' will end up overriding
5559 // 'Foo' even though the cursor location was at 'Foo'.
5560 if (Data->VisitedObjCPropertyImplDecl)
5561 return CXChildVisit_Break;
5562 Data->VisitedObjCPropertyImplDecl = true;
5563 }
5564 }
5565
5566 if (clang_isExpression(cursor.kind) &&
5567 clang_isDeclaration(BestCursor->kind)) {
5568 if (const Decl *D = getCursorDecl(*BestCursor)) {
5569 // Avoid having the cursor of an expression replace the declaration cursor
5570 // when the expression source range overlaps the declaration range.
5571 // This can happen for C++ constructor expressions whose range generally
5572 // include the variable declaration, e.g.:
5573 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5574 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5575 D->getLocation() == Data->TokenBeginLoc)
5576 return CXChildVisit_Break;
5577 }
5578 }
5579
5580 // If our current best cursor is the construction of a temporary object,
5581 // don't replace that cursor with a type reference, because we want
5582 // clang_getCursor() to point at the constructor.
5583 if (clang_isExpression(BestCursor->kind) &&
5584 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5585 cursor.kind == CXCursor_TypeRef) {
5586 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5587 // as having the actual point on the type reference.
5588 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5589 return CXChildVisit_Recurse;
5590 }
5591
5592 // If we already have an Objective-C superclass reference, don't
5593 // update it further.
5594 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5595 return CXChildVisit_Break;
5596
5597 *BestCursor = cursor;
5598 return CXChildVisit_Recurse;
5599}
5600
5601CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
5602 if (isNotUsableTU(TU)) {
5603 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
5604 return clang_getNullCursor();
5605 }
5606
5607 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5608 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5609
5610 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5611 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5612
5613 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
5614 CXFile SearchFile;
5615 unsigned SearchLine, SearchColumn;
5616 CXFile ResultFile;
5617 unsigned ResultLine, ResultColumn;
5618 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5619 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5620 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
5621
5622 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5623 nullptr);
5624 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
5625 &ResultColumn, nullptr);
5626 SearchFileName = clang_getFileName(SearchFile);
5627 ResultFileName = clang_getFileName(ResultFile);
5628 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5629 USR = clang_getCursorUSR(Result);
5630 *Log << llvm::format("(%s:%d:%d) = %s",
5631 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5632 clang_getCString(KindSpelling))
5633 << llvm::format("(%s:%d:%d):%s%s",
5634 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5635 clang_getCString(USR), IsDef);
5636 clang_disposeString(SearchFileName);
5637 clang_disposeString(ResultFileName);
5638 clang_disposeString(KindSpelling);
5639 clang_disposeString(USR);
5640
5641 CXCursor Definition = clang_getCursorDefinition(Result);
5642 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5643 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5644 CXString DefinitionKindSpelling
5645 = clang_getCursorKindSpelling(Definition.kind);
5646 CXFile DefinitionFile;
5647 unsigned DefinitionLine, DefinitionColumn;
5648 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
5649 &DefinitionLine, &DefinitionColumn, nullptr);
5650 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
5651 *Log << llvm::format(" -> %s(%s:%d:%d)",
5652 clang_getCString(DefinitionKindSpelling),
5653 clang_getCString(DefinitionFileName),
5654 DefinitionLine, DefinitionColumn);
5655 clang_disposeString(DefinitionFileName);
5656 clang_disposeString(DefinitionKindSpelling);
5657 }
5658 }
5659
5660 return Result;
5661}
5662
5663CXCursor clang_getNullCursor(void) {
5664 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5665}
5666
5667unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
5668 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5669 // can't set consistently. For example, when visiting a DeclStmt we will set
5670 // it but we don't set it on the result of clang_getCursorDefinition for
5671 // a reference of the same declaration.
5672 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5673 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5674 // to provide that kind of info.
5675 if (clang_isDeclaration(X.kind))
5676 X.data[1] = nullptr;
5677 if (clang_isDeclaration(Y.kind))
5678 Y.data[1] = nullptr;
5679
5680 return X == Y;
5681}
5682
5683unsigned clang_hashCursor(CXCursor C) {
5684 unsigned Index = 0;
5685 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5686 Index = 1;
5687
5688 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
5689 std::make_pair(C.kind, C.data[Index]));
5690}
5691
5692unsigned clang_isInvalid(enum CXCursorKind K) {
5693 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5694}
5695
5696unsigned clang_isDeclaration(enum CXCursorKind K) {
5697 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5698 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5699}
5700
5701unsigned clang_isInvalidDeclaration(CXCursor C) {
5702 if (clang_isDeclaration(C.kind)) {
5703 if (const Decl *D = getCursorDecl(C))
5704 return D->isInvalidDecl();
5705 }
5706
5707 return 0;
5708}
5709
5710unsigned clang_isReference(enum CXCursorKind K) {
5711 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5712}
5713
5714unsigned clang_isExpression(enum CXCursorKind K) {
5715 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5716}
5717
5718unsigned clang_isStatement(enum CXCursorKind K) {
5719 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5720}
5721
5722unsigned clang_isAttribute(enum CXCursorKind K) {
5723 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5724}
5725
5726unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5727 return K == CXCursor_TranslationUnit;
5728}
5729
5730unsigned clang_isPreprocessing(enum CXCursorKind K) {
5731 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5732}
5733
5734unsigned clang_isUnexposed(enum CXCursorKind K) {
5735 switch (K) {
5736 case CXCursor_UnexposedDecl:
5737 case CXCursor_UnexposedExpr:
5738 case CXCursor_UnexposedStmt:
5739 case CXCursor_UnexposedAttr:
5740 return true;
5741 default:
5742 return false;
5743 }
5744}
5745
5746CXCursorKind clang_getCursorKind(CXCursor C) {
5747 return C.kind;
5748}
5749
5750CXSourceLocation clang_getCursorLocation(CXCursor C) {
5751 if (clang_isReference(C.kind)) {
5752 switch (C.kind) {
5753 case CXCursor_ObjCSuperClassRef: {
5754 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
5755 = getCursorObjCSuperClassRef(C);
5756 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5757 }
5758
5759 case CXCursor_ObjCProtocolRef: {
5760 std::pair<const ObjCProtocolDecl *, SourceLocation> P
5761 = getCursorObjCProtocolRef(C);
5762 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5763 }
5764
5765 case CXCursor_ObjCClassRef: {
5766 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
5767 = getCursorObjCClassRef(C);
5768 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5769 }
5770
5771 case CXCursor_TypeRef: {
5772 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
5773 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5774 }
5775
5776 case CXCursor_TemplateRef: {
5777 std::pair<const TemplateDecl *, SourceLocation> P =
5778 getCursorTemplateRef(C);
5779 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5780 }
5781
5782 case CXCursor_NamespaceRef: {
5783 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
5784 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5785 }
5786
5787 case CXCursor_MemberRef: {
5788 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
5789 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5790 }
5791
5792 case CXCursor_VariableRef: {
5793 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
5794 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5795 }
5796
5797 case CXCursor_CXXBaseSpecifier: {
5798 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
5799 if (!BaseSpec)
5800 return clang_getNullLocation();
5801
5802 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5803 return cxloc::translateSourceLocation(getCursorContext(C),
5804 TSInfo->getTypeLoc().getBeginLoc());
5805
5806 return cxloc::translateSourceLocation(getCursorContext(C),
5807 BaseSpec->getBeginLoc());
5808 }
5809
5810 case CXCursor_LabelRef: {
5811 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
5812 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5813 }
5814
5815 case CXCursor_OverloadedDeclRef:
5816 return cxloc::translateSourceLocation(getCursorContext(C),
5817 getCursorOverloadedDeclRef(C).second);
5818
5819 default:
5820 // FIXME: Need a way to enumerate all non-reference cases.
5821 llvm_unreachable("Missed a reference kind")::llvm::llvm_unreachable_internal("Missed a reference kind", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 5821)
;
5822 }
5823 }
5824
5825 if (clang_isExpression(C.kind))
5826 return cxloc::translateSourceLocation(getCursorContext(C),
5827 getLocationFromExpr(getCursorExpr(C)));
5828
5829 if (clang_isStatement(C.kind))
5830 return cxloc::translateSourceLocation(getCursorContext(C),
5831 getCursorStmt(C)->getBeginLoc());
5832
5833 if (C.kind == CXCursor_PreprocessingDirective) {
5834 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5835 return cxloc::translateSourceLocation(getCursorContext(C), L);
5836 }
5837
5838 if (C.kind == CXCursor_MacroExpansion) {
5839 SourceLocation L
5840 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
5841 return cxloc::translateSourceLocation(getCursorContext(C), L);
5842 }
5843
5844 if (C.kind == CXCursor_MacroDefinition) {
5845 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5846 return cxloc::translateSourceLocation(getCursorContext(C), L);
5847 }
5848
5849 if (C.kind == CXCursor_InclusionDirective) {
5850 SourceLocation L
5851 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5852 return cxloc::translateSourceLocation(getCursorContext(C), L);
5853 }
5854
5855 if (clang_isAttribute(C.kind)) {
5856 SourceLocation L
5857 = cxcursor::getCursorAttr(C)->getLocation();
5858 return cxloc::translateSourceLocation(getCursorContext(C), L);
5859 }
5860
5861 if (!clang_isDeclaration(C.kind))
5862 return clang_getNullLocation();
5863
5864 const Decl *D = getCursorDecl(C);
5865 if (!D)
5866 return clang_getNullLocation();
5867
5868 SourceLocation Loc = D->getLocation();
5869 // FIXME: Multiple variables declared in a single declaration
5870 // currently lack the information needed to correctly determine their
5871 // ranges when accounting for the type-specifier. We use context
5872 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5873 // and if so, whether it is the first decl.
5874 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5875 if (!cxcursor::isFirstInDeclGroup(C))
5876 Loc = VD->getLocation();
5877 }
5878
5879 // For ObjC methods, give the start location of the method name.
5880 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
5881 Loc = MD->getSelectorStartLoc();
5882
5883 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5884}
5885
5886} // end extern "C"
5887
5888CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5889 assert(TU)((TU) ? static_cast<void> (0) : __assert_fail ("TU", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 5889, __PRETTY_FUNCTION__))
;
5890
5891 // Guard against an invalid SourceLocation, or we may assert in one
5892 // of the following calls.
5893 if (SLoc.isInvalid())
5894 return clang_getNullCursor();
5895
5896 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5897
5898 // Translate the given source location to make it point at the beginning of
5899 // the token under the cursor.
5900 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5901 CXXUnit->getASTContext().getLangOpts());
5902
5903 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5904 if (SLoc.isValid()) {
5905 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5906 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5907 /*VisitPreprocessorLast=*/true,
5908 /*VisitIncludedEntities=*/false,
5909 SourceLocation(SLoc));
5910 CursorVis.visitFileRegion();
5911 }
5912
5913 return Result;
5914}
5915
5916static SourceRange getRawCursorExtent(CXCursor C) {
5917 if (clang_isReference(C.kind)) {
5918 switch (C.kind) {
5919 case CXCursor_ObjCSuperClassRef:
5920 return getCursorObjCSuperClassRef(C).second;
5921
5922 case CXCursor_ObjCProtocolRef:
5923 return getCursorObjCProtocolRef(C).second;
5924
5925 case CXCursor_ObjCClassRef:
5926 return getCursorObjCClassRef(C).second;
5927
5928 case CXCursor_TypeRef:
5929 return getCursorTypeRef(C).second;
5930
5931 case CXCursor_TemplateRef:
5932 return getCursorTemplateRef(C).second;
5933
5934 case CXCursor_NamespaceRef:
5935 return getCursorNamespaceRef(C).second;
5936
5937 case CXCursor_MemberRef:
5938 return getCursorMemberRef(C).second;
5939
5940 case CXCursor_CXXBaseSpecifier:
5941 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5942
5943 case CXCursor_LabelRef:
5944 return getCursorLabelRef(C).second;
5945
5946 case CXCursor_OverloadedDeclRef:
5947 return getCursorOverloadedDeclRef(C).second;
5948
5949 case CXCursor_VariableRef:
5950 return getCursorVariableRef(C).second;
5951
5952 default:
5953 // FIXME: Need a way to enumerate all non-reference cases.
5954 llvm_unreachable("Missed a reference kind")::llvm::llvm_unreachable_internal("Missed a reference kind", "/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/tools/libclang/CIndex.cpp"
, 5954)
;
5955 }
5956 }
5957
5958 if (clang_isExpression(C.kind))
5959 return getCursorExpr(C)->getSourceRange();
5960
5961 if (clang_isStatement(C.kind))
5962 return getCursorStmt(C)->getSourceRange();
5963
5964 if (clang_isAttribute(C.kind))
5965 return getCursorAttr(C)->getRange();
5966
5967 if (C.kind == CXCursor_PreprocessingDirective)
5968 return cxcursor::getCursorPreprocessingDirective(C);
5969
5970 if (C.kind == CXCursor_MacroExpansion) {
5971 ASTUnit *TU = getCursorASTUnit(C);
5972 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
5973 return TU->mapRangeFromPreamble(Range);
5974 }
5975
5976 if (C.kind == CXCursor_MacroDefinition) {
5977 ASTUnit *TU = getCursorASTUnit(C);
5978 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5979 return TU->mapRangeFromPreamble(Range);
5980 }
5981
5982 if (C.kind == CXCursor_InclusionDirective) {
5983 ASTUnit *TU = getCursorASTUnit(C);
5984 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5985 return TU->mapRangeFromPreamble(Range);
5986 }
5987
5988 if (C.kind == CXCursor_TranslationUnit) {
5989 ASTUnit *TU = getCursorASTUnit(C);
5990 FileID MainID = TU->getSourceManager().getMainFileID();
5991 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5992 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5993 return SourceRange(Start, End);
5994 }
5995
5996 if (clang_isDeclaration(C.kind)) {
5997 const Decl *D = cxcursor::getCursorDecl(C);
5998 if (!D)
5999 return SourceRange();
6000
6001 SourceRange R = D->getSourceRange();
6002 // FIXME: Multiple variables declared in a single declaration
6003 // currently lack the information needed to correctly determine their
6004 // ranges when accounting for the type-specifier. We use context
6005 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6006 // and if so, whether it is the first decl.
6007 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6008 if (!cxcursor::isFirstInDeclGroup(C))
6009 R.setBegin(VD->getLocation());
6010 }
6011 return R;
6012 }
6013 return SourceRange();
6014}
6015
6016/// Retrieves the "raw" cursor extent, which is then extended to include
6017/// the decl-specifier-seq for declarations.
6018static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6019 if (clang_isDeclaration(C.kind)) {
6020 const Decl *D = cxcursor::getCursorDecl(C);
6021 if (!D)
6022 return SourceRange();
6023
6024 SourceRange R = D->getSourceRange();
6025
6026 // Adjust the start of the location for declarations preceded by
6027 // declaration specifiers.
6028 SourceLocation StartLoc;
6029 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6030 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
6031 StartLoc = TI->getTypeLoc().getBeginLoc();
6032 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
6033 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
6034 StartLoc = TI->getTypeLoc().getBeginLoc();
6035 }
6036
6037 if (StartLoc.isValid() && R.getBegin().isValid() &&
6038 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6039 R.setBegin(StartLoc);
6040
6041 // FIXME: Multiple variables declared in a single declaration
6042 // currently lack the information needed to correctly determine their
6043 // ranges when accounting for the type-specifier. We use context
6044 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6045 // and if so, whether it is the first decl.
6046 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6047 if (!cxcursor::isFirstInDeclGroup(C))
6048 R.setBegin(VD->getLocation());
6049 }
6050
6051 return R;
6052 }
6053
6054 return getRawCursorExtent(C);
6055}
6056
6057CXSourceRange clang_getCursorExtent(CXCursor C) {
6058 SourceRange R = getRawCursorExtent(C);
6059 if (R.isInvalid())
6060 return clang_getNullRange();
6061
6062 return cxloc::translateSourceRange(getCursorContext(C), R);
6063}
6064
6065CXCursor clang_getCursorReferenced(CXCursor C) {
6066 if (clang_isInvalid(C.kind))
6067 return clang_getNullCursor();
6068
6069 CXTranslationUnit tu = getCursorTU(C);
6070 if (clang_isDeclaration(C.kind)) {
6071 const Decl *D = getCursorDecl(C);
6072 if (!D)
6073 return clang_getNullCursor();
6074 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
6075 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
6076 if (const ObjCPropertyImplDecl *PropImpl =
6077 dyn_cast<ObjCPropertyImplDecl>(D))
6078 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6079 return MakeCXCursor(Property, tu);
6080
6081 return C;
6082 }
6083
6084 if (clang_isExpression(C.kind)) {
6085 const Expr *E = getCursorExpr(C);
6086 const Decl *D = getDeclFromExpr(E);
6087 if (D) {
6088 CXCursor declCursor = MakeCXCursor(D, tu);
6089 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6090 declCursor);
6091 return declCursor;
6092 }
6093
6094 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
6095 return MakeCursorOverloadedDeclRef(Ovl, tu);
6096
6097 return clang_getNullCursor();
6098 }
6099
6100 if (clang_isStatement(C.kind)) {
6101 const Stmt *S = getCursorStmt(C);
6102 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
6103 if (LabelDecl *label = Goto->getLabel())
6104 if (LabelStmt *labelS = label->getStmt())
6105 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6106
6107 return clang_getNullCursor();
6108 }
6109
6110 if (C.kind == CXCursor_MacroExpansion) {
6111 if (const MacroDefinitionRecord *Def =
6112 getCursorMacroExpansion(C).getDefinition())
6113 return MakeMacroDefinitionCursor(Def, tu);
6114 }
6115
6116 if (!clang_isReference(C.kind))
6117 return clang_getNullCursor();
6118
6119 switch (C.kind) {
6120 case CXCursor_ObjCSuperClassRef:
6121 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6122
6123 case CXCursor_ObjCProtocolRef: {
6124 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6125 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
6126 return MakeCXCursor(Def, tu);
6127
6128 return Ma