Bug Summary

File:build/source/clang/tools/libclang/CIndex.cpp
Warning:line 3933, column 3
Branch condition evaluates to a garbage value

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 -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 CLANG_REPOSITORY_STRING="++20221205100733+0d03ba62c55f-1~exp1~20221205220848.944" -D _CINDEX_LIB_ -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -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/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 1670278128 -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-12-06-005535-15974-1 -x c++ /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 std::nullopt;
608
609 switch (CompareRegionOfInterest(Range)) {
610 case RangeBefore:
611 // This declaration comes before the region of interest; skip it.
612 return std::nullopt;
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 DI_saved(DI_current, &I);
632 SaveAndRestore 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 std::nullopt;
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 std::nullopt;
680 if (!V.value())
681 return false;
682 if (Visit(Cursor, true))
683 return true;
684 return std::nullopt;
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::VisitOMPAtClause(const OMPAtClause *) {}
2447
2448void OMPClauseEnqueue::VisitOMPSeverityClause(const OMPSeverityClause *) {}
2449
2450void OMPClauseEnqueue::VisitOMPMessageClause(const OMPMessageClause *) {}
2451
2452void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2453 Visitor->AddStmt(C->getDevice());
2454}
2455
2456void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2457 VisitOMPClauseWithPreInit(C);
2458 Visitor->AddStmt(C->getNumTeams());
2459}
2460
2461void OMPClauseEnqueue::VisitOMPThreadLimitClause(
2462 const OMPThreadLimitClause *C) {
2463 VisitOMPClauseWithPreInit(C);
2464 Visitor->AddStmt(C->getThreadLimit());
2465}
2466
2467void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2468 Visitor->AddStmt(C->getPriority());
2469}
2470
2471void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2472 Visitor->AddStmt(C->getGrainsize());
2473}
2474
2475void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2476 Visitor->AddStmt(C->getNumTasks());
2477}
2478
2479void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2480 Visitor->AddStmt(C->getHint());
2481}
2482
2483template <typename T> void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2484 for (const auto *I : Node->varlists()) {
2485 Visitor->AddStmt(I);
2486 }
2487}
2488
2489void OMPClauseEnqueue::VisitOMPInclusiveClause(const OMPInclusiveClause *C) {
2490 VisitOMPClauseList(C);
2491}
2492void OMPClauseEnqueue::VisitOMPExclusiveClause(const OMPExclusiveClause *C) {
2493 VisitOMPClauseList(C);
2494}
2495void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2496 VisitOMPClauseList(C);
2497 Visitor->AddStmt(C->getAllocator());
2498}
2499void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2500 VisitOMPClauseList(C);
2501 for (const auto *E : C->private_copies()) {
2502 Visitor->AddStmt(E);
2503 }
2504}
2505void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2506 const OMPFirstprivateClause *C) {
2507 VisitOMPClauseList(C);
2508 VisitOMPClauseWithPreInit(C);
2509 for (const auto *E : C->private_copies()) {
2510 Visitor->AddStmt(E);
2511 }
2512 for (const auto *E : C->inits()) {
2513 Visitor->AddStmt(E);
2514 }
2515}
2516void OMPClauseEnqueue::VisitOMPLastprivateClause(
2517 const OMPLastprivateClause *C) {
2518 VisitOMPClauseList(C);
2519 VisitOMPClauseWithPostUpdate(C);
2520 for (auto *E : C->private_copies()) {
2521 Visitor->AddStmt(E);
2522 }
2523 for (auto *E : C->source_exprs()) {
2524 Visitor->AddStmt(E);
2525 }
2526 for (auto *E : C->destination_exprs()) {
2527 Visitor->AddStmt(E);
2528 }
2529 for (auto *E : C->assignment_ops()) {
2530 Visitor->AddStmt(E);
2531 }
2532}
2533void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2534 VisitOMPClauseList(C);
2535}
2536void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2537 VisitOMPClauseList(C);
2538 VisitOMPClauseWithPostUpdate(C);
2539 for (auto *E : C->privates()) {
2540 Visitor->AddStmt(E);
2541 }
2542 for (auto *E : C->lhs_exprs()) {
2543 Visitor->AddStmt(E);
2544 }
2545 for (auto *E : C->rhs_exprs()) {
2546 Visitor->AddStmt(E);
2547 }
2548 for (auto *E : C->reduction_ops()) {
2549 Visitor->AddStmt(E);
2550 }
2551 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
2552 for (auto *E : C->copy_ops()) {
2553 Visitor->AddStmt(E);
2554 }
2555 for (auto *E : C->copy_array_temps()) {
2556 Visitor->AddStmt(E);
2557 }
2558 for (auto *E : C->copy_array_elems()) {
2559 Visitor->AddStmt(E);
2560 }
2561 }
2562}
2563void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2564 const OMPTaskReductionClause *C) {
2565 VisitOMPClauseList(C);
2566 VisitOMPClauseWithPostUpdate(C);
2567 for (auto *E : C->privates()) {
2568 Visitor->AddStmt(E);
2569 }
2570 for (auto *E : C->lhs_exprs()) {
2571 Visitor->AddStmt(E);
2572 }
2573 for (auto *E : C->rhs_exprs()) {
2574 Visitor->AddStmt(E);
2575 }
2576 for (auto *E : C->reduction_ops()) {
2577 Visitor->AddStmt(E);
2578 }
2579}
2580void OMPClauseEnqueue::VisitOMPInReductionClause(
2581 const OMPInReductionClause *C) {
2582 VisitOMPClauseList(C);
2583 VisitOMPClauseWithPostUpdate(C);
2584 for (auto *E : C->privates()) {
2585 Visitor->AddStmt(E);
2586 }
2587 for (auto *E : C->lhs_exprs()) {
2588 Visitor->AddStmt(E);
2589 }
2590 for (auto *E : C->rhs_exprs()) {
2591 Visitor->AddStmt(E);
2592 }
2593 for (auto *E : C->reduction_ops()) {
2594 Visitor->AddStmt(E);
2595 }
2596 for (auto *E : C->taskgroup_descriptors())
2597 Visitor->AddStmt(E);
2598}
2599void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2600 VisitOMPClauseList(C);
2601 VisitOMPClauseWithPostUpdate(C);
2602 for (const auto *E : C->privates()) {
2603 Visitor->AddStmt(E);
2604 }
2605 for (const auto *E : C->inits()) {
2606 Visitor->AddStmt(E);
2607 }
2608 for (const auto *E : C->updates()) {
2609 Visitor->AddStmt(E);
2610 }
2611 for (const auto *E : C->finals()) {
2612 Visitor->AddStmt(E);
2613 }
2614 Visitor->AddStmt(C->getStep());
2615 Visitor->AddStmt(C->getCalcStep());
2616}
2617void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2618 VisitOMPClauseList(C);
2619 Visitor->AddStmt(C->getAlignment());
2620}
2621void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2622 VisitOMPClauseList(C);
2623 for (auto *E : C->source_exprs()) {
2624 Visitor->AddStmt(E);
2625 }
2626 for (auto *E : C->destination_exprs()) {
2627 Visitor->AddStmt(E);
2628 }
2629 for (auto *E : C->assignment_ops()) {
2630 Visitor->AddStmt(E);
2631 }
2632}
2633void OMPClauseEnqueue::VisitOMPCopyprivateClause(
2634 const OMPCopyprivateClause *C) {
2635 VisitOMPClauseList(C);
2636 for (auto *E : C->source_exprs()) {
2637 Visitor->AddStmt(E);
2638 }
2639 for (auto *E : C->destination_exprs()) {
2640 Visitor->AddStmt(E);
2641 }
2642 for (auto *E : C->assignment_ops()) {
2643 Visitor->AddStmt(E);
2644 }
2645}
2646void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2647 VisitOMPClauseList(C);
2648}
2649void OMPClauseEnqueue::VisitOMPDepobjClause(const OMPDepobjClause *C) {
2650 Visitor->AddStmt(C->getDepobj());
2651}
2652void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2653 VisitOMPClauseList(C);
2654}
2655void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2656 VisitOMPClauseList(C);
2657}
2658void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2659 const OMPDistScheduleClause *C) {
2660 VisitOMPClauseWithPreInit(C);
2661 Visitor->AddStmt(C->getChunkSize());
2662}
2663void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2664 const OMPDefaultmapClause * /*C*/) {}
2665void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2666 VisitOMPClauseList(C);
2667}
2668void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2669 VisitOMPClauseList(C);
2670}
2671void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(
2672 const OMPUseDevicePtrClause *C) {
2673 VisitOMPClauseList(C);
2674}
2675void OMPClauseEnqueue::VisitOMPUseDeviceAddrClause(
2676 const OMPUseDeviceAddrClause *C) {
2677 VisitOMPClauseList(C);
2678}
2679void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(
2680 const OMPIsDevicePtrClause *C) {
2681 VisitOMPClauseList(C);
2682}
2683void OMPClauseEnqueue::VisitOMPHasDeviceAddrClause(
2684 const OMPHasDeviceAddrClause *C) {
2685 VisitOMPClauseList(C);
2686}
2687void OMPClauseEnqueue::VisitOMPNontemporalClause(
2688 const OMPNontemporalClause *C) {
2689 VisitOMPClauseList(C);
2690 for (const auto *E : C->private_refs())
2691 Visitor->AddStmt(E);
2692}
2693void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
2694void OMPClauseEnqueue::VisitOMPUsesAllocatorsClause(
2695 const OMPUsesAllocatorsClause *C) {
2696 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
2697 const OMPUsesAllocatorsClause::Data &D = C->getAllocatorData(I);
2698 Visitor->AddStmt(D.Allocator);
2699 Visitor->AddStmt(D.AllocatorTraits);
2700 }
2701}
2702void OMPClauseEnqueue::VisitOMPAffinityClause(const OMPAffinityClause *C) {
2703 Visitor->AddStmt(C->getModifier());
2704 for (const Expr *E : C->varlists())
2705 Visitor->AddStmt(E);
2706}
2707void OMPClauseEnqueue::VisitOMPBindClause(const OMPBindClause *C) {}
2708
2709} // namespace
2710
2711void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2712 unsigned size = WL.size();
2713 OMPClauseEnqueue Visitor(this);
2714 Visitor.Visit(S);
2715 if (size == WL.size())
2716 return;
2717 // Now reverse the entries we just added. This will match the DFS
2718 // ordering performed by the worklist.
2719 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2720 std::reverse(I, E);
2721}
2722void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2723 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2724}
2725void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2726 AddDecl(B->getBlockDecl());
2727}
2728void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2729 EnqueueChildren(E);
2730 AddTypeLoc(E->getTypeSourceInfo());
2731}
2732void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2733 for (auto &I : llvm::reverse(S->body()))
2734 AddStmt(I);
2735}
2736void EnqueueVisitor::VisitMSDependentExistsStmt(
2737 const MSDependentExistsStmt *S) {
2738 AddStmt(S->getSubStmt());
2739 AddDeclarationNameInfo(S);
2740 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2741 AddNestedNameSpecifierLoc(QualifierLoc);
2742}
2743
2744void EnqueueVisitor::VisitCXXDependentScopeMemberExpr(
2745 const CXXDependentScopeMemberExpr *E) {
2746 if (E->hasExplicitTemplateArgs())
2747 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2748 AddDeclarationNameInfo(E);
2749 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2750 AddNestedNameSpecifierLoc(QualifierLoc);
2751 if (!E->isImplicitAccess())
2752 AddStmt(E->getBase());
2753}
2754void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2755 // Enqueue the initializer , if any.
2756 AddStmt(E->getInitializer());
2757 // Enqueue the array size, if any.
2758 AddStmt(E->getArraySize().value_or(nullptr));
2759 // Enqueue the allocated type.
2760 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2761 // Enqueue the placement arguments.
2762 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2763 AddStmt(E->getPlacementArg(I - 1));
2764}
2765void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2766 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2767 AddStmt(CE->getArg(I - 1));
2768 AddStmt(CE->getCallee());
2769 AddStmt(CE->getArg(0));
2770}
2771void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2772 const CXXPseudoDestructorExpr *E) {
2773 // Visit the name of the type being destroyed.
2774 AddTypeLoc(E->getDestroyedTypeInfo());
2775 // Visit the scope type that looks disturbingly like the nested-name-specifier
2776 // but isn't.
2777 AddTypeLoc(E->getScopeTypeInfo());
2778 // Visit the nested-name-specifier.
2779 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2780 AddNestedNameSpecifierLoc(QualifierLoc);
2781 // Visit base expression.
2782 AddStmt(E->getBase());
2783}
2784void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2785 const CXXScalarValueInitExpr *E) {
2786 AddTypeLoc(E->getTypeSourceInfo());
2787}
2788void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2789 const CXXTemporaryObjectExpr *E) {
2790 EnqueueChildren(E);
2791 AddTypeLoc(E->getTypeSourceInfo());
2792}
2793void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2794 EnqueueChildren(E);
2795 if (E->isTypeOperand())
2796 AddTypeLoc(E->getTypeOperandSourceInfo());
2797}
2798
2799void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2800 const CXXUnresolvedConstructExpr *E) {
2801 EnqueueChildren(E);
2802 AddTypeLoc(E->getTypeSourceInfo());
2803}
2804void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2805 EnqueueChildren(E);
2806 if (E->isTypeOperand())
2807 AddTypeLoc(E->getTypeOperandSourceInfo());
2808}
2809
2810void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2811 EnqueueChildren(S);
2812 AddDecl(S->getExceptionDecl());
2813}
2814
2815void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2816 AddStmt(S->getBody());
2817 AddStmt(S->getRangeInit());
2818 AddDecl(S->getLoopVariable());
2819}
2820
2821void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2822 if (DR->hasExplicitTemplateArgs())
2823 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
2824 WL.push_back(DeclRefExprParts(DR, Parent));
2825}
2826void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2827 const DependentScopeDeclRefExpr *E) {
2828 if (E->hasExplicitTemplateArgs())
2829 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2830 AddDeclarationNameInfo(E);
2831 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2832}
2833void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2834 unsigned size = WL.size();
2835 bool isFirst = true;
2836 for (const auto *D : S->decls()) {
2837 AddDecl(D, isFirst);
2838 isFirst = false;
2839 }
2840 if (size == WL.size())
2841 return;
2842 // Now reverse the entries we just added. This will match the DFS
2843 // ordering performed by the worklist.
2844 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2845 std::reverse(I, E);
2846}
2847void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2848 AddStmt(E->getInit());
2849 for (const DesignatedInitExpr::Designator &D :
2850 llvm::reverse(E->designators())) {
2851 if (D.isFieldDesignator()) {
2852 if (FieldDecl *Field = D.getField())
2853 AddMemberRef(Field, D.getFieldLoc());
2854 continue;
2855 }
2856 if (D.isArrayDesignator()) {
2857 AddStmt(E->getArrayIndex(D));
2858 continue;
2859 }
2860 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", 2860, __extension__ __PRETTY_FUNCTION__
))
;
2861 AddStmt(E->getArrayRangeEnd(D));
2862 AddStmt(E->getArrayRangeStart(D));
2863 }
2864}
2865void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2866 EnqueueChildren(E);
2867 AddTypeLoc(E->getTypeInfoAsWritten());
2868}
2869void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2870 AddStmt(FS->getBody());
2871 AddStmt(FS->getInc());
2872 AddStmt(FS->getCond());
2873 AddDecl(FS->getConditionVariable());
2874 AddStmt(FS->getInit());
2875}
2876void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2877 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2878}
2879void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2880 AddStmt(If->getElse());
2881 AddStmt(If->getThen());
2882 AddStmt(If->getCond());
2883 AddStmt(If->getInit());
2884 AddDecl(If->getConditionVariable());
2885}
2886void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2887 // We care about the syntactic form of the initializer list, only.
2888 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2889 IE = Syntactic;
2890 EnqueueChildren(IE);
2891}
2892void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2893 WL.push_back(MemberExprParts(M, Parent));
2894
2895 // If the base of the member access expression is an implicit 'this', don't
2896 // visit it.
2897 // FIXME: If we ever want to show these implicit accesses, this will be
2898 // unfortunate. However, clang_getCursor() relies on this behavior.
2899 if (M->isImplicitAccess())
2900 return;
2901
2902 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2903 // real field that we are interested in.
2904 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2905 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2906 if (FD->isAnonymousStructOrUnion()) {
2907 AddStmt(SubME->getBase());
2908 return;
2909 }
2910 }
2911 }
2912
2913 AddStmt(M->getBase());
2914}
2915void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2916 AddTypeLoc(E->getEncodedTypeSourceInfo());
2917}
2918void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2919 EnqueueChildren(M);
2920 AddTypeLoc(M->getClassReceiverTypeInfo());
2921}
2922void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2923 // Visit the components of the offsetof expression.
2924 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2925 const OffsetOfNode &Node = E->getComponent(I - 1);
2926 switch (Node.getKind()) {
2927 case OffsetOfNode::Array:
2928 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2929 break;
2930 case OffsetOfNode::Field:
2931 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2932 break;
2933 case OffsetOfNode::Identifier:
2934 case OffsetOfNode::Base:
2935 continue;
2936 }
2937 }
2938 // Visit the type into which we're computing the offset.
2939 AddTypeLoc(E->getTypeSourceInfo());
2940}
2941void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2942 if (E->hasExplicitTemplateArgs())
2943 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2944 WL.push_back(OverloadExprParts(E, Parent));
2945}
2946void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2947 const UnaryExprOrTypeTraitExpr *E) {
2948 EnqueueChildren(E);
2949 if (E->isArgumentType())
2950 AddTypeLoc(E->getArgumentTypeInfo());
2951}
2952void EnqueueVisitor::VisitStmt(const Stmt *S) { EnqueueChildren(S); }
2953void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2954 AddStmt(S->getBody());
2955 AddStmt(S->getCond());
2956 AddDecl(S->getConditionVariable());
2957}
2958
2959void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2960 AddStmt(W->getBody());
2961 AddStmt(W->getCond());
2962 AddDecl(W->getConditionVariable());
2963}
2964
2965void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2966 for (unsigned I = E->getNumArgs(); I > 0; --I)
2967 AddTypeLoc(E->getArg(I - 1));
2968}
2969
2970void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2971 AddTypeLoc(E->getQueriedTypeSourceInfo());
2972}
2973
2974void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2975 EnqueueChildren(E);
2976}
2977
2978void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2979 VisitOverloadExpr(U);
2980 if (!U->isImplicitAccess())
2981 AddStmt(U->getBase());
2982}
2983void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2984 AddStmt(E->getSubExpr());
2985 AddTypeLoc(E->getWrittenTypeInfo());
2986}
2987void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2988 WL.push_back(SizeOfPackExprParts(E, Parent));
2989}
2990void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2991 // If the opaque value has a source expression, just transparently
2992 // visit that. This is useful for (e.g.) pseudo-object expressions.
2993 if (Expr *SourceExpr = E->getSourceExpr())
2994 return Visit(SourceExpr);
2995}
2996void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2997 AddStmt(E->getBody());
2998 WL.push_back(LambdaExprParts(E, Parent));
2999}
3000void EnqueueVisitor::VisitConceptSpecializationExpr(
3001 const ConceptSpecializationExpr *E) {
3002 WL.push_back(ConceptSpecializationExprVisit(E, Parent));
3003}
3004void EnqueueVisitor::VisitRequiresExpr(const RequiresExpr *E) {
3005 WL.push_back(RequiresExprVisit(E, Parent));
3006 for (ParmVarDecl *VD : E->getLocalParameters())
3007 AddDecl(VD);
3008}
3009void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
3010 // Treat the expression like its syntactic form.
3011 Visit(E->getSyntacticForm());
3012}
3013
3014void EnqueueVisitor::VisitOMPExecutableDirective(
3015 const OMPExecutableDirective *D) {
3016 EnqueueChildren(D);
3017 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
3018 E = D->clauses().end();
3019 I != E; ++I)
3020 EnqueueChildren(*I);
3021}
3022
3023void EnqueueVisitor::VisitOMPLoopBasedDirective(
3024 const OMPLoopBasedDirective *D) {
3025 VisitOMPExecutableDirective(D);
3026}
3027
3028void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
3029 VisitOMPLoopBasedDirective(D);
3030}
3031
3032void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
3033 VisitOMPExecutableDirective(D);
3034}
3035
3036void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
3037 VisitOMPLoopDirective(D);
3038}
3039
3040void EnqueueVisitor::VisitOMPLoopTransformationDirective(
3041 const OMPLoopTransformationDirective *D) {
3042 VisitOMPLoopBasedDirective(D);
3043}
3044
3045void EnqueueVisitor::VisitOMPTileDirective(const OMPTileDirective *D) {
3046 VisitOMPLoopTransformationDirective(D);
3047}
3048
3049void EnqueueVisitor::VisitOMPUnrollDirective(const OMPUnrollDirective *D) {
3050 VisitOMPLoopTransformationDirective(D);
3051}
3052
3053void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
3054 VisitOMPLoopDirective(D);
3055}
3056
3057void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
3058 VisitOMPLoopDirective(D);
3059}
3060
3061void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
3062 VisitOMPExecutableDirective(D);
3063}
3064
3065void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
3066 VisitOMPExecutableDirective(D);
3067}
3068
3069void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
3070 VisitOMPExecutableDirective(D);
3071}
3072
3073void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
3074 VisitOMPExecutableDirective(D);
3075}
3076
3077void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
3078 VisitOMPExecutableDirective(D);
3079 AddDeclarationNameInfo(D);
3080}
3081
3082void EnqueueVisitor::VisitOMPParallelForDirective(
3083 const OMPParallelForDirective *D) {
3084 VisitOMPLoopDirective(D);
3085}
3086
3087void EnqueueVisitor::VisitOMPParallelForSimdDirective(
3088 const OMPParallelForSimdDirective *D) {
3089 VisitOMPLoopDirective(D);
3090}
3091
3092void EnqueueVisitor::VisitOMPParallelMasterDirective(
3093 const OMPParallelMasterDirective *D) {
3094 VisitOMPExecutableDirective(D);
3095}
3096
3097void EnqueueVisitor::VisitOMPParallelMaskedDirective(
3098 const OMPParallelMaskedDirective *D) {
3099 VisitOMPExecutableDirective(D);
3100}
3101
3102void EnqueueVisitor::VisitOMPParallelSectionsDirective(
3103 const OMPParallelSectionsDirective *D) {
3104 VisitOMPExecutableDirective(D);
3105}
3106
3107void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
3108 VisitOMPExecutableDirective(D);
3109}
3110
3111void EnqueueVisitor::VisitOMPTaskyieldDirective(
3112 const OMPTaskyieldDirective *D) {
3113 VisitOMPExecutableDirective(D);
3114}
3115
3116void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
3117 VisitOMPExecutableDirective(D);
3118}
3119
3120void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
3121 VisitOMPExecutableDirective(D);
3122}
3123
3124void EnqueueVisitor::VisitOMPErrorDirective(const OMPErrorDirective *D) {
3125 VisitOMPExecutableDirective(D);
3126}
3127
3128void EnqueueVisitor::VisitOMPTaskgroupDirective(
3129 const OMPTaskgroupDirective *D) {
3130 VisitOMPExecutableDirective(D);
3131 if (const Expr *E = D->getReductionRef())
3132 VisitStmt(E);
3133}
3134
3135void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
3136 VisitOMPExecutableDirective(D);
3137}
3138
3139void EnqueueVisitor::VisitOMPDepobjDirective(const OMPDepobjDirective *D) {
3140 VisitOMPExecutableDirective(D);
3141}
3142
3143void EnqueueVisitor::VisitOMPScanDirective(const OMPScanDirective *D) {
3144 VisitOMPExecutableDirective(D);
3145}
3146
3147void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
3148 VisitOMPExecutableDirective(D);
3149}
3150
3151void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
3152 VisitOMPExecutableDirective(D);
3153}
3154
3155void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
3156 VisitOMPExecutableDirective(D);
3157}
3158
3159void EnqueueVisitor::VisitOMPTargetDataDirective(
3160 const OMPTargetDataDirective *D) {
3161 VisitOMPExecutableDirective(D);
3162}
3163
3164void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
3165 const OMPTargetEnterDataDirective *D) {
3166 VisitOMPExecutableDirective(D);
3167}
3168
3169void EnqueueVisitor::VisitOMPTargetExitDataDirective(
3170 const OMPTargetExitDataDirective *D) {
3171 VisitOMPExecutableDirective(D);
3172}
3173
3174void EnqueueVisitor::VisitOMPTargetParallelDirective(
3175 const OMPTargetParallelDirective *D) {
3176 VisitOMPExecutableDirective(D);
3177}
3178
3179void EnqueueVisitor::VisitOMPTargetParallelForDirective(
3180 const OMPTargetParallelForDirective *D) {
3181 VisitOMPLoopDirective(D);
3182}
3183
3184void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
3185 VisitOMPExecutableDirective(D);
3186}
3187
3188void EnqueueVisitor::VisitOMPCancellationPointDirective(
3189 const OMPCancellationPointDirective *D) {
3190 VisitOMPExecutableDirective(D);
3191}
3192
3193void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
3194 VisitOMPExecutableDirective(D);
3195}
3196
3197void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
3198 VisitOMPLoopDirective(D);
3199}
3200
3201void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
3202 const OMPTaskLoopSimdDirective *D) {
3203 VisitOMPLoopDirective(D);
3204}
3205
3206void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
3207 const OMPMasterTaskLoopDirective *D) {
3208 VisitOMPLoopDirective(D);
3209}
3210
3211void EnqueueVisitor::VisitOMPMaskedTaskLoopDirective(
3212 const OMPMaskedTaskLoopDirective *D) {
3213 VisitOMPLoopDirective(D);
3214}
3215
3216void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
3217 const OMPMasterTaskLoopSimdDirective *D) {
3218 VisitOMPLoopDirective(D);
3219}
3220
3221void EnqueueVisitor::VisitOMPMaskedTaskLoopSimdDirective(
3222 const OMPMaskedTaskLoopSimdDirective *D) {
3223 VisitOMPLoopDirective(D);
3224}
3225
3226void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
3227 const OMPParallelMasterTaskLoopDirective *D) {
3228 VisitOMPLoopDirective(D);
3229}
3230
3231void EnqueueVisitor::VisitOMPParallelMaskedTaskLoopDirective(
3232 const OMPParallelMaskedTaskLoopDirective *D) {
3233 VisitOMPLoopDirective(D);
3234}
3235
3236void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
3237 const OMPParallelMasterTaskLoopSimdDirective *D) {
3238 VisitOMPLoopDirective(D);
3239}
3240
3241void EnqueueVisitor::VisitOMPParallelMaskedTaskLoopSimdDirective(
3242 const OMPParallelMaskedTaskLoopSimdDirective *D) {
3243 VisitOMPLoopDirective(D);
3244}
3245
3246void EnqueueVisitor::VisitOMPDistributeDirective(
3247 const OMPDistributeDirective *D) {
3248 VisitOMPLoopDirective(D);
3249}
3250
3251void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
3252 const OMPDistributeParallelForDirective *D) {
3253 VisitOMPLoopDirective(D);
3254}
3255
3256void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
3257 const OMPDistributeParallelForSimdDirective *D) {
3258 VisitOMPLoopDirective(D);
3259}
3260
3261void EnqueueVisitor::VisitOMPDistributeSimdDirective(
3262 const OMPDistributeSimdDirective *D) {
3263 VisitOMPLoopDirective(D);
3264}
3265
3266void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
3267 const OMPTargetParallelForSimdDirective *D) {
3268 VisitOMPLoopDirective(D);
3269}
3270
3271void EnqueueVisitor::VisitOMPTargetSimdDirective(
3272 const OMPTargetSimdDirective *D) {
3273 VisitOMPLoopDirective(D);
3274}
3275
3276void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
3277 const OMPTeamsDistributeDirective *D) {
3278 VisitOMPLoopDirective(D);
3279}
3280
3281void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
3282 const OMPTeamsDistributeSimdDirective *D) {
3283 VisitOMPLoopDirective(D);
3284}
3285
3286void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
3287 const OMPTeamsDistributeParallelForSimdDirective *D) {
3288 VisitOMPLoopDirective(D);
3289}
3290
3291void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
3292 const OMPTeamsDistributeParallelForDirective *D) {
3293 VisitOMPLoopDirective(D);
3294}
3295
3296void EnqueueVisitor::VisitOMPTargetTeamsDirective(
3297 const OMPTargetTeamsDirective *D) {
3298 VisitOMPExecutableDirective(D);
3299}
3300
3301void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
3302 const OMPTargetTeamsDistributeDirective *D) {
3303 VisitOMPLoopDirective(D);
3304}
3305
3306void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3307 const OMPTargetTeamsDistributeParallelForDirective *D) {
3308 VisitOMPLoopDirective(D);
3309}
3310
3311void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3312 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3313 VisitOMPLoopDirective(D);
3314}
3315
3316void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3317 const OMPTargetTeamsDistributeSimdDirective *D) {
3318 VisitOMPLoopDirective(D);
3319}
3320
3321void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
3322 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU, RegionOfInterest))
3323 .Visit(S);
3324}
3325
3326bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3327 if (RegionOfInterest.isValid()) {
3328 SourceRange Range = getRawCursorExtent(C);
3329 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3330 return false;
3331 }
3332 return true;
3333}
3334
3335bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3336 while (!WL.empty()) {
3337 // Dequeue the worklist item.
3338 VisitorJob LI = WL.pop_back_val();
3339
3340 // Set the Parent field, then back to its old value once we're done.
3341 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3342
3343 switch (LI.getKind()) {
3344 case VisitorJob::DeclVisitKind: {
3345 const Decl *D = cast<DeclVisit>(&LI)->get();
3346 if (!D)
3347 continue;
3348
3349 // For now, perform default visitation for Decls.
3350 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3351 cast<DeclVisit>(&LI)->isFirst())))
3352 return true;
3353
3354 continue;
3355 }
3356 case VisitorJob::ExplicitTemplateArgsVisitKind: {
3357 for (const TemplateArgumentLoc &Arg :
3358 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3359 if (VisitTemplateArgumentLoc(Arg))
3360 return true;
3361 }
3362 continue;
3363 }
3364 case VisitorJob::TypeLocVisitKind: {
3365 // Perform default visitation for TypeLocs.
3366 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3367 return true;
3368 continue;
3369 }
3370 case VisitorJob::LabelRefVisitKind: {
3371 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
3372 if (LabelStmt *stmt = LS->getStmt()) {
3373 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3374 TU))) {
3375 return true;
3376 }
3377 }
3378 continue;
3379 }
3380
3381 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3382 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3383 if (VisitNestedNameSpecifierLoc(V->get()))
3384 return true;
3385 continue;
3386 }
3387
3388 case VisitorJob::DeclarationNameInfoVisitKind: {
3389 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)->get()))
3390 return true;
3391 continue;
3392 }
3393 case VisitorJob::MemberRefVisitKind: {
3394 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3395 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3396 return true;
3397 continue;
3398 }
3399 case VisitorJob::StmtVisitKind: {
3400 const Stmt *S = cast<StmtVisit>(&LI)->get();
3401 if (!S)
3402 continue;
3403
3404 // Update the current cursor.
3405 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3406 if (!IsInRegionOfInterest(Cursor))
3407 continue;
3408 switch (Visitor(Cursor, Parent, ClientData)) {
3409 case CXChildVisit_Break:
3410 return true;
3411 case CXChildVisit_Continue:
3412 break;
3413 case CXChildVisit_Recurse:
3414 if (PostChildrenVisitor)
3415 WL.push_back(PostChildrenVisit(nullptr, Cursor));
3416 EnqueueWorkList(WL, S);
3417 break;
3418 }
3419 continue;
3420 }
3421 case VisitorJob::MemberExprPartsKind: {
3422 // Handle the other pieces in the MemberExpr besides the base.
3423 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
3424
3425 // Visit the nested-name-specifier
3426 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3427 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3428 return true;
3429
3430 // Visit the declaration name.
3431 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3432 return true;
3433
3434 // Visit the explicitly-specified template arguments, if any.
3435 if (M->hasExplicitTemplateArgs()) {
3436 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3437 *ArgEnd = Arg + M->getNumTemplateArgs();
3438 Arg != ArgEnd; ++Arg) {
3439 if (VisitTemplateArgumentLoc(*Arg))
3440 return true;
3441 }
3442 }
3443 continue;
3444 }
3445 case VisitorJob::DeclRefExprPartsKind: {
3446 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
3447 // Visit nested-name-specifier, if present.
3448 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3449 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3450 return true;
3451 // Visit declaration name.
3452 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3453 return true;
3454 continue;
3455 }
3456 case VisitorJob::OverloadExprPartsKind: {
3457 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
3458 // Visit the nested-name-specifier.
3459 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3460 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3461 return true;
3462 // Visit the declaration name.
3463 if (VisitDeclarationNameInfo(O->getNameInfo()))
3464 return true;
3465 // Visit the overloaded declaration reference.
3466 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3467 return true;
3468 continue;
3469 }
3470 case VisitorJob::SizeOfPackExprPartsKind: {
3471 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
3472 NamedDecl *Pack = E->getPack();
3473 if (isa<TemplateTypeParmDecl>(Pack)) {
3474 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3475 E->getPackLoc(), TU)))
3476 return true;
3477
3478 continue;
3479 }
3480
3481 if (isa<TemplateTemplateParmDecl>(Pack)) {
3482 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3483 E->getPackLoc(), TU)))
3484 return true;
3485
3486 continue;
3487 }
3488
3489 // Non-type template parameter packs and function parameter packs are
3490 // treated like DeclRefExpr cursors.
3491 continue;
3492 }
3493
3494 case VisitorJob::LambdaExprPartsKind: {
3495 // Visit non-init captures.
3496 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
3497 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3498 CEnd = E->explicit_capture_end();
3499 C != CEnd; ++C) {
3500 if (!C->capturesVariable())
3501 continue;
3502 // TODO: handle structured bindings here ?
3503 if (!isa<VarDecl>(C->getCapturedVar()))
3504 continue;
3505 if (Visit(MakeCursorVariableRef(cast<VarDecl>(C->getCapturedVar()),
3506 C->getLocation(), TU)))
3507 return true;
3508 }
3509 // Visit init captures
3510 for (auto InitExpr : E->capture_inits()) {
3511 if (InitExpr && Visit(InitExpr))
3512 return true;
3513 }
3514
3515 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3516 // Visit parameters and return type, if present.
3517 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3518 if (E->hasExplicitParameters()) {
3519 // Visit parameters.
3520 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3521 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
3522 return true;
3523 }
3524 if (E->hasExplicitResultType()) {
3525 // Visit result type.
3526 if (Visit(Proto.getReturnLoc()))
3527 return true;
3528 }
3529 }
3530 break;
3531 }
3532
3533 case VisitorJob::ConceptSpecializationExprVisitKind: {
3534 const ConceptSpecializationExpr *E =
3535 cast<ConceptSpecializationExprVisit>(&LI)->get();
3536 if (NestedNameSpecifierLoc QualifierLoc =
3537 E->getNestedNameSpecifierLoc()) {
3538 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3539 return true;
3540 }
3541
3542 if (E->getNamedConcept() &&
3543 Visit(MakeCursorTemplateRef(E->getNamedConcept(),
3544 E->getConceptNameLoc(), TU)))
3545 return true;
3546
3547 if (auto Args = E->getTemplateArgsAsWritten()) {
3548 for (const auto &Arg : Args->arguments()) {
3549 if (VisitTemplateArgumentLoc(Arg))
3550 return true;
3551 }
3552 }
3553 break;
3554 }
3555
3556 case VisitorJob::RequiresExprVisitKind: {
3557 const RequiresExpr *E = cast<RequiresExprVisit>(&LI)->get();
3558 for (const concepts::Requirement *R : E->getRequirements())
3559 VisitConceptRequirement(*R);
3560 break;
3561 }
3562
3563 case VisitorJob::PostChildrenVisitKind:
3564 if (PostChildrenVisitor(Parent, ClientData))
3565 return true;
3566 break;
3567 }
3568 }
3569 return false;
3570}
3571
3572bool CursorVisitor::Visit(const Stmt *S) {
3573 VisitorWorkList *WL = nullptr;
3574 if (!WorkListFreeList.empty()) {
3575 WL = WorkListFreeList.back();
3576 WL->clear();
3577 WorkListFreeList.pop_back();
3578 } else {
3579 WL = new VisitorWorkList();
3580 WorkListCache.push_back(WL);
3581 }
3582 EnqueueWorkList(*WL, S);
3583 bool result = RunVisitorWorkList(*WL);
3584 WorkListFreeList.push_back(WL);
3585 return result;
3586}
3587
3588namespace {
3589typedef SmallVector<SourceRange, 4> RefNamePieces;
3590RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3591 const DeclarationNameInfo &NI, SourceRange QLoc,
3592 const SourceRange *TemplateArgsLoc = nullptr) {
3593 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3594 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3595 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3596
3597 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3598
3599 RefNamePieces Pieces;
3600
3601 if (WantQualifier && QLoc.isValid())
3602 Pieces.push_back(QLoc);
3603
3604 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3605 Pieces.push_back(NI.getLoc());
3606
3607 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3608 Pieces.push_back(*TemplateArgsLoc);
3609
3610 if (Kind == DeclarationName::CXXOperatorName) {
3611 Pieces.push_back(NI.getInfo().getCXXOperatorNameBeginLoc());
3612 Pieces.push_back(NI.getInfo().getCXXOperatorNameEndLoc());
3613 }
3614
3615 if (WantSinglePiece) {
3616 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3617 Pieces.clear();
3618 Pieces.push_back(R);
3619 }
3620
3621 return Pieces;
3622}
3623} // namespace
3624
3625//===----------------------------------------------------------------------===//
3626// Misc. API hooks.
3627//===----------------------------------------------------------------------===//
3628
3629namespace {
3630struct RegisterFatalErrorHandler {
3631 RegisterFatalErrorHandler() {
3632 clang_install_aborting_llvm_fatal_error_handler();
3633 }
3634};
3635} // namespace
3636
3637static llvm::ManagedStatic<RegisterFatalErrorHandler>
3638 RegisterFatalErrorHandlerOnce;
3639
3640CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3641 int displayDiagnostics) {
3642 // We use crash recovery to make some of our APIs more reliable, implicitly
3643 // enable it.
3644 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3645 llvm::CrashRecoveryContext::Enable();
3646
3647 // Look through the managed static to trigger construction of the managed
3648 // static which registers our fatal error handler. This ensures it is only
3649 // registered once.
3650 (void)*RegisterFatalErrorHandlerOnce;
3651
3652 // Initialize targets for clang module support.
3653 llvm::InitializeAllTargets();
3654 llvm::InitializeAllTargetMCs();
3655 llvm::InitializeAllAsmPrinters();
3656 llvm::InitializeAllAsmParsers();
3657
3658 CIndexer *CIdxr = new CIndexer();
3659
3660 if (excludeDeclarationsFromPCH)
3661 CIdxr->setOnlyLocalDecls();
3662 if (displayDiagnostics)
3663 CIdxr->setDisplayDiagnostics();
3664
3665 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3666 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3667 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3668 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3669 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3670 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3671
3672 return CIdxr;
3673}
3674
3675void clang_disposeIndex(CXIndex CIdx) {
3676 if (CIdx)
3677 delete static_cast<CIndexer *>(CIdx);
3678}
3679
3680void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3681 if (CIdx)
3682 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3683}
3684
3685unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3686 if (CIdx)
3687 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3688 return 0;
3689}
3690
3691void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3692 const char *Path) {
3693 if (CIdx)
3694 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3695}
3696
3697void clang_toggleCrashRecovery(unsigned isEnabled) {
3698 if (isEnabled)
3699 llvm::CrashRecoveryContext::Enable();
3700 else
3701 llvm::CrashRecoveryContext::Disable();
3702}
3703
3704CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3705 const char *ast_filename) {
3706 CXTranslationUnit TU;
3707 enum CXErrorCode Result =
3708 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
3709 (void)Result;
3710 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", 3711, __extension__ __PRETTY_FUNCTION__
))
3711 (!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", 3711, __extension__ __PRETTY_FUNCTION__
))
;
3712 return TU;
3713}
3714
3715enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3716 const char *ast_filename,
3717 CXTranslationUnit *out_TU) {
3718 if (out_TU)
3719 *out_TU = nullptr;
3720
3721 if (!CIdx || !ast_filename || !out_TU)
3722 return CXError_InvalidArguments;
3723
3724 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{ *Log << ast_filename; }
3725
3726 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3727 FileSystemOptions FileSystemOpts;
3728
3729 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3730 CompilerInstance::createDiagnostics(new DiagnosticOptions());
3731 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
3732 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3733 ASTUnit::LoadEverything, Diags, FileSystemOpts, /*UseDebugInfo=*/false,
3734 CXXIdx->getOnlyLocalDecls(), CaptureDiagsKind::All,
3735 /*AllowASTWithCompilerErrors=*/true,
3736 /*UserFilesAreVolatile=*/true);
3737 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
3738 return *out_TU ? CXError_Success : CXError_Failure;
3739}
3740
3741unsigned clang_defaultEditingTranslationUnitOptions() {
3742 return CXTranslationUnit_PrecompiledPreamble |
3743 CXTranslationUnit_CacheCompletionResults;
3744}
3745
3746CXTranslationUnit clang_createTranslationUnitFromSourceFile(
3747 CXIndex CIdx, const char *source_filename, int num_command_line_args,
3748 const char *const *command_line_args, unsigned num_unsaved_files,
3749 struct CXUnsavedFile *unsaved_files) {
3750 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3751 return clang_parseTranslationUnit(CIdx, source_filename, command_line_args,
1
Calling 'clang_parseTranslationUnit'
3752 num_command_line_args, unsaved_files,
3753 num_unsaved_files, Options);
3754}
3755
3756static CXErrorCode
3757clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3758 const char *const *command_line_args,
3759 int num_command_line_args,
3760 ArrayRef<CXUnsavedFile> unsaved_files,
3761 unsigned options, CXTranslationUnit *out_TU) {
3762 // Set up the initial return values.
3763 if (out_TU)
3764 *out_TU = nullptr;
3765
3766 // Check arguments.
3767 if (!CIdx || !out_TU)
3768 return CXError_InvalidArguments;
3769
3770 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3771
3772 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3773 setThreadBackgroundPriority();
3774
3775 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3776 bool CreatePreambleOnFirstParse =
3777 options & CXTranslationUnit_CreatePreambleOnFirstParse;
3778 // FIXME: Add a flag for modules.
3779 TranslationUnitKind TUKind = (options & (CXTranslationUnit_Incomplete |
3780 CXTranslationUnit_SingleFileParse))
3781 ? TU_Prefix
3782 : TU_Complete;
3783 bool CacheCodeCompletionResults =
3784 options & CXTranslationUnit_CacheCompletionResults;
3785 bool IncludeBriefCommentsInCodeCompletion =
3786 options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3787 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3788 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3789 bool RetainExcludedCB =
3790 options & CXTranslationUnit_RetainExcludedConditionalBlocks;
3791 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3792 if (options & CXTranslationUnit_SkipFunctionBodies) {
3793 SkipFunctionBodies =
3794 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3795 ? SkipFunctionBodiesScope::Preamble
3796 : SkipFunctionBodiesScope::PreambleAndMainFile;
3797 }
3798
3799 // Configure the diagnostics.
3800 std::unique_ptr<DiagnosticOptions> DiagOpts = CreateAndPopulateDiagOpts(
3801 llvm::makeArrayRef(command_line_args, num_command_line_args));
3802 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
3803 CompilerInstance::createDiagnostics(DiagOpts.release()));
3804
3805 if (options & CXTranslationUnit_KeepGoing)
3806 Diags->setFatalsAsError(true);
3807
3808 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3809 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3810 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3811
3812 // Recover resources if we crash before exiting this function.
3813 llvm::CrashRecoveryContextCleanupRegistrar<
3814 DiagnosticsEngine,
3815 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
3816 DiagCleanup(Diags.get());
3817
3818 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3819 new std::vector<ASTUnit::RemappedFile>());
3820
3821 // Recover resources if we crash before exiting this function.
3822 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
3823 RemappedCleanup(RemappedFiles.get());
3824
3825 for (auto &UF : unsaved_files) {
3826 std::unique_ptr<llvm::MemoryBuffer> MB =
3827 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3828 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3829 }
3830
3831 std::unique_ptr<std::vector<const char *>> Args(
3832 new std::vector<const char *>());
3833
3834 // Recover resources if we crash before exiting this method.
3835 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char *>>
3836 ArgsCleanup(Args.get());
3837
3838 // Since the Clang C library is primarily used by batch tools dealing with
3839 // (often very broken) source code, where spell-checking can have a
3840 // significant negative impact on performance (particularly when
3841 // precompiled headers are involved), we disable it by default.
3842 // Only do this if we haven't found a spell-checking-related argument.
3843 bool FoundSpellCheckingArgument = false;
3844 for (int I = 0; I != num_command_line_args; ++I) {
3845 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3846 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3847 FoundSpellCheckingArgument = true;
3848 break;
3849 }
3850 }
3851 Args->insert(Args->end(), command_line_args,
3852 command_line_args + num_command_line_args);
3853
3854 if (!FoundSpellCheckingArgument)
3855 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3856
3857 // The 'source_filename' argument is optional. If the caller does not
3858 // specify it then it is assumed that the source file is specified
3859 // in the actual argument list.
3860 // Put the source file after command_line_args otherwise if '-x' flag is
3861 // present it will be unused.
3862 if (source_filename)
3863 Args->push_back(source_filename);
3864
3865 // Do we need the detailed preprocessing record?
3866 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3867 Args->push_back("-Xclang");
3868 Args->push_back("-detailed-preprocessing-record");
3869 }
3870
3871 // Suppress any editor placeholder diagnostics.
3872 Args->push_back("-fallow-editor-placeholders");
3873
3874 unsigned NumErrors = Diags->getClient()->getNumErrors();
3875 std::unique_ptr<ASTUnit> ErrUnit;
3876 // Unless the user specified that they want the preamble on the first parse
3877 // set it up to be created on the first reparse. This makes the first parse
3878 // faster, trading for a slower (first) reparse.
3879 unsigned PrecompilePreambleAfterNParses =
3880 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
3881
3882 LibclangInvocationReporter InvocationReporter(
3883 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
3884 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/std::nullopt,
3885 unsaved_files);
3886 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3887 Args->data(), Args->data() + Args->size(),
3888 CXXIdx->getPCHContainerOperations(), Diags,
3889 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3890 CaptureDiagnostics, *RemappedFiles.get(),
3891 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3892 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3893 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
3894 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
3895 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3896 &ErrUnit));
3897
3898 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3899 if (!Unit && !ErrUnit)
3900 return CXError_ASTReadError;
3901
3902 if (NumErrors != Diags->getClient()->getNumErrors()) {
3903 // Make sure to check that 'Unit' is non-NULL.
3904 if (CXXIdx->getDisplayDiagnostics())
3905 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3906 }
3907
3908 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3909 return CXError_ASTReadError;
3910
3911 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
3912 if (CXTranslationUnitImpl *TU = *out_TU) {
3913 TU->ParsingOptions = options;
3914 TU->Arguments.reserve(Args->size());
3915 for (const char *Arg : *Args)
3916 TU->Arguments.push_back(Arg);
3917 return CXError_Success;
3918 }
3919 return CXError_Failure;
3920}
3921
3922CXTranslationUnit
3923clang_parseTranslationUnit(CXIndex CIdx, const char *source_filename,
3924 const char *const *command_line_args,
3925 int num_command_line_args,
3926 struct CXUnsavedFile *unsaved_files,
3927 unsigned num_unsaved_files, unsigned options) {
3928 CXTranslationUnit TU;
2
'TU' declared without an initial value
3929 enum CXErrorCode Result = clang_parseTranslationUnit2(
3
Calling 'clang_parseTranslationUnit2'
12
Returning from 'clang_parseTranslationUnit2'
3930 CIdx, source_filename, command_line_args, num_command_line_args,
3931 unsaved_files, num_unsaved_files, options, &TU);
3932 (void)Result;
3933 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", 3934, __extension__ __PRETTY_FUNCTION__
))
13
Branch condition evaluates to a garbage value
3934 (!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", 3934, __extension__ __PRETTY_FUNCTION__
))
;
3935 return TU;
3936}
3937
3938enum CXErrorCode clang_parseTranslationUnit2(
3939 CXIndex CIdx, const char *source_filename,
3940 const char *const *command_line_args, int num_command_line_args,
3941 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3942 unsigned options, CXTranslationUnit *out_TU) {
3943 noteBottomOfStack();
3944 SmallVector<const char *, 4> Args;
3945 Args.push_back("clang");
3946 Args.append(command_line_args, command_line_args + num_command_line_args);
3947 return clang_parseTranslationUnit2FullArgv(
4
Calling 'clang_parseTranslationUnit2FullArgv'
10
Returning from 'clang_parseTranslationUnit2FullArgv'
11
Returning without writing to '*out_TU'
3948 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3949 num_unsaved_files, options, out_TU);
3950}
3951
3952enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3953 CXIndex CIdx, const char *source_filename,
3954 const char *const *command_line_args, int num_command_line_args,
3955 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3956 unsigned options, CXTranslationUnit *out_TU) {
3957 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
5
Taking false branch
3958 *Log << source_filename << ": ";
3959 for (int i = 0; i != num_command_line_args; ++i)
3960 *Log << command_line_args[i] << " ";
3961 }
3962
3963 if (num_unsaved_files && !unsaved_files)
6
Assuming 'num_unsaved_files' is not equal to 0
7
Assuming 'unsaved_files' is null
8
Taking true branch
3964 return CXError_InvalidArguments;
9
Returning without writing to '*out_TU'
3965
3966 CXErrorCode result = CXError_Failure;
3967 auto ParseTranslationUnitImpl = [=, &result] {
3968 noteBottomOfStack();
3969 result = clang_parseTranslationUnit_Impl(
3970 CIdx, source_filename, command_line_args, num_command_line_args,
3971 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3972 };
3973
3974 llvm::CrashRecoveryContext CRC;
3975
3976 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3977 fprintf(stderrstderr, "libclang: crash detected during parsing: {\n");
3978 fprintf(stderrstderr, " 'source_filename' : '%s'\n", source_filename);
3979 fprintf(stderrstderr, " 'command_line_args' : [");
3980 for (int i = 0; i != num_command_line_args; ++i) {
3981 if (i)
3982 fprintf(stderrstderr, ", ");
3983 fprintf(stderrstderr, "'%s'", command_line_args[i]);
3984 }
3985 fprintf(stderrstderr, "],\n");
3986 fprintf(stderrstderr, " 'unsaved_files' : [");
3987 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3988 if (i)
3989 fprintf(stderrstderr, ", ");
3990 fprintf(stderrstderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3991 unsaved_files[i].Length);
3992 }
3993 fprintf(stderrstderr, "],\n");
3994 fprintf(stderrstderr, " 'options' : %d,\n", options);
3995 fprintf(stderrstderr, "}\n");
3996
3997 return CXError_Crashed;
3998 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3999 if (CXTranslationUnit *TU = out_TU)
4000 PrintLibclangResourceUsage(*TU);
4001 }
4002
4003 return result;
4004}
4005
4006CXString clang_Type_getObjCEncoding(CXType CT) {
4007 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
4008 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
4009 std::string encoding;
4010 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]), encoding);
4011
4012 return cxstring::createDup(encoding);
4013}
4014
4015static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
4016 if (C.kind == CXCursor_MacroDefinition) {
4017 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
4018 return MDR->getName();
4019 } else if (C.kind == CXCursor_MacroExpansion) {
4020 MacroExpansionCursor ME = getCursorMacroExpansion(C);
4021 return ME.getName();
4022 }
4023 return nullptr;
4024}
4025
4026unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
4027 const IdentifierInfo *II = getMacroIdentifier(C);
4028 if (!II) {
4029 return false;
4030 }
4031 ASTUnit *ASTU = getCursorASTUnit(C);
4032 Preprocessor &PP = ASTU->getPreprocessor();
4033 if (const MacroInfo *MI = PP.getMacroInfo(II))
4034 return MI->isFunctionLike();
4035 return false;
4036}
4037
4038unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
4039 const IdentifierInfo *II = getMacroIdentifier(C);
4040 if (!II) {
4041 return false;
4042 }
4043 ASTUnit *ASTU = getCursorASTUnit(C);
4044 Preprocessor &PP = ASTU->getPreprocessor();
4045 if (const MacroInfo *MI = PP.getMacroInfo(II))
4046 return MI->isBuiltinMacro();
4047 return false;
4048}
4049
4050unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
4051 const Decl *D = getCursorDecl(C);
4052 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
4053 if (!FD) {
4054 return false;
4055 }
4056 return FD->isInlined();
4057}
4058
4059static StringLiteral *getCFSTR_value(CallExpr *callExpr) {
4060 if (callExpr->getNumArgs() != 1) {
4061 return nullptr;
4062 }
4063
4064 StringLiteral *S = nullptr;
4065 auto *arg = callExpr->getArg(0);
4066 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
4067 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
4068 auto *subExpr = I->getSubExprAsWritten();
4069
4070 if (subExpr->getStmtClass() != Stmt::StringLiteralClass) {
4071 return nullptr;
4072 }
4073
4074 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
4075 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
4076 S = static_cast<StringLiteral *>(callExpr->getArg(0));
4077 } else {
4078 return nullptr;
4079 }
4080 return S;
4081}
4082
4083struct ExprEvalResult {
4084 CXEvalResultKind EvalType;
4085 union {
4086 unsigned long long unsignedVal;
4087 long long intVal;
4088 double floatVal;
4089 char *stringVal;
4090 } EvalData;
4091 bool IsUnsignedInt;
4092 ~ExprEvalResult() {
4093 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
4094 EvalType != CXEval_Int) {
4095 delete[] EvalData.stringVal;
4096 }
4097 }
4098};
4099
4100void clang_EvalResult_dispose(CXEvalResult E) {
4101 delete static_cast<ExprEvalResult *>(E);
4102}
4103
4104CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
4105 if (!E) {
4106 return CXEval_UnExposed;
4107 }
4108 return ((ExprEvalResult *)E)->EvalType;
4109}
4110
4111int clang_EvalResult_getAsInt(CXEvalResult E) {
4112 return clang_EvalResult_getAsLongLong(E);
4113}
4114
4115long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
4116 if (!E) {
4117 return 0;
4118 }
4119 ExprEvalResult *Result = (ExprEvalResult *)E;
4120 if (Result->IsUnsignedInt)
4121 return Result->EvalData.unsignedVal;
4122 return Result->EvalData.intVal;
4123}
4124
4125unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
4126 return ((ExprEvalResult *)E)->IsUnsignedInt;
4127}
4128
4129unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
4130 if (!E) {
4131 return 0;
4132 }
4133
4134 ExprEvalResult *Result = (ExprEvalResult *)E;
4135 if (Result->IsUnsignedInt)
4136 return Result->EvalData.unsignedVal;
4137 return Result->EvalData.intVal;
4138}
4139
4140double clang_EvalResult_getAsDouble(CXEvalResult E) {
4141 if (!E) {
4142 return 0;
4143 }
4144 return ((ExprEvalResult *)E)->EvalData.floatVal;
4145}
4146
4147const char *clang_EvalResult_getAsStr(CXEvalResult E) {
4148 if (!E) {
4149 return nullptr;
4150 }
4151 return ((ExprEvalResult *)E)->EvalData.stringVal;
4152}
4153
4154static const ExprEvalResult *evaluateExpr(Expr *expr, CXCursor C) {
4155 Expr::EvalResult ER;
4156 ASTContext &ctx = getCursorContext(C);
4157 if (!expr)
4158 return nullptr;
4159
4160 expr = expr->IgnoreParens();
4161 if (expr->isValueDependent())
4162 return nullptr;
4163 if (!expr->EvaluateAsRValue(ER, ctx))
4164 return nullptr;
4165
4166 QualType rettype;
4167 CallExpr *callExpr;
4168 auto result = std::make_unique<ExprEvalResult>();
4169 result->EvalType = CXEval_UnExposed;
4170 result->IsUnsignedInt = false;
4171
4172 if (ER.Val.isInt()) {
4173 result->EvalType = CXEval_Int;
4174
4175 auto &val = ER.Val.getInt();
4176 if (val.isUnsigned()) {
4177 result->IsUnsignedInt = true;
4178 result->EvalData.unsignedVal = val.getZExtValue();
4179 } else {
4180 result->EvalData.intVal = val.getExtValue();
4181 }
4182
4183 return result.release();
4184 }
4185
4186 if (ER.Val.isFloat()) {
4187 llvm::SmallVector<char, 100> Buffer;
4188 ER.Val.getFloat().toString(Buffer);
4189 std::string floatStr(Buffer.data(), Buffer.size());
4190 result->EvalType = CXEval_Float;
4191 bool ignored;
4192 llvm::APFloat apFloat = ER.Val.getFloat();
4193 apFloat.convert(llvm::APFloat::IEEEdouble(),
4194 llvm::APFloat::rmNearestTiesToEven, &ignored);
4195 result->EvalData.floatVal = apFloat.convertToDouble();
4196 return result.release();
4197 }
4198
4199 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
4200 const auto *I = cast<ImplicitCastExpr>(expr);
4201 auto *subExpr = I->getSubExprAsWritten();
4202 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
4203 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
4204 const StringLiteral *StrE = nullptr;
4205 const ObjCStringLiteral *ObjCExpr;
4206 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
4207
4208 if (ObjCExpr) {
4209 StrE = ObjCExpr->getString();
4210 result->EvalType = CXEval_ObjCStrLiteral;
4211 } else {
4212 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
4213 result->EvalType = CXEval_StrLiteral;
4214 }
4215
4216 std::string strRef(StrE->getString().str());
4217 result->EvalData.stringVal = new char[strRef.size() + 1];
4218 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
4219 strRef.size());
4220 result->EvalData.stringVal[strRef.size()] = '\0';
4221 return result.release();
4222 }
4223 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
4224 expr->getStmtClass() == Stmt::StringLiteralClass) {
4225 const StringLiteral *StrE = nullptr;
4226 const ObjCStringLiteral *ObjCExpr;
4227 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
4228
4229 if (ObjCExpr) {
4230 StrE = ObjCExpr->getString();
4231 result->EvalType = CXEval_ObjCStrLiteral;
4232 } else {
4233 StrE = cast<StringLiteral>(expr);
4234 result->EvalType = CXEval_StrLiteral;
4235 }
4236
4237 std::string strRef(StrE->getString().str());
4238 result->EvalData.stringVal = new char[strRef.size() + 1];
4239 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
4240 result->EvalData.stringVal[strRef.size()] = '\0';
4241 return result.release();
4242 }
4243
4244 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
4245 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
4246
4247 rettype = CC->getType();
4248 if (rettype.getAsString() == "CFStringRef" &&
4249 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
4250
4251 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
4252 StringLiteral *S = getCFSTR_value(callExpr);
4253 if (S) {
4254 std::string strLiteral(S->getString().str());
4255 result->EvalType = CXEval_CFStr;
4256
4257 result->EvalData.stringVal = new char[strLiteral.size() + 1];
4258 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
4259 strLiteral.size());
4260 result->EvalData.stringVal[strLiteral.size()] = '\0';
4261 return result.release();
4262 }
4263 }
4264
4265 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
4266 callExpr = static_cast<CallExpr *>(expr);
4267 rettype = callExpr->getCallReturnType(ctx);
4268
4269 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
4270 return nullptr;
4271
4272 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
4273 if (callExpr->getNumArgs() == 1 &&
4274 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
4275 return nullptr;
4276 } else if (rettype.getAsString() == "CFStringRef") {
4277
4278 StringLiteral *S = getCFSTR_value(callExpr);
4279 if (S) {
4280 std::string strLiteral(S->getString().str());
4281 result->EvalType = CXEval_CFStr;
4282 result->EvalData.stringVal = new char[strLiteral.size() + 1];
4283 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
4284 strLiteral.size());
4285 result->EvalData.stringVal[strLiteral.size()] = '\0';
4286 return result.release();
4287 }
4288 }
4289 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
4290 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
4291 ValueDecl *V = D->getDecl();
4292 if (V->getKind() == Decl::Function) {
4293 std::string strName = V->getNameAsString();
4294 result->EvalType = CXEval_Other;
4295 result->EvalData.stringVal = new char[strName.size() + 1];
4296 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
4297 result->EvalData.stringVal[strName.size()] = '\0';
4298 return result.release();
4299 }
4300 }
4301
4302 return nullptr;
4303}
4304
4305static const Expr *evaluateDeclExpr(const Decl *D) {
4306 if (!D)
4307 return nullptr;
4308 if (auto *Var = dyn_cast<VarDecl>(D))
4309 return Var->getInit();
4310 else if (auto *Field = dyn_cast<FieldDecl>(D))
4311 return Field->getInClassInitializer();
4312 return nullptr;
4313}
4314
4315static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
4316 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", 4316, __extension__ __PRETTY_FUNCTION__
))
;
4317 for (auto *bodyIterator : CS->body()) {
4318 if (const auto *E = dyn_cast<Expr>(bodyIterator))
4319 return E;
4320 }
4321 return nullptr;
4322}
4323
4324CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
4325 const Expr *E = nullptr;
4326 if (clang_getCursorKind(C) == CXCursor_CompoundStmt)
4327 E = evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)));
4328 else if (clang_isDeclaration(C.kind))
4329 E = evaluateDeclExpr(getCursorDecl(C));
4330 else if (clang_isExpression(C.kind))
4331 E = getCursorExpr(C);
4332 if (E)
4333 return const_cast<CXEvalResult>(
4334 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4335 return nullptr;
4336}
4337
4338unsigned clang_Cursor_hasAttrs(CXCursor C) {
4339 const Decl *D = getCursorDecl(C);
4340 if (!D) {
4341 return 0;
4342 }
4343
4344 if (D->hasAttrs()) {
4345 return 1;
4346 }
4347
4348 return 0;
4349}
4350unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4351 return CXSaveTranslationUnit_None;
4352}
4353
4354static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4355 const char *FileName,
4356 unsigned options) {
4357 CIndexer *CXXIdx = TU->CIdx;
4358 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4359 setThreadBackgroundPriority();
4360
4361 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4362 return hadError ? CXSaveError_Unknown : CXSaveError_None;
4363}
4364
4365int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4366 unsigned options) {
4367 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{ *Log << TU << ' ' << FileName; }
4368
4369 if (isNotUsableTU(TU)) {
4370 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4371 return CXSaveError_InvalidTU;
4372 }
4373
4374 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4375 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4376 if (!CXXUnit->hasSema())
4377 return CXSaveError_InvalidTU;
4378
4379 CXSaveError result;
4380 auto SaveTranslationUnitImpl = [=, &result]() {
4381 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4382 };
4383
4384 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
4385 SaveTranslationUnitImpl();
4386
4387 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4388 PrintLibclangResourceUsage(TU);
4389
4390 return result;
4391 }
4392
4393 // We have an AST that has invalid nodes due to compiler errors.
4394 // Use a crash recovery thread for protection.
4395
4396 llvm::CrashRecoveryContext CRC;
4397
4398 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
4399 fprintf(stderrstderr, "libclang: crash detected during AST saving: {\n");
4400 fprintf(stderrstderr, " 'filename' : '%s'\n", FileName);
4401 fprintf(stderrstderr, " 'options' : %d,\n", options);
4402 fprintf(stderrstderr, "}\n");
4403
4404 return CXSaveError_Unknown;
4405
4406 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4407 PrintLibclangResourceUsage(TU);
4408 }
4409
4410 return result;
4411}
4412
4413void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4414 if (CTUnit) {
4415 // If the translation unit has been marked as unsafe to free, just discard
4416 // it.
4417 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4418 if (Unit && Unit->isUnsafeToFree())
4419 return;
4420
4421 delete cxtu::getASTUnit(CTUnit);
4422 delete CTUnit->StringPool;
4423 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4424 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
4425 delete CTUnit->CommentToXML;
4426 delete CTUnit;
4427 }
4428}
4429
4430unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4431 if (CTUnit) {
4432 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4433
4434 if (Unit && Unit->isUnsafeToFree())
4435 return false;
4436
4437 Unit->ResetForParse();
4438 return true;
4439 }
4440
4441 return false;
4442}
4443
4444unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4445 return CXReparse_None;
4446}
4447
4448static CXErrorCode
4449clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4450 ArrayRef<CXUnsavedFile> unsaved_files,
4451 unsigned options) {
4452 // Check arguments.
4453 if (isNotUsableTU(TU)) {
4454 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4455 return CXError_InvalidArguments;
4456 }
4457
4458 // Reset the associated diagnostics.
4459 delete static_cast<CXDiagnosticSetImpl *>(TU->Diagnostics);
4460 TU->Diagnostics = nullptr;
4461
4462 CIndexer *CXXIdx = TU->CIdx;
4463 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4464 setThreadBackgroundPriority();
4465
4466 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4467 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4468
4469 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4470 new std::vector<ASTUnit::RemappedFile>());
4471
4472 // Recover resources if we crash before exiting this function.
4473 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
4474 RemappedCleanup(RemappedFiles.get());
4475
4476 for (auto &UF : unsaved_files) {
4477 std::unique_ptr<llvm::MemoryBuffer> MB =
4478 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
4479 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
4480 }
4481
4482 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4483 *RemappedFiles.get()))
4484 return CXError_Success;
4485 if (isASTReadError(CXXUnit))
4486 return CXError_ASTReadError;
4487 return CXError_Failure;
4488}
4489
4490int clang_reparseTranslationUnit(CXTranslationUnit TU,
4491 unsigned num_unsaved_files,
4492 struct CXUnsavedFile *unsaved_files,
4493 unsigned options) {
4494 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{ *Log << TU; }
4495
4496 if (num_unsaved_files && !unsaved_files)
4497 return CXError_InvalidArguments;
4498
4499 CXErrorCode result;
4500 auto ReparseTranslationUnitImpl = [=, &result]() {
4501 result = clang_reparseTranslationUnit_Impl(
4502 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4503 };
4504
4505 llvm::CrashRecoveryContext CRC;
4506
4507 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
4508 fprintf(stderrstderr, "libclang: crash detected during reparsing\n");
4509 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
4510 return CXError_Crashed;
4511 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4512 PrintLibclangResourceUsage(TU);
4513
4514 return result;
4515}
4516
4517CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
4518 if (isNotUsableTU(CTUnit)) {
4519 LOG_BAD_TU(CTUnit)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
CTUnit; } } while(false)
;
4520 return cxstring::createEmpty();
4521 }
4522
4523 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4524 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
4525}
4526
4527CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
4528 if (isNotUsableTU(TU)) {
4529 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4530 return clang_getNullCursor();
4531 }
4532
4533 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4534 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4535}
4536
4537CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4538 if (isNotUsableTU(CTUnit)) {
4539 LOG_BAD_TU(CTUnit)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
CTUnit; } } while(false)
;
4540 return nullptr;
4541 }
4542
4543 CXTargetInfoImpl *impl = new CXTargetInfoImpl();
4544 impl->TranslationUnit = CTUnit;
4545 return impl;
4546}
4547
4548CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4549 if (!TargetInfo)
4550 return cxstring::createEmpty();
4551
4552 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4553 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", 4554, __extension__ __PRETTY_FUNCTION__
))
4554 "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", 4554, __extension__ __PRETTY_FUNCTION__
))
;
4555
4556 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4557 std::string Triple =
4558 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4559 return cxstring::createDup(Triple);
4560}
4561
4562int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4563 if (!TargetInfo)
4564 return -1;
4565
4566 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4567 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", 4568, __extension__ __PRETTY_FUNCTION__
))
4568 "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", 4568, __extension__ __PRETTY_FUNCTION__
))
;
4569
4570 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4571 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4572}
4573
4574void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4575 if (!TargetInfo)
4576 return;
4577
4578 delete TargetInfo;
4579}
4580
4581//===----------------------------------------------------------------------===//
4582// CXFile Operations.
4583//===----------------------------------------------------------------------===//
4584
4585CXString clang_getFileName(CXFile SFile) {
4586 if (!SFile)
4587 return cxstring::createNull();
4588
4589 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4590 return cxstring::createRef(FEnt->getName());
4591}
4592
4593time_t clang_getFileTime(CXFile SFile) {
4594 if (!SFile)
4595 return 0;
4596
4597 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4598 return FEnt->getModificationTime();
4599}
4600
4601CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
4602 if (isNotUsableTU(TU)) {
4603 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4604 return nullptr;
4605 }
4606
4607 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4608
4609 FileManager &FMgr = CXXUnit->getFileManager();
4610 auto File = FMgr.getFile(file_name);
4611 if (!File)
4612 return nullptr;
4613 return const_cast<FileEntry *>(*File);
4614}
4615
4616const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4617 size_t *size) {
4618 if (isNotUsableTU(TU)) {
4619 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4620 return nullptr;
4621 }
4622
4623 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4624 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4625 llvm::Optional<llvm::MemoryBufferRef> buf = SM.getBufferOrNone(fid);
4626 if (!buf) {
4627 if (size)
4628 *size = 0;
4629 return nullptr;
4630 }
4631 if (size)
4632 *size = buf->getBufferSize();
4633 return buf->getBufferStart();
4634}
4635
4636unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, CXFile file) {
4637 if (isNotUsableTU(TU)) {
4638 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4639 return 0;
4640 }
4641
4642 if (!file)
4643 return 0;
4644
4645 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4646 FileEntry *FEnt = static_cast<FileEntry *>(file);
4647 return CXXUnit->getPreprocessor()
4648 .getHeaderSearchInfo()
4649 .isFileMultipleIncludeGuarded(FEnt);
4650}
4651
4652int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4653 if (!file || !outID)
4654 return 1;
4655
4656 FileEntry *FEnt = static_cast<FileEntry *>(file);
4657 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4658 outID->data[0] = ID.getDevice();
4659 outID->data[1] = ID.getFile();
4660 outID->data[2] = FEnt->getModificationTime();
4661 return 0;
4662}
4663
4664int clang_File_isEqual(CXFile file1, CXFile file2) {
4665 if (file1 == file2)
4666 return true;
4667
4668 if (!file1 || !file2)
4669 return false;
4670
4671 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4672 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4673 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4674}
4675
4676CXString clang_File_tryGetRealPathName(CXFile SFile) {
4677 if (!SFile)
4678 return cxstring::createNull();
4679
4680 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4681 return cxstring::createRef(FEnt->tryGetRealPathName());
4682}
4683
4684//===----------------------------------------------------------------------===//
4685// CXCursor Operations.
4686//===----------------------------------------------------------------------===//
4687
4688static const Decl *getDeclFromExpr(const Stmt *E) {
4689 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4690 return getDeclFromExpr(CE->getSubExpr());
4691
4692 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
4693 return RefExpr->getDecl();
4694 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4695 return ME->getMemberDecl();
4696 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
4697 return RE->getDecl();
4698 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
4699 if (PRE->isExplicitProperty())
4700 return PRE->getExplicitProperty();
4701 // It could be messaging both getter and setter as in:
4702 // ++myobj.myprop;
4703 // in which case prefer to associate the setter since it is less obvious
4704 // from inspecting the source that the setter is going to get called.
4705 if (PRE->isMessagingSetter())
4706 return PRE->getImplicitPropertySetter();
4707 return PRE->getImplicitPropertyGetter();
4708 }
4709 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
4710 return getDeclFromExpr(POE->getSyntacticForm());
4711 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4712 if (Expr *Src = OVE->getSourceExpr())
4713 return getDeclFromExpr(Src);
4714
4715 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
4716 return getDeclFromExpr(CE->getCallee());
4717 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
4718 if (!CE->isElidable())
4719 return CE->getConstructor();
4720 if (const CXXInheritedCtorInitExpr *CE =
4721 dyn_cast<CXXInheritedCtorInitExpr>(E))
4722 return CE->getConstructor();
4723 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
4724 return OME->getMethodDecl();
4725
4726 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
4727 return PE->getProtocol();
4728 if (const SubstNonTypeTemplateParmPackExpr *NTTP =
4729 dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4730 return NTTP->getParameterPack();
4731 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4732 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4733 isa<ParmVarDecl>(SizeOfPack->getPack()))
4734 return SizeOfPack->getPack();
4735
4736 return nullptr;
4737}
4738
4739static SourceLocation getLocationFromExpr(const Expr *E) {
4740 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4741 return getLocationFromExpr(CE->getSubExpr());
4742
4743 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
4744 return /*FIXME:*/ Msg->getLeftLoc();
4745 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4746 return DRE->getLocation();
4747 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
4748 return Member->getMemberLoc();
4749 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
4750 return Ivar->getLocation();
4751 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4752 return SizeOfPack->getPackLoc();
4753 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
4754 return PropRef->getLocation();
4755
4756 return E->getBeginLoc();
4757}
4758
4759extern "C" {
4760
4761unsigned clang_visitChildren(CXCursor parent, CXCursorVisitor visitor,
4762 CXClientData client_data) {
4763 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4764 /*VisitPreprocessorLast=*/false);
4765 return CursorVis.VisitChildren(parent);
4766}
4767
4768#ifndef __has_feature
4769#define0 __has_feature(x)0 0
4770#endif
4771#if __has_feature(blocks)0
4772typedef enum CXChildVisitResult (^CXCursorVisitorBlock)(CXCursor cursor,
4773 CXCursor parent);
4774
4775static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4776 CXClientData client_data) {
4777 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4778 return block(cursor, parent);
4779}
4780#else
4781// If we are compiled with a compiler that doesn't have native blocks support,
4782// define and call the block manually, so the
4783typedef struct _CXChildVisitResult {
4784 void *isa;
4785 int flags;
4786 int reserved;
4787 enum CXChildVisitResult (*invoke)(struct _CXChildVisitResult *, CXCursor,
4788 CXCursor);
4789} * CXCursorVisitorBlock;
4790
4791static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4792 CXClientData client_data) {
4793 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4794 return block->invoke(block, cursor, parent);
4795}
4796#endif
4797
4798unsigned clang_visitChildrenWithBlock(CXCursor parent,
4799 CXCursorVisitorBlock block) {
4800 return clang_visitChildren(parent, visitWithBlock, block);
4801}
4802
4803static CXString getDeclSpelling(const Decl *D) {
4804 if (!D)
4805 return cxstring::createEmpty();
4806
4807 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
4808 if (!ND) {
4809 if (const ObjCPropertyImplDecl *PropImpl =
4810 dyn_cast<ObjCPropertyImplDecl>(D))
4811 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4812 return cxstring::createDup(Property->getIdentifier()->getName());
4813
4814 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
4815 if (Module *Mod = ImportD->getImportedModule())
4816 return cxstring::createDup(Mod->getFullModuleName());
4817
4818 return cxstring::createEmpty();
4819 }
4820
4821 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
4822 return cxstring::createDup(OMD->getSelector().getAsString());
4823
4824 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
4825 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4826 // and returns different names. NamedDecl returns the class name and
4827 // ObjCCategoryImplDecl returns the category name.
4828 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
4829
4830 if (isa<UsingDirectiveDecl>(D))
4831 return cxstring::createEmpty();
4832
4833 SmallString<1024> S;
4834 llvm::raw_svector_ostream os(S);
4835 ND->printName(os);
4836
4837 return cxstring::createDup(os.str());
4838}
4839
4840CXString clang_getCursorSpelling(CXCursor C) {
4841 if (clang_isTranslationUnit(C.kind))
4842 return clang_getTranslationUnitSpelling(getCursorTU(C));
4843
4844 if (clang_isReference(C.kind)) {
4845 switch (C.kind) {
4846 case CXCursor_ObjCSuperClassRef: {
4847 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
4848 return cxstring::createRef(Super->getIdentifier()->getNameStart());
4849 }
4850 case CXCursor_ObjCClassRef: {
4851 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4852 return cxstring::createRef(Class->getIdentifier()->getNameStart());
4853 }
4854 case CXCursor_ObjCProtocolRef: {
4855 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
4856 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", 4856, __extension__ __PRETTY_FUNCTION__
))
;
4857 return cxstring::createRef(OID->getIdentifier()->getNameStart());
4858 }
4859 case CXCursor_CXXBaseSpecifier: {
4860 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
4861 return cxstring::createDup(B->getType().getAsString());
4862 }
4863 case CXCursor_TypeRef: {
4864 const TypeDecl *Type = getCursorTypeRef(C).first;
4865 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", 4865, __extension__ __PRETTY_FUNCTION__
))
;
4866
4867 return cxstring::createDup(
4868 getCursorContext(C).getTypeDeclType(Type).getAsString());
4869 }
4870 case CXCursor_TemplateRef: {
4871 const TemplateDecl *Template = getCursorTemplateRef(C).first;
4872 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", 4872, __extension__ __PRETTY_FUNCTION__
))
;
4873
4874 return cxstring::createDup(Template->getNameAsString());
4875 }
4876
4877 case CXCursor_NamespaceRef: {
4878 const NamedDecl *NS = getCursorNamespaceRef(C).first;
4879 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", 4879, __extension__ __PRETTY_FUNCTION__
))
;
4880
4881 return cxstring::createDup(NS->getNameAsString());
4882 }
4883
4884 case CXCursor_MemberRef: {
4885 const FieldDecl *Field = getCursorMemberRef(C).first;
4886 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", 4886, __extension__ __PRETTY_FUNCTION__
))
;
4887
4888 return cxstring::createDup(Field->getNameAsString());
4889 }
4890
4891 case CXCursor_LabelRef: {
4892 const LabelStmt *Label = getCursorLabelRef(C).first;
4893 assert(Label && "Missing label")(static_cast <bool> (Label && "Missing label") ?
void (0) : __assert_fail ("Label && \"Missing label\""
, "clang/tools/libclang/CIndex.cpp", 4893, __extension__ __PRETTY_FUNCTION__
))
;
4894
4895 return cxstring::createRef(Label->getName());
4896 }
4897
4898 case CXCursor_OverloadedDeclRef: {
4899 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4900 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4901 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
4902 return cxstring::createDup(ND->getNameAsString());
4903 return cxstring::createEmpty();
4904 }
4905 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4906 return cxstring::createDup(E->getName().getAsString());
4907 OverloadedTemplateStorage *Ovl =
4908 Storage.get<OverloadedTemplateStorage *>();
4909 if (Ovl->size() == 0)
4910 return cxstring::createEmpty();
4911 return cxstring::createDup((*Ovl->begin())->getNameAsString());
4912 }
4913
4914 case CXCursor_VariableRef: {
4915 const VarDecl *Var = getCursorVariableRef(C).first;
4916 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", 4916, __extension__ __PRETTY_FUNCTION__
))
;
4917
4918 return cxstring::createDup(Var->getNameAsString());
4919 }
4920
4921 default:
4922 return cxstring::createRef("<not implemented>");
4923 }
4924 }
4925
4926 if (clang_isExpression(C.kind)) {
4927 const Expr *E = getCursorExpr(C);
4928
4929 if (C.kind == CXCursor_ObjCStringLiteral ||
4930 C.kind == CXCursor_StringLiteral) {
4931 const StringLiteral *SLit;
4932 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4933 SLit = OSL->getString();
4934 } else {
4935 SLit = cast<StringLiteral>(E);
4936 }
4937 SmallString<256> Buf;
4938 llvm::raw_svector_ostream OS(Buf);
4939 SLit->outputString(OS);
4940 return cxstring::createDup(OS.str());
4941 }
4942
4943 const Decl *D = getDeclFromExpr(getCursorExpr(C));
4944 if (D)
4945 return getDeclSpelling(D);
4946 return cxstring::createEmpty();
4947 }
4948
4949 if (clang_isStatement(C.kind)) {
4950 const Stmt *S = getCursorStmt(C);
4951 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
4952 return cxstring::createRef(Label->getName());
4953
4954 return cxstring::createEmpty();
4955 }
4956
4957 if (C.kind == CXCursor_MacroExpansion)
4958 return cxstring::createRef(
4959 getCursorMacroExpansion(C).getName()->getNameStart());
4960
4961 if (C.kind == CXCursor_MacroDefinition)
4962 return cxstring::createRef(
4963 getCursorMacroDefinition(C)->getName()->getNameStart());
4964
4965 if (C.kind == CXCursor_InclusionDirective)
4966 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
4967
4968 if (clang_isDeclaration(C.kind))
4969 return getDeclSpelling(getCursorDecl(C));
4970
4971 if (C.kind == CXCursor_AnnotateAttr) {
4972 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
4973 return cxstring::createDup(AA->getAnnotation());
4974 }
4975
4976 if (C.kind == CXCursor_AsmLabelAttr) {
4977 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
4978 return cxstring::createDup(AA->getLabel());
4979 }
4980
4981 if (C.kind == CXCursor_PackedAttr) {
4982 return cxstring::createRef("packed");
4983 }
4984
4985 if (C.kind == CXCursor_VisibilityAttr) {
4986 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4987 switch (AA->getVisibility()) {
4988 case VisibilityAttr::VisibilityType::Default:
4989 return cxstring::createRef("default");
4990 case VisibilityAttr::VisibilityType::Hidden:
4991 return cxstring::createRef("hidden");
4992 case VisibilityAttr::VisibilityType::Protected:
4993 return cxstring::createRef("protected");
4994 }
4995 llvm_unreachable("unknown visibility type")::llvm::llvm_unreachable_internal("unknown visibility type", "clang/tools/libclang/CIndex.cpp"
, 4995)
;
4996 }
4997
4998 return cxstring::createEmpty();
4999}
5000
5001CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, unsigned pieceIndex,
5002 unsigned options) {
5003 if (clang_Cursor_isNull(C))
5004 return clang_getNullRange();
5005
5006 ASTContext &Ctx = getCursorContext(C);
5007
5008 if (clang_isStatement(C.kind)) {
5009 const Stmt *S = getCursorStmt(C);
5010 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
5011 if (pieceIndex > 0)
5012 return clang_getNullRange();
5013 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
5014 }
5015
5016 return clang_getNullRange();
5017 }
5018
5019 if (C.kind == CXCursor_ObjCMessageExpr) {
5020 if (const ObjCMessageExpr *ME =
5021 dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
5022 if (pieceIndex >= ME->getNumSelectorLocs())
5023 return clang_getNullRange();
5024 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
5025 }
5026 }
5027
5028 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
5029 C.kind == CXCursor_ObjCClassMethodDecl) {
5030 if (const ObjCMethodDecl *MD =
5031 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
5032 if (pieceIndex >= MD->getNumSelectorLocs())
5033 return clang_getNullRange();
5034 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
5035 }
5036 }
5037
5038 if (C.kind == CXCursor_ObjCCategoryDecl ||
5039 C.kind == CXCursor_ObjCCategoryImplDecl) {
5040 if (pieceIndex > 0)
5041 return clang_getNullRange();
5042 if (const ObjCCategoryDecl *CD =
5043 dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
5044 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
5045 if (const ObjCCategoryImplDecl *CID =
5046 dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
5047 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
5048 }
5049
5050 if (C.kind == CXCursor_ModuleImportDecl) {
5051 if (pieceIndex > 0)
5052 return clang_getNullRange();
5053 if (const ImportDecl *ImportD =
5054 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
5055 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
5056 if (!Locs.empty())
5057 return cxloc::translateSourceRange(
5058 Ctx, SourceRange(Locs.front(), Locs.back()));
5059 }
5060 return clang_getNullRange();
5061 }
5062
5063 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
5064 C.kind == CXCursor_ConversionFunction ||
5065 C.kind == CXCursor_FunctionDecl) {
5066 if (pieceIndex > 0)
5067 return clang_getNullRange();
5068 if (const FunctionDecl *FD =
5069 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
5070 DeclarationNameInfo FunctionName = FD->getNameInfo();
5071 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
5072 }
5073 return clang_getNullRange();
5074 }
5075
5076 // FIXME: A CXCursor_InclusionDirective should give the location of the
5077 // filename, but we don't keep track of this.
5078
5079 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
5080 // but we don't keep track of this.
5081
5082 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
5083 // but we don't keep track of this.
5084
5085 // Default handling, give the location of the cursor.
5086
5087 if (pieceIndex > 0)
5088 return clang_getNullRange();
5089
5090 CXSourceLocation CXLoc = clang_getCursorLocation(C);
5091 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
5092 return cxloc::translateSourceRange(Ctx, Loc);
5093}
5094
5095CXString clang_Cursor_getMangling(CXCursor C) {
5096 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
5097 return cxstring::createEmpty();
5098
5099 // Mangling only works for functions and variables.
5100 const Decl *D = getCursorDecl(C);
5101 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
5102 return cxstring::createEmpty();
5103
5104 ASTContext &Ctx = D->getASTContext();
5105 ASTNameGenerator ASTNameGen(Ctx);
5106 return cxstring::createDup(ASTNameGen.getName(D));
5107}
5108
5109CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
5110 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
5111 return nullptr;
5112
5113 const Decl *D = getCursorDecl(C);
5114 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
5115 return nullptr;
5116
5117 ASTContext &Ctx = D->getASTContext();
5118 ASTNameGenerator ASTNameGen(Ctx);
5119 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
5120 return cxstring::createSet(Manglings);
5121}
5122
5123CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
5124 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
5125 return nullptr;
5126
5127 const Decl *D = getCursorDecl(C);
5128 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
5129 return nullptr;
5130
5131 ASTContext &Ctx = D->getASTContext();
5132 ASTNameGenerator ASTNameGen(Ctx);
5133 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
5134 return cxstring::createSet(Manglings);
5135}
5136
5137CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
5138 if (clang_Cursor_isNull(C))
5139 return nullptr;
5140 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
5141}
5142
5143void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
5144 if (Policy)
5145 delete static_cast<PrintingPolicy *>(Policy);
5146}
5147
5148unsigned
5149clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
5150 enum CXPrintingPolicyProperty Property) {
5151 if (!Policy)
5152 return 0;
5153
5154 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
5155 switch (Property) {
5156 case CXPrintingPolicy_Indentation:
5157 return P->Indentation;
5158 case CXPrintingPolicy_SuppressSpecifiers:
5159 return P->SuppressSpecifiers;
5160 case CXPrintingPolicy_SuppressTagKeyword:
5161 return P->SuppressTagKeyword;
5162 case CXPrintingPolicy_IncludeTagDefinition:
5163 return P->IncludeTagDefinition;
5164 case CXPrintingPolicy_SuppressScope:
5165 return P->SuppressScope;
5166 case CXPrintingPolicy_SuppressUnwrittenScope:
5167 return P->SuppressUnwrittenScope;
5168 case CXPrintingPolicy_SuppressInitializers:
5169 return P->SuppressInitializers;
5170 case CXPrintingPolicy_ConstantArraySizeAsWritten:
5171 return P->ConstantArraySizeAsWritten;
5172 case CXPrintingPolicy_AnonymousTagLocations:
5173 return P->AnonymousTagLocations;
5174 case CXPrintingPolicy_SuppressStrongLifetime:
5175 return P->SuppressStrongLifetime;
5176 case CXPrintingPolicy_SuppressLifetimeQualifiers:
5177 return P->SuppressLifetimeQualifiers;
5178 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
5179 return P->SuppressTemplateArgsInCXXConstructors;
5180 case CXPrintingPolicy_Bool:
5181 return P->Bool;
5182 case CXPrintingPolicy_Restrict:
5183 return P->Restrict;
5184 case CXPrintingPolicy_Alignof:
5185 return P->Alignof;
5186 case CXPrintingPolicy_UnderscoreAlignof:
5187 return P->UnderscoreAlignof;
5188 case CXPrintingPolicy_UseVoidForZeroParams:
5189 return P->UseVoidForZeroParams;
5190 case CXPrintingPolicy_TerseOutput:
5191 return P->TerseOutput;
5192 case CXPrintingPolicy_PolishForDeclaration:
5193 return P->PolishForDeclaration;
5194 case CXPrintingPolicy_Half:
5195 return P->Half;
5196 case CXPrintingPolicy_MSWChar:
5197 return P->MSWChar;
5198 case CXPrintingPolicy_IncludeNewlines:
5199 return P->IncludeNewlines;
5200 case CXPrintingPolicy_MSVCFormatting:
5201 return P->MSVCFormatting;
5202 case CXPrintingPolicy_ConstantsAsWritten:
5203 return P->ConstantsAsWritten;
5204 case CXPrintingPolicy_SuppressImplicitBase:
5205 return P->SuppressImplicitBase;
5206 case CXPrintingPolicy_FullyQualifiedName:
5207 return P->FullyQualifiedName;
5208 }
5209
5210 assert(false && "Invalid CXPrintingPolicyProperty")(static_cast <bool> (false && "Invalid CXPrintingPolicyProperty"
) ? void (0) : __assert_fail ("false && \"Invalid CXPrintingPolicyProperty\""
, "clang/tools/libclang/CIndex.cpp", 5210, __extension__ __PRETTY_FUNCTION__
))
;
5211 return 0;
5212}
5213
5214void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
5215 enum CXPrintingPolicyProperty Property,
5216 unsigned Value) {
5217 if (!Policy)
5218 return;
5219
5220 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
5221 switch (Property) {
5222 case CXPrintingPolicy_Indentation:
5223 P->Indentation = Value;
5224 return;
5225 case CXPrintingPolicy_SuppressSpecifiers:
5226 P->SuppressSpecifiers = Value;
5227 return;
5228 case CXPrintingPolicy_SuppressTagKeyword:
5229 P->SuppressTagKeyword = Value;
5230 return;
5231 case CXPrintingPolicy_IncludeTagDefinition:
5232 P->IncludeTagDefinition = Value;
5233 return;
5234 case CXPrintingPolicy_SuppressScope:
5235 P->SuppressScope = Value;
5236 return;
5237 case CXPrintingPolicy_SuppressUnwrittenScope:
5238 P->SuppressUnwrittenScope = Value;
5239 return;
5240 case CXPrintingPolicy_SuppressInitializers:
5241 P->SuppressInitializers = Value;
5242 return;
5243 case CXPrintingPolicy_ConstantArraySizeAsWritten:
5244 P->ConstantArraySizeAsWritten = Value;
5245 return;
5246 case CXPrintingPolicy_AnonymousTagLocations:
5247 P->AnonymousTagLocations = Value;
5248 return;
5249 case CXPrintingPolicy_SuppressStrongLifetime:
5250 P->SuppressStrongLifetime = Value;
5251 return;
5252 case CXPrintingPolicy_SuppressLifetimeQualifiers:
5253 P->SuppressLifetimeQualifiers = Value;
5254 return;
5255 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
5256 P->SuppressTemplateArgsInCXXConstructors = Value;
5257 return;
5258 case CXPrintingPolicy_Bool:
5259 P->Bool = Value;
5260 return;
5261 case CXPrintingPolicy_Restrict:
5262 P->Restrict = Value;
5263 return;
5264 case CXPrintingPolicy_Alignof:
5265 P->Alignof = Value;
5266 return;
5267 case CXPrintingPolicy_UnderscoreAlignof:
5268 P->UnderscoreAlignof = Value;
5269 return;
5270 case CXPrintingPolicy_UseVoidForZeroParams:
5271 P->UseVoidForZeroParams = Value;
5272 return;
5273 case CXPrintingPolicy_TerseOutput:
5274 P->TerseOutput = Value;
5275 return;
5276 case CXPrintingPolicy_PolishForDeclaration:
5277 P->PolishForDeclaration = Value;
5278 return;
5279 case CXPrintingPolicy_Half:
5280 P->Half = Value;
5281 return;
5282 case CXPrintingPolicy_MSWChar:
5283 P->MSWChar = Value;
5284 return;
5285 case CXPrintingPolicy_IncludeNewlines:
5286 P->IncludeNewlines = Value;
5287 return;
5288 case CXPrintingPolicy_MSVCFormatting:
5289 P->MSVCFormatting = Value;
5290 return;
5291 case CXPrintingPolicy_ConstantsAsWritten:
5292 P->ConstantsAsWritten = Value;
5293 return;
5294 case CXPrintingPolicy_SuppressImplicitBase:
5295 P->SuppressImplicitBase = Value;
5296 return;
5297 case CXPrintingPolicy_FullyQualifiedName:
5298 P->FullyQualifiedName = Value;
5299 return;
5300 }
5301
5302 assert(false && "Invalid CXPrintingPolicyProperty")(static_cast <bool> (false && "Invalid CXPrintingPolicyProperty"
) ? void (0) : __assert_fail ("false && \"Invalid CXPrintingPolicyProperty\""
, "clang/tools/libclang/CIndex.cpp", 5302, __extension__ __PRETTY_FUNCTION__
))
;
5303}
5304
5305CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
5306 if (clang_Cursor_isNull(C))
5307 return cxstring::createEmpty();
5308
5309 if (clang_isDeclaration(C.kind)) {
5310 const Decl *D = getCursorDecl(C);
5311 if (!D)
5312 return cxstring::createEmpty();
5313
5314 SmallString<128> Str;
5315 llvm::raw_svector_ostream OS(Str);
5316 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
5317 D->print(OS, UserPolicy ? *UserPolicy
5318 : getCursorContext(C).getPrintingPolicy());
5319
5320 return cxstring::createDup(OS.str());
5321 }
5322
5323 return cxstring::createEmpty();
5324}
5325
5326CXString clang_getCursorDisplayName(CXCursor C) {
5327 if (!clang_isDeclaration(C.kind))
5328 return clang_getCursorSpelling(C);
5329
5330 const Decl *D = getCursorDecl(C);
5331 if (!D)
5332 return cxstring::createEmpty();
5333
5334 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
5335 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
5336 D = FunTmpl->getTemplatedDecl();
5337
5338 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
5339 SmallString<64> Str;
5340 llvm::raw_svector_ostream OS(Str);
5341 OS << *Function;
5342 if (Function->getPrimaryTemplate())
5343 OS << "<>";
5344 OS << "(";
5345 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5346 if (I)
5347 OS << ", ";
5348 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5349 }
5350
5351 if (Function->isVariadic()) {
5352 if (Function->getNumParams())
5353 OS << ", ";
5354 OS << "...";
5355 }
5356 OS << ")";
5357 return cxstring::createDup(OS.str());
5358 }
5359
5360 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
5361 SmallString<64> Str;
5362 llvm::raw_svector_ostream OS(Str);
5363 OS << *ClassTemplate;
5364 OS << "<";
5365 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5366 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5367 if (I)
5368 OS << ", ";
5369
5370 NamedDecl *Param = Params->getParam(I);
5371 if (Param->getIdentifier()) {
5372 OS << Param->getIdentifier()->getName();
5373 continue;
5374 }
5375
5376 // There is no parameter name, which makes this tricky. Try to come up
5377 // with something useful that isn't too long.
5378 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5379 if (const auto *TC = TTP->getTypeConstraint()) {
5380 TC->getConceptNameInfo().printName(OS, Policy);
5381 if (TC->hasExplicitTemplateArgs())
5382 OS << "<...>";
5383 } else
5384 OS << (TTP->wasDeclaredWithTypename() ? "typename" : "class");
5385 else if (NonTypeTemplateParmDecl *NTTP =
5386 dyn_cast<NonTypeTemplateParmDecl>(Param))
5387 OS << NTTP->getType().getAsString(Policy);
5388 else
5389 OS << "template<...> class";
5390 }
5391
5392 OS << ">";
5393 return cxstring::createDup(OS.str());
5394 }
5395
5396 if (const ClassTemplateSpecializationDecl *ClassSpec =
5397 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5398 // If the type was explicitly written, use that.
5399 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
5400 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
5401
5402 SmallString<128> Str;
5403 llvm::raw_svector_ostream OS(Str);
5404 OS << *ClassSpec;
5405 printTemplateArgumentList(
5406 OS, ClassSpec->getTemplateArgs().asArray(), Policy,
5407 ClassSpec->getSpecializedTemplate()->getTemplateParameters());
5408 return cxstring::createDup(OS.str());
5409 }
5410
5411 return clang_getCursorSpelling(C);
5412}
5413
5414CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5415 switch (Kind) {
5416 case CXCursor_FunctionDecl:
5417 return cxstring::createRef("FunctionDecl");
5418 case CXCursor_TypedefDecl:
5419 return cxstring::createRef("TypedefDecl");
5420 case CXCursor_EnumDecl:
5421 return cxstring::createRef("EnumDecl");
5422 case CXCursor_EnumConstantDecl:
5423 return cxstring::createRef("EnumConstantDecl");
5424 case CXCursor_StructDecl:
5425 return cxstring::createRef("StructDecl");
5426 case CXCursor_UnionDecl:
5427 return cxstring::createRef("UnionDecl");
5428 case CXCursor_ClassDecl:
5429 return cxstring::createRef("ClassDecl");
5430 case CXCursor_FieldDecl:
5431 return cxstring::createRef("FieldDecl");
5432 case CXCursor_VarDecl:
5433 return cxstring::createRef("VarDecl");
5434 case CXCursor_ParmDecl:
5435 return cxstring::createRef("ParmDecl");
5436 case CXCursor_ObjCInterfaceDecl:
5437 return cxstring::createRef("ObjCInterfaceDecl");
5438 case CXCursor_ObjCCategoryDecl:
5439 return cxstring::createRef("ObjCCategoryDecl");
5440 case CXCursor_ObjCProtocolDecl:
5441 return cxstring::createRef("ObjCProtocolDecl");
5442 case CXCursor_ObjCPropertyDecl:
5443 return cxstring::createRef("ObjCPropertyDecl");
5444 case CXCursor_ObjCIvarDecl:
5445 return cxstring::createRef("ObjCIvarDecl");
5446 case CXCursor_ObjCInstanceMethodDecl:
5447 return cxstring::createRef("ObjCInstanceMethodDecl");
5448 case CXCursor_ObjCClassMethodDecl:
5449 return cxstring::createRef("ObjCClassMethodDecl");
5450 case CXCursor_ObjCImplementationDecl:
5451 return cxstring::createRef("ObjCImplementationDecl");
5452 case CXCursor_ObjCCategoryImplDecl:
5453 return cxstring::createRef("ObjCCategoryImplDecl");
5454 case CXCursor_CXXMethod:
5455 return cxstring::createRef("CXXMethod");
5456 case CXCursor_UnexposedDecl:
5457 return cxstring::createRef("UnexposedDecl");
5458 case CXCursor_ObjCSuperClassRef:
5459 return cxstring::createRef("ObjCSuperClassRef");
5460 case CXCursor_ObjCProtocolRef:
5461 return cxstring::createRef("ObjCProtocolRef");
5462 case CXCursor_ObjCClassRef:
5463 return cxstring::createRef("ObjCClassRef");
5464 case CXCursor_TypeRef:
5465 return cxstring::createRef("TypeRef");
5466 case CXCursor_TemplateRef:
5467 return cxstring::createRef("TemplateRef");
5468 case CXCursor_NamespaceRef:
5469 return cxstring::createRef("NamespaceRef");
5470 case CXCursor_MemberRef:
5471 return cxstring::createRef("MemberRef");
5472 case CXCursor_LabelRef:
5473 return cxstring::createRef("LabelRef");
5474 case CXCursor_OverloadedDeclRef:
5475 return cxstring::createRef("OverloadedDeclRef");
5476 case CXCursor_VariableRef:
5477 return cxstring::createRef("VariableRef");
5478 case CXCursor_IntegerLiteral:
5479 return cxstring::createRef("IntegerLiteral");
5480 case CXCursor_FixedPointLiteral:
5481 return cxstring::createRef("FixedPointLiteral");
5482 case CXCursor_FloatingLiteral:
5483 return cxstring::createRef("FloatingLiteral");
5484 case CXCursor_ImaginaryLiteral:
5485 return cxstring::createRef("ImaginaryLiteral");
5486 case CXCursor_StringLiteral:
5487 return cxstring::createRef("StringLiteral");
5488 case CXCursor_CharacterLiteral:
5489 return cxstring::createRef("CharacterLiteral");
5490 case CXCursor_ParenExpr:
5491 return cxstring::createRef("ParenExpr");
5492 case CXCursor_UnaryOperator:
5493 return cxstring::createRef("UnaryOperator");
5494 case CXCursor_ArraySubscriptExpr:
5495 return cxstring::createRef("ArraySubscriptExpr");
5496 case CXCursor_OMPArraySectionExpr:
5497 return cxstring::createRef("OMPArraySectionExpr");
5498 case CXCursor_OMPArrayShapingExpr:
5499 return cxstring::createRef("OMPArrayShapingExpr");
5500 case CXCursor_OMPIteratorExpr:
5501 return cxstring::createRef("OMPIteratorExpr");
5502 case CXCursor_BinaryOperator:
5503 return cxstring::createRef("BinaryOperator");
5504 case CXCursor_CompoundAssignOperator:
5505 return cxstring::createRef("CompoundAssignOperator");
5506 case CXCursor_ConditionalOperator:
5507 return cxstring::createRef("ConditionalOperator");
5508 case CXCursor_CStyleCastExpr:
5509 return cxstring::createRef("CStyleCastExpr");
5510 case CXCursor_CompoundLiteralExpr:
5511 return cxstring::createRef("CompoundLiteralExpr");
5512 case CXCursor_InitListExpr:
5513 return cxstring::createRef("InitListExpr");
5514 case CXCursor_AddrLabelExpr:
5515 return cxstring::createRef("AddrLabelExpr");
5516 case CXCursor_StmtExpr:
5517 return cxstring::createRef("StmtExpr");
5518 case CXCursor_GenericSelectionExpr:
5519 return cxstring::createRef("GenericSelectionExpr");
5520 case CXCursor_GNUNullExpr:
5521 return cxstring::createRef("GNUNullExpr");
5522 case CXCursor_CXXStaticCastExpr:
5523 return cxstring::createRef("CXXStaticCastExpr");
5524 case CXCursor_CXXDynamicCastExpr:
5525 return cxstring::createRef("CXXDynamicCastExpr");
5526 case CXCursor_CXXReinterpretCastExpr:
5527 return cxstring::createRef("CXXReinterpretCastExpr");
5528 case CXCursor_CXXConstCastExpr:
5529 return cxstring::createRef("CXXConstCastExpr");
5530 case CXCursor_CXXFunctionalCastExpr:
5531 return cxstring::createRef("CXXFunctionalCastExpr");
5532 case CXCursor_CXXAddrspaceCastExpr:
5533 return cxstring::createRef("CXXAddrspaceCastExpr");
5534 case CXCursor_CXXTypeidExpr:
5535 return cxstring::createRef("CXXTypeidExpr");
5536 case CXCursor_CXXBoolLiteralExpr:
5537 return cxstring::createRef("CXXBoolLiteralExpr");
5538 case CXCursor_CXXNullPtrLiteralExpr:
5539 return cxstring::createRef("CXXNullPtrLiteralExpr");
5540 case CXCursor_CXXThisExpr:
5541 return cxstring::createRef("CXXThisExpr");
5542 case CXCursor_CXXThrowExpr:
5543 return cxstring::createRef("CXXThrowExpr");
5544 case CXCursor_CXXNewExpr:
5545 return cxstring::createRef("CXXNewExpr");
5546 case CXCursor_CXXDeleteExpr:
5547 return cxstring::createRef("CXXDeleteExpr");
5548 case CXCursor_UnaryExpr:
5549 return cxstring::createRef("UnaryExpr");
5550 case CXCursor_ObjCStringLiteral:
5551 return cxstring::createRef("ObjCStringLiteral");
5552 case CXCursor_ObjCBoolLiteralExpr:
5553 return cxstring::createRef("ObjCBoolLiteralExpr");
5554 case CXCursor_ObjCAvailabilityCheckExpr:
5555 return cxstring::createRef("ObjCAvailabilityCheckExpr");
5556 case CXCursor_ObjCSelfExpr:
5557 return cxstring::createRef("ObjCSelfExpr");
5558 case CXCursor_ObjCEncodeExpr:
5559 return cxstring::createRef("ObjCEncodeExpr");
5560 case CXCursor_ObjCSelectorExpr:
5561 return cxstring::createRef("ObjCSelectorExpr");
5562 case CXCursor_ObjCProtocolExpr:
5563 return cxstring::createRef("ObjCProtocolExpr");
5564 case CXCursor_ObjCBridgedCastExpr:
5565 return cxstring::createRef("ObjCBridgedCastExpr");
5566 case CXCursor_BlockExpr:
5567 return cxstring::createRef("BlockExpr");
5568 case CXCursor_PackExpansionExpr:
5569 return cxstring::createRef("PackExpansionExpr");
5570 case CXCursor_SizeOfPackExpr:
5571 return cxstring::createRef("SizeOfPackExpr");
5572 case CXCursor_LambdaExpr:
5573 return cxstring::createRef("LambdaExpr");
5574 case CXCursor_UnexposedExpr:
5575 return cxstring::createRef("UnexposedExpr");
5576 case CXCursor_DeclRefExpr:
5577 return cxstring::createRef("DeclRefExpr");
5578 case CXCursor_MemberRefExpr:
5579 return cxstring::createRef("MemberRefExpr");
5580 case CXCursor_CallExpr:
5581 return cxstring::createRef("CallExpr");
5582 case CXCursor_ObjCMessageExpr:
5583 return cxstring::createRef("ObjCMessageExpr");
5584 case CXCursor_BuiltinBitCastExpr:
5585 return cxstring::createRef("BuiltinBitCastExpr");
5586 case CXCursor_ConceptSpecializationExpr:
5587 return cxstring::createRef("ConceptSpecializationExpr");
5588 case CXCursor_RequiresExpr:
5589 return cxstring::createRef("RequiresExpr");
5590 case CXCursor_UnexposedStmt:
5591 return cxstring::createRef("UnexposedStmt");
5592 case CXCursor_DeclStmt:
5593 return cxstring::createRef("DeclStmt");
5594 case CXCursor_LabelStmt:
5595 return cxstring::createRef("LabelStmt");
5596 case CXCursor_CompoundStmt:
5597 return cxstring::createRef("CompoundStmt");
5598 case CXCursor_CaseStmt:
5599 return cxstring::createRef("CaseStmt");
5600 case CXCursor_DefaultStmt:
5601 return cxstring::createRef("DefaultStmt");
5602 case CXCursor_IfStmt:
5603 return cxstring::createRef("IfStmt");
5604 case CXCursor_SwitchStmt:
5605 return cxstring::createRef("SwitchStmt");
5606 case CXCursor_WhileStmt:
5607 return cxstring::createRef("WhileStmt");
5608 case CXCursor_DoStmt:
5609 return cxstring::createRef("DoStmt");
5610 case CXCursor_ForStmt:
5611 return cxstring::createRef("ForStmt");
5612 case CXCursor_GotoStmt:
5613 return cxstring::createRef("GotoStmt");
5614 case CXCursor_IndirectGotoStmt:
5615 return cxstring::createRef("IndirectGotoStmt");
5616 case CXCursor_ContinueStmt:
5617 return cxstring::createRef("ContinueStmt");
5618 case CXCursor_BreakStmt:
5619 return cxstring::createRef("BreakStmt");
5620 case CXCursor_ReturnStmt:
5621 return cxstring::createRef("ReturnStmt");
5622 case CXCursor_GCCAsmStmt:
5623 return cxstring::createRef("GCCAsmStmt");
5624 case CXCursor_MSAsmStmt:
5625 return cxstring::createRef("MSAsmStmt");
5626 case CXCursor_ObjCAtTryStmt:
5627 return cxstring::createRef("ObjCAtTryStmt");
5628 case CXCursor_ObjCAtCatchStmt:
5629 return cxstring::createRef("ObjCAtCatchStmt");
5630 case CXCursor_ObjCAtFinallyStmt:
5631 return cxstring::createRef("ObjCAtFinallyStmt");
5632 case CXCursor_ObjCAtThrowStmt:
5633 return cxstring::createRef("ObjCAtThrowStmt");
5634 case CXCursor_ObjCAtSynchronizedStmt:
5635 return cxstring::createRef("ObjCAtSynchronizedStmt");
5636 case CXCursor_ObjCAutoreleasePoolStmt:
5637 return cxstring::createRef("ObjCAutoreleasePoolStmt");
5638 case CXCursor_ObjCForCollectionStmt:
5639 return cxstring::createRef("ObjCForCollectionStmt");
5640 case CXCursor_CXXCatchStmt:
5641 return cxstring::createRef("CXXCatchStmt");
5642 case CXCursor_CXXTryStmt:
5643 return cxstring::createRef("CXXTryStmt");
5644 case CXCursor_CXXForRangeStmt:
5645 return cxstring::createRef("CXXForRangeStmt");
5646 case CXCursor_SEHTryStmt:
5647 return cxstring::createRef("SEHTryStmt");
5648 case CXCursor_SEHExceptStmt:
5649 return cxstring::createRef("SEHExceptStmt");
5650 case CXCursor_SEHFinallyStmt:
5651 return cxstring::createRef("SEHFinallyStmt");
5652 case CXCursor_SEHLeaveStmt:
5653 return cxstring::createRef("SEHLeaveStmt");
5654 case CXCursor_NullStmt:
5655 return cxstring::createRef("NullStmt");
5656 case CXCursor_InvalidFile:
5657 return cxstring::createRef("InvalidFile");
5658 case CXCursor_InvalidCode:
5659 return cxstring::createRef("InvalidCode");
5660 case CXCursor_NoDeclFound:
5661 return cxstring::createRef("NoDeclFound");
5662 case CXCursor_NotImplemented:
5663 return cxstring::createRef("NotImplemented");
5664 case CXCursor_TranslationUnit:
5665 return cxstring::createRef("TranslationUnit");
5666 case CXCursor_UnexposedAttr:
5667 return cxstring::createRef("UnexposedAttr");
5668 case CXCursor_IBActionAttr:
5669 return cxstring::createRef("attribute(ibaction)");
5670 case CXCursor_IBOutletAttr:
5671 return cxstring::createRef("attribute(iboutlet)");
5672 case CXCursor_IBOutletCollectionAttr:
5673 return cxstring::createRef("attribute(iboutletcollection)");
5674 case CXCursor_CXXFinalAttr:
5675 return cxstring::createRef("attribute(final)");
5676 case CXCursor_CXXOverrideAttr:
5677 return cxstring::createRef("attribute(override)");
5678 case CXCursor_AnnotateAttr:
5679 return cxstring::createRef("attribute(annotate)");
5680 case CXCursor_AsmLabelAttr:
5681 return cxstring::createRef("asm label");
5682 case CXCursor_PackedAttr:
5683 return cxstring::createRef("attribute(packed)");
5684 case CXCursor_PureAttr:
5685 return cxstring::createRef("attribute(pure)");
5686 case CXCursor_ConstAttr:
5687 return cxstring::createRef("attribute(const)");
5688 case CXCursor_NoDuplicateAttr:
5689 return cxstring::createRef("attribute(noduplicate)");
5690 case CXCursor_CUDAConstantAttr:
5691 return cxstring::createRef("attribute(constant)");
5692 case CXCursor_CUDADeviceAttr:
5693 return cxstring::createRef("attribute(device)");
5694 case CXCursor_CUDAGlobalAttr:
5695 return cxstring::createRef("attribute(global)");
5696 case CXCursor_CUDAHostAttr:
5697 return cxstring::createRef("attribute(host)");
5698 case CXCursor_CUDASharedAttr:
5699 return cxstring::createRef("attribute(shared)");
5700 case CXCursor_VisibilityAttr:
5701 return cxstring::createRef("attribute(visibility)");
5702 case CXCursor_DLLExport:
5703 return cxstring::createRef("attribute(dllexport)");
5704 case CXCursor_DLLImport:
5705 return cxstring::createRef("attribute(dllimport)");
5706 case CXCursor_NSReturnsRetained:
5707 return cxstring::createRef("attribute(ns_returns_retained)");
5708 case CXCursor_NSReturnsNotRetained:
5709 return cxstring::createRef("attribute(ns_returns_not_retained)");
5710 case CXCursor_NSReturnsAutoreleased:
5711 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5712 case CXCursor_NSConsumesSelf:
5713 return cxstring::createRef("attribute(ns_consumes_self)");
5714 case CXCursor_NSConsumed:
5715 return cxstring::createRef("attribute(ns_consumed)");
5716 case CXCursor_ObjCException:
5717 return cxstring::createRef("attribute(objc_exception)");
5718 case CXCursor_ObjCNSObject:
5719 return cxstring::createRef("attribute(NSObject)");
5720 case CXCursor_ObjCIndependentClass:
5721 return cxstring::createRef("attribute(objc_independent_class)");
5722 case CXCursor_ObjCPreciseLifetime:
5723 return cxstring::createRef("attribute(objc_precise_lifetime)");
5724 case CXCursor_ObjCReturnsInnerPointer:
5725 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5726 case CXCursor_ObjCRequiresSuper:
5727 return cxstring::createRef("attribute(objc_requires_super)");
5728 case CXCursor_ObjCRootClass:
5729 return cxstring::createRef("attribute(objc_root_class)");
5730 case CXCursor_ObjCSubclassingRestricted:
5731 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5732 case CXCursor_ObjCExplicitProtocolImpl:
5733 return cxstring::createRef(
5734 "attribute(objc_protocol_requires_explicit_implementation)");
5735 case CXCursor_ObjCDesignatedInitializer:
5736 return cxstring::createRef("attribute(objc_designated_initializer)");
5737 case CXCursor_ObjCRuntimeVisible:
5738 return cxstring::createRef("attribute(objc_runtime_visible)");
5739 case CXCursor_ObjCBoxable:
5740 return cxstring::createRef("attribute(objc_boxable)");
5741 case CXCursor_FlagEnum:
5742 return cxstring::createRef("attribute(flag_enum)");
5743 case CXCursor_PreprocessingDirective:
5744 return cxstring::createRef("preprocessing directive");
5745 case CXCursor_MacroDefinition:
5746 return cxstring::createRef("macro definition");
5747 case CXCursor_MacroExpansion:
5748 return cxstring::createRef("macro expansion");
5749 case CXCursor_InclusionDirective:
5750 return cxstring::createRef("inclusion directive");
5751 case CXCursor_Namespace:
5752 return cxstring::createRef("Namespace");
5753 case CXCursor_LinkageSpec:
5754 return cxstring::createRef("LinkageSpec");
5755 case CXCursor_CXXBaseSpecifier:
5756 return cxstring::createRef("C++ base class specifier");
5757 case CXCursor_Constructor:
5758 return cxstring::createRef("CXXConstructor");
5759 case CXCursor_Destructor:
5760 return cxstring::createRef("CXXDestructor");
5761 case CXCursor_ConversionFunction:
5762 return cxstring::createRef("CXXConversion");
5763 case CXCursor_TemplateTypeParameter:
5764 return cxstring::createRef("TemplateTypeParameter");
5765 case CXCursor_NonTypeTemplateParameter:
5766 return cxstring::createRef("NonTypeTemplateParameter");
5767 case CXCursor_TemplateTemplateParameter:
5768 return cxstring::createRef("TemplateTemplateParameter");
5769 case CXCursor_FunctionTemplate:
5770 return cxstring::createRef("FunctionTemplate");
5771 case CXCursor_ClassTemplate:
5772 return cxstring::createRef("ClassTemplate");
5773 case CXCursor_ClassTemplatePartialSpecialization:
5774 return cxstring::createRef("ClassTemplatePartialSpecialization");
5775 case CXCursor_NamespaceAlias:
5776 return cxstring::createRef("NamespaceAlias");
5777 case CXCursor_UsingDirective:
5778 return cxstring::createRef("UsingDirective");
5779 case CXCursor_UsingDeclaration:
5780 return cxstring::createRef("UsingDeclaration");
5781 case CXCursor_TypeAliasDecl:
5782 return cxstring::createRef("TypeAliasDecl");
5783 case CXCursor_ObjCSynthesizeDecl:
5784 return cxstring::createRef("ObjCSynthesizeDecl");
5785 case CXCursor_ObjCDynamicDecl:
5786 return cxstring::createRef("ObjCDynamicDecl");
5787 case CXCursor_CXXAccessSpecifier:
5788 return cxstring::createRef("CXXAccessSpecifier");
5789 case CXCursor_ModuleImportDecl:
5790 return cxstring::createRef("ModuleImport");
5791 case CXCursor_OMPCanonicalLoop:
5792 return cxstring::createRef("OMPCanonicalLoop");
5793 case CXCursor_OMPMetaDirective:
5794 return cxstring::createRef("OMPMetaDirective");
5795 case CXCursor_OMPParallelDirective:
5796 return cxstring::createRef("OMPParallelDirective");
5797 case CXCursor_OMPSimdDirective:
5798 return cxstring::createRef("OMPSimdDirective");
5799 case CXCursor_OMPTileDirective:
5800 return cxstring::createRef("OMPTileDirective");
5801 case CXCursor_OMPUnrollDirective:
5802 return cxstring::createRef("OMPUnrollDirective");
5803 case CXCursor_OMPForDirective:
5804 return cxstring::createRef("OMPForDirective");
5805 case CXCursor_OMPForSimdDirective:
5806 return cxstring::createRef("OMPForSimdDirective");
5807 case CXCursor_OMPSectionsDirective:
5808 return cxstring::createRef("OMPSectionsDirective");
5809 case CXCursor_OMPSectionDirective:
5810 return cxstring::createRef("OMPSectionDirective");
5811 case CXCursor_OMPSingleDirective:
5812 return cxstring::createRef("OMPSingleDirective");
5813 case CXCursor_OMPMasterDirective:
5814 return cxstring::createRef("OMPMasterDirective");
5815 case CXCursor_OMPCriticalDirective:
5816 return cxstring::createRef("OMPCriticalDirective");
5817 case CXCursor_OMPParallelForDirective:
5818 return cxstring::createRef("OMPParallelForDirective");
5819 case CXCursor_OMPParallelForSimdDirective:
5820 return cxstring::createRef("OMPParallelForSimdDirective");
5821 case CXCursor_OMPParallelMasterDirective:
5822 return cxstring::createRef("OMPParallelMasterDirective");
5823 case CXCursor_OMPParallelMaskedDirective:
5824 return cxstring::createRef("OMPParallelMaskedDirective");
5825 case CXCursor_OMPParallelSectionsDirective:
5826 return cxstring::createRef("OMPParallelSectionsDirective");
5827 case CXCursor_OMPTaskDirective:
5828 return cxstring::createRef("OMPTaskDirective");
5829 case CXCursor_OMPTaskyieldDirective:
5830 return cxstring::createRef("OMPTaskyieldDirective");
5831 case CXCursor_OMPBarrierDirective:
5832 return cxstring::createRef("OMPBarrierDirective");
5833 case CXCursor_OMPTaskwaitDirective:
5834 return cxstring::createRef("OMPTaskwaitDirective");
5835 case CXCursor_OMPErrorDirective:
5836 return cxstring::createRef("OMPErrorDirective");
5837 case CXCursor_OMPTaskgroupDirective:
5838 return cxstring::createRef("OMPTaskgroupDirective");
5839 case CXCursor_OMPFlushDirective:
5840 return cxstring::createRef("OMPFlushDirective");
5841 case CXCursor_OMPDepobjDirective:
5842 return cxstring::createRef("OMPDepobjDirective");
5843 case CXCursor_OMPScanDirective:
5844 return cxstring::createRef("OMPScanDirective");
5845 case CXCursor_OMPOrderedDirective:
5846 return cxstring::createRef("OMPOrderedDirective");
5847 case CXCursor_OMPAtomicDirective:
5848 return cxstring::createRef("OMPAtomicDirective");
5849 case CXCursor_OMPTargetDirective:
5850 return cxstring::createRef("OMPTargetDirective");
5851 case CXCursor_OMPTargetDataDirective:
5852 return cxstring::createRef("OMPTargetDataDirective");
5853 case CXCursor_OMPTargetEnterDataDirective:
5854 return cxstring::createRef("OMPTargetEnterDataDirective");
5855 case CXCursor_OMPTargetExitDataDirective:
5856 return cxstring::createRef("OMPTargetExitDataDirective");
5857 case CXCursor_OMPTargetParallelDirective:
5858 return cxstring::createRef("OMPTargetParallelDirective");
5859 case CXCursor_OMPTargetParallelForDirective:
5860 return cxstring::createRef("OMPTargetParallelForDirective");
5861 case CXCursor_OMPTargetUpdateDirective:
5862 return cxstring::createRef("OMPTargetUpdateDirective");
5863 case CXCursor_OMPTeamsDirective:
5864 return cxstring::createRef("OMPTeamsDirective");
5865 case CXCursor_OMPCancellationPointDirective:
5866 return cxstring::createRef("OMPCancellationPointDirective");
5867 case CXCursor_OMPCancelDirective:
5868 return cxstring::createRef("OMPCancelDirective");
5869 case CXCursor_OMPTaskLoopDirective:
5870 return cxstring::createRef("OMPTaskLoopDirective");
5871 case CXCursor_OMPTaskLoopSimdDirective:
5872 return cxstring::createRef("OMPTaskLoopSimdDirective");
5873 case CXCursor_OMPMasterTaskLoopDirective:
5874 return cxstring::createRef("OMPMasterTaskLoopDirective");
5875 case CXCursor_OMPMaskedTaskLoopDirective:
5876 return cxstring::createRef("OMPMaskedTaskLoopDirective");
5877 case CXCursor_OMPMasterTaskLoopSimdDirective:
5878 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
5879 case CXCursor_OMPMaskedTaskLoopSimdDirective:
5880 return cxstring::createRef("OMPMaskedTaskLoopSimdDirective");
5881 case CXCursor_OMPParallelMasterTaskLoopDirective:
5882 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
5883 case CXCursor_OMPParallelMaskedTaskLoopDirective:
5884 return cxstring::createRef("OMPParallelMaskedTaskLoopDirective");
5885 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5886 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
5887 case CXCursor_OMPParallelMaskedTaskLoopSimdDirective:
5888 return cxstring::createRef("OMPParallelMaskedTaskLoopSimdDirective");
5889 case CXCursor_OMPDistributeDirective:
5890 return cxstring::createRef("OMPDistributeDirective");
5891 case CXCursor_OMPDistributeParallelForDirective:
5892 return cxstring::createRef("OMPDistributeParallelForDirective");
5893 case CXCursor_OMPDistributeParallelForSimdDirective:
5894 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
5895 case CXCursor_OMPDistributeSimdDirective:
5896 return cxstring::createRef("OMPDistributeSimdDirective");
5897 case CXCursor_OMPTargetParallelForSimdDirective:
5898 return cxstring::createRef("OMPTargetParallelForSimdDirective");
5899 case CXCursor_OMPTargetSimdDirective:
5900 return cxstring::createRef("OMPTargetSimdDirective");
5901 case CXCursor_OMPTeamsDistributeDirective:
5902 return cxstring::createRef("OMPTeamsDistributeDirective");
5903 case CXCursor_OMPTeamsDistributeSimdDirective:
5904 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
5905 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5906 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
5907 case CXCursor_OMPTeamsDistributeParallelForDirective:
5908 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
5909 case CXCursor_OMPTargetTeamsDirective:
5910 return cxstring::createRef("OMPTargetTeamsDirective");
5911 case CXCursor_OMPTargetTeamsDistributeDirective:
5912 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
5913 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5914 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
5915 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5916 return cxstring::createRef(
5917 "OMPTargetTeamsDistributeParallelForSimdDirective");
5918 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5919 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
5920 case CXCursor_OMPInteropDirective:
5921 return cxstring::createRef("OMPInteropDirective");
5922 case CXCursor_OMPDispatchDirective:
5923 return cxstring::createRef("OMPDispatchDirective");
5924 case CXCursor_OMPMaskedDirective:
5925 return cxstring::createRef("OMPMaskedDirective");
5926 case CXCursor_OMPGenericLoopDirective:
5927 return cxstring::createRef("OMPGenericLoopDirective");
5928 case CXCursor_OMPTeamsGenericLoopDirective:
5929 return cxstring::createRef("OMPTeamsGenericLoopDirective");
5930 case CXCursor_OMPTargetTeamsGenericLoopDirective:
5931 return cxstring::createRef("OMPTargetTeamsGenericLoopDirective");
5932 case CXCursor_OMPParallelGenericLoopDirective:
5933 return cxstring::createRef("OMPParallelGenericLoopDirective");
5934 case CXCursor_OMPTargetParallelGenericLoopDirective:
5935 return cxstring::createRef("OMPTargetParallelGenericLoopDirective");
5936 case CXCursor_OverloadCandidate:
5937 return cxstring::createRef("OverloadCandidate");
5938 case CXCursor_TypeAliasTemplateDecl:
5939 return cxstring::createRef("TypeAliasTemplateDecl");
5940 case CXCursor_StaticAssert:
5941 return cxstring::createRef("StaticAssert");
5942 case CXCursor_FriendDecl:
5943 return cxstring::createRef("FriendDecl");
5944 case CXCursor_ConvergentAttr:
5945 return cxstring::createRef("attribute(convergent)");
5946 case CXCursor_WarnUnusedAttr:
5947 return cxstring::createRef("attribute(warn_unused)");
5948 case CXCursor_WarnUnusedResultAttr:
5949 return cxstring::createRef("attribute(warn_unused_result)");
5950 case CXCursor_AlignedAttr:
5951 return cxstring::createRef("attribute(aligned)");
5952 case CXCursor_ConceptDecl:
5953 return cxstring::createRef("ConceptDecl");
5954 }
5955
5956 llvm_unreachable("Unhandled CXCursorKind")::llvm::llvm_unreachable_internal("Unhandled CXCursorKind", "clang/tools/libclang/CIndex.cpp"
, 5956)
;
5957}
5958
5959struct GetCursorData {
5960 SourceLocation TokenBeginLoc;
5961 bool PointsAtMacroArgExpansion;
5962 bool VisitedObjCPropertyImplDecl;
5963 SourceLocation VisitedDeclaratorDeclStartLoc;
5964 CXCursor &BestCursor;
5965
5966 GetCursorData(SourceManager &SM, SourceLocation tokenBegin,
5967 CXCursor &outputCursor)
5968 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5969 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5970 VisitedObjCPropertyImplDecl = false;
5971 }
5972};
5973
5974static enum CXChildVisitResult
5975GetCursorVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
5976 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5977 CXCursor *BestCursor = &Data->BestCursor;
5978
5979 // If we point inside a macro argument we should provide info of what the
5980 // token is so use the actual cursor, don't replace it with a macro expansion
5981 // cursor.
5982 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5983 return CXChildVisit_Recurse;
5984
5985 if (clang_isDeclaration(cursor.kind)) {
5986 // Avoid having the implicit methods override the property decls.
5987 if (const ObjCMethodDecl *MD =
5988 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5989 if (MD->isImplicit())
5990 return CXChildVisit_Break;
5991
5992 } else if (const ObjCInterfaceDecl *ID =
5993 dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5994 // Check that when we have multiple @class references in the same line,
5995 // that later ones do not override the previous ones.
5996 // If we have:
5997 // @class Foo, Bar;
5998 // source ranges for both start at '@', so 'Bar' will end up overriding
5999 // 'Foo' even though the cursor location was at 'Foo'.
6000 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
6001 BestCursor->kind == CXCursor_ObjCClassRef)
6002 if (const ObjCInterfaceDecl *PrevID =
6003 dyn_cast_or_null<ObjCInterfaceDecl>(
6004 getCursorDecl(*BestCursor))) {
6005 if (PrevID != ID && !PrevID->isThisDeclarationADefinition() &&
6006 !ID->isThisDeclarationADefinition())
6007 return CXChildVisit_Break;
6008 }
6009
6010 } else if (const DeclaratorDecl *DD =
6011 dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
6012 SourceLocation StartLoc = DD->getSourceRange().getBegin();
6013 // Check that when we have multiple declarators in the same line,
6014 // that later ones do not override the previous ones.
6015 // If we have:
6016 // int Foo, Bar;
6017 // source ranges for both start at 'int', so 'Bar' will end up overriding
6018 // 'Foo' even though the cursor location was at 'Foo'.
6019 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)