Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name CIndex.cpp -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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _CINDEX_LIB_ -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/tools/libclang -I /build/source/clang/tools/libclang -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1668078801 -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-11-10-135928-647445-1 -x c++ /build/source/clang/tools/libclang/CIndex.cpp

/build/source/clang/tools/libclang/CIndex.cpp

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