blob: 62dc0e2b8f926516e3712612ef59904399b5a432 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the main API hooks in the Clang-C Source Indexing
10// library.
11//
12//===----------------------------------------------------------------------===//
13
Guy Benyei11169dd2012-12-18 14:30:41 +000014#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000015#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000016#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#include "CXCursor.h"
18#include "CXSourceLocation.h"
19#include "CXString.h"
20#include "CXTranslationUnit.h"
21#include "CXType.h"
22#include "CursorVisitor.h"
Jan Korousf7d23762019-09-12 22:55:55 +000023#include "clang-c/FatalErrorHandler.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Jan Korous7e36ecd2019-09-05 20:33:52 +000025#include "clang/AST/Mangle.h"
Alexey Bataev95598342020-02-10 15:49:05 -050026#include "clang/AST/OpenMPClause.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/AST/StmtVisitor.h"
28#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000029#include "clang/Basic/DiagnosticCategories.h"
30#include "clang/Basic/DiagnosticIDs.h"
Richard Smith0a7b2972018-07-03 21:34:13 +000031#include "clang/Basic/Stack.h"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000032#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000033#include "clang/Basic/Version.h"
34#include "clang/Frontend/ASTUnit.h"
35#include "clang/Frontend/CompilerInstance.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000036#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "clang/Lex/HeaderSearch.h"
38#include "clang/Lex/Lexer.h"
39#include "clang/Lex/PreprocessingRecord.h"
40#include "clang/Lex/Preprocessor.h"
41#include "llvm/ADT/Optional.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000044#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "llvm/Support/Compiler.h"
46#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000047#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000048#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/Support/MemoryBuffer.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "llvm/Support/Program.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000053#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000054#include "llvm/Support/Threading.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/raw_ostream.h"
Benjamin Kramer762bc332019-08-07 14:44:40 +000057#include <mutex>
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000058
Alp Toker1a86ad22014-07-06 06:24:00 +000059#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
60#define USE_DARWIN_THREADS
61#endif
62
63#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000064#include <pthread.h>
65#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000066
67using namespace clang;
68using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000069using namespace clang::cxtu;
70using namespace clang::cxindex;
71
David Blaikieea4395e2017-01-06 19:49:01 +000072CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
73 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000074 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000075 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000076 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000077 CXTranslationUnit D = new CXTranslationUnitImpl();
78 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000079 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000080 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000081 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000082 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000083 D->CommentToXML = nullptr;
Alex Lorenz690f0e22017-12-07 20:37:50 +000084 D->ParsingOptions = 0;
85 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000086 return D;
87}
88
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000089bool cxtu::isASTReadError(ASTUnit *AU) {
90 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
91 DEnd = AU->stored_diag_end();
92 D != DEnd; ++D) {
93 if (D->getLevel() >= DiagnosticsEngine::Error &&
94 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
95 diag::DiagCat_AST_Deserialization_Issue)
96 return true;
97 }
98 return false;
99}
100
Guy Benyei11169dd2012-12-18 14:30:41 +0000101cxtu::CXTUOwner::~CXTUOwner() {
102 if (TU)
103 clang_disposeTranslationUnit(TU);
104}
105
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000106/// Compare two source ranges to determine their relative position in
Guy Benyei11169dd2012-12-18 14:30:41 +0000107/// the translation unit.
108static RangeComparisonResult RangeCompare(SourceManager &SM,
109 SourceRange R1,
110 SourceRange R2) {
111 assert(R1.isValid() && "First range is invalid?");
112 assert(R2.isValid() && "Second range is invalid?");
113 if (R1.getEnd() != R2.getBegin() &&
114 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
115 return RangeBefore;
116 if (R2.getEnd() != R1.getBegin() &&
117 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
118 return RangeAfter;
119 return RangeOverlap;
120}
121
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000122/// Determine if a source location falls within, before, or after a
Guy Benyei11169dd2012-12-18 14:30:41 +0000123/// a given source range.
124static RangeComparisonResult LocationCompare(SourceManager &SM,
125 SourceLocation L, SourceRange R) {
126 assert(R.isValid() && "First range is invalid?");
127 assert(L.isValid() && "Second range is invalid?");
128 if (L == R.getBegin() || L == R.getEnd())
129 return RangeOverlap;
130 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
131 return RangeBefore;
132 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
133 return RangeAfter;
134 return RangeOverlap;
135}
136
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000137/// Translate a Clang source range into a CIndex source range.
Guy Benyei11169dd2012-12-18 14:30:41 +0000138///
139/// Clang internally represents ranges where the end location points to the
140/// start of the token at the end. However, for external clients it is more
141/// useful to have a CXSourceRange be a proper half-open interval. This routine
142/// does the appropriate translation.
143CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
144 const LangOptions &LangOpts,
145 const CharSourceRange &R) {
146 // We want the last character in this location, so we will adjust the
147 // location accordingly.
148 SourceLocation EndLoc = R.getEnd();
Richard Smithb5f81712018-04-30 05:25:48 +0000149 bool IsTokenRange = R.isTokenRange();
150 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
151 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
152 EndLoc = Expansion.getEnd();
153 IsTokenRange = Expansion.isTokenRange();
154 }
155 if (IsTokenRange && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000156 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
157 SM, LangOpts);
158 EndLoc = EndLoc.getLocWithOffset(Length);
159 }
160
Bill Wendlingeade3622013-01-23 08:25:41 +0000161 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000162 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000163 R.getBegin().getRawEncoding(),
164 EndLoc.getRawEncoding()
165 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000166 return Result;
167}
168
169//===----------------------------------------------------------------------===//
170// Cursor visitor.
171//===----------------------------------------------------------------------===//
172
173static SourceRange getRawCursorExtent(CXCursor C);
174static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
175
Guy Benyei11169dd2012-12-18 14:30:41 +0000176RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
177 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
178}
179
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000180/// Visit the given cursor and, if requested by the visitor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000181/// its children.
182///
183/// \param Cursor the cursor to visit.
184///
185/// \param CheckedRegionOfInterest if true, then the caller already checked
186/// that this cursor is within the region of interest.
187///
188/// \returns true if the visitation should be aborted, false if it
189/// should continue.
190bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
191 if (clang_isInvalid(Cursor.kind))
192 return false;
193
194 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000195 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000196 if (!D) {
197 assert(0 && "Invalid declaration cursor");
198 return true; // abort.
199 }
200
201 // Ignore implicit declarations, unless it's an objc method because
202 // currently we should report implicit methods for properties when indexing.
203 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
204 return false;
205 }
206
207 // If we have a range of interest, and this cursor doesn't intersect with it,
208 // we're done.
209 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
210 SourceRange Range = getRawCursorExtent(Cursor);
211 if (Range.isInvalid() || CompareRegionOfInterest(Range))
212 return false;
213 }
214
215 switch (Visitor(Cursor, Parent, ClientData)) {
216 case CXChildVisit_Break:
217 return true;
218
219 case CXChildVisit_Continue:
220 return false;
221
222 case CXChildVisit_Recurse: {
223 bool ret = VisitChildren(Cursor);
224 if (PostChildrenVisitor)
225 if (PostChildrenVisitor(Cursor, ClientData))
226 return true;
227 return ret;
228 }
229 }
230
231 llvm_unreachable("Invalid CXChildVisitResult!");
232}
233
234static bool visitPreprocessedEntitiesInRange(SourceRange R,
235 PreprocessingRecord &PPRec,
236 CursorVisitor &Visitor) {
237 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
238 FileID FID;
239
240 if (!Visitor.shouldVisitIncludedEntities()) {
241 // If the begin/end of the range lie in the same FileID, do the optimization
242 // where we skip preprocessed entities that do not come from the same FileID.
243 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
244 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
245 FID = FileID();
246 }
247
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000248 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
249 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000250 PPRec, FID);
251}
252
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000253bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000254 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000255 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000256
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000257 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000258 SourceManager &SM = Unit->getSourceManager();
259
260 std::pair<FileID, unsigned>
261 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
262 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
263
264 if (End.first != Begin.first) {
265 // If the end does not reside in the same file, try to recover by
266 // picking the end of the file of begin location.
267 End.first = Begin.first;
268 End.second = SM.getFileIDSize(Begin.first);
269 }
270
271 assert(Begin.first == End.first);
272 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000273 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000274
275 FileID File = Begin.first;
276 unsigned Offset = Begin.second;
277 unsigned Length = End.second - Begin.second;
278
279 if (!VisitDeclsOnly && !VisitPreprocessorLast)
280 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000281 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000282
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000283 if (visitDeclsFromFileRegion(File, Offset, Length))
284 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000285
286 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000287 return visitPreprocessedEntitiesInRegion();
288
289 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000290}
291
292static bool isInLexicalContext(Decl *D, DeclContext *DC) {
293 if (!DC)
294 return false;
295
296 for (DeclContext *DeclDC = D->getLexicalDeclContext();
297 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
298 if (DeclDC == DC)
299 return true;
300 }
301 return false;
302}
303
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000304bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000305 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000306 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000307 SourceManager &SM = Unit->getSourceManager();
308 SourceRange Range = RegionOfInterest;
309
310 SmallVector<Decl *, 16> Decls;
311 Unit->findFileRegionDecls(File, Offset, Length, Decls);
312
313 // If we didn't find any file level decls for the file, try looking at the
314 // file that it was included from.
315 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
316 bool Invalid = false;
317 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
318 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000319 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000320
321 SourceLocation Outer;
322 if (SLEntry.isFile())
323 Outer = SLEntry.getFile().getIncludeLoc();
324 else
325 Outer = SLEntry.getExpansion().getExpansionLocStart();
326 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000327 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000328
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000329 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000330 Length = 0;
331 Unit->findFileRegionDecls(File, Offset, Length, Decls);
332 }
333
334 assert(!Decls.empty());
335
336 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000337 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000338 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
339 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000340 Decl *D = *DIt;
341 if (D->getSourceRange().isInvalid())
342 continue;
343
344 if (isInLexicalContext(D, CurDC))
345 continue;
346
347 CurDC = dyn_cast<DeclContext>(D);
348
349 if (TagDecl *TD = dyn_cast<TagDecl>(D))
350 if (!TD->isFreeStanding())
351 continue;
352
353 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
354 if (CompRes == RangeBefore)
355 continue;
356 if (CompRes == RangeAfter)
357 break;
358
359 assert(CompRes == RangeOverlap);
360 VisitedAtLeastOnce = true;
361
362 if (isa<ObjCContainerDecl>(D)) {
363 FileDI_current = &DIt;
364 FileDE_current = DE;
365 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000366 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000367 }
368
369 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000370 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000371 }
372
373 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000374 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000375
376 // No Decls overlapped with the range. Move up the lexical context until there
377 // is a context that contains the range or we reach the translation unit
378 // level.
379 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
380 : (*(DIt-1))->getLexicalDeclContext();
381
382 while (DC && !DC->isTranslationUnit()) {
383 Decl *D = cast<Decl>(DC);
384 SourceRange CurDeclRange = D->getSourceRange();
385 if (CurDeclRange.isInvalid())
386 break;
387
388 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000389 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
390 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000391 }
392
393 DC = D->getLexicalDeclContext();
394 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000395
396 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000397}
398
399bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
400 if (!AU->getPreprocessor().getPreprocessingRecord())
401 return false;
402
403 PreprocessingRecord &PPRec
404 = *AU->getPreprocessor().getPreprocessingRecord();
405 SourceManager &SM = AU->getSourceManager();
406
407 if (RegionOfInterest.isValid()) {
408 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
409 SourceLocation B = MappedRange.getBegin();
410 SourceLocation E = MappedRange.getEnd();
411
412 if (AU->isInPreambleFileID(B)) {
413 if (SM.isLoadedSourceLocation(E))
414 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
415 PPRec, *this);
416
417 // Beginning of range lies in the preamble but it also extends beyond
418 // it into the main file. Split the range into 2 parts, one covering
419 // the preamble and another covering the main file. This allows subsequent
420 // calls to visitPreprocessedEntitiesInRange to accept a source range that
421 // lies in the same FileID, allowing it to skip preprocessed entities that
422 // do not come from the same FileID.
423 bool breaked =
424 visitPreprocessedEntitiesInRange(
425 SourceRange(B, AU->getEndOfPreambleFileID()),
426 PPRec, *this);
427 if (breaked) return true;
428 return visitPreprocessedEntitiesInRange(
429 SourceRange(AU->getStartOfMainFileID(), E),
430 PPRec, *this);
431 }
432
433 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
434 }
435
436 bool OnlyLocalDecls
437 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
438
439 if (OnlyLocalDecls)
440 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
441 PPRec);
442
443 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
444}
445
446template<typename InputIterator>
447bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
448 InputIterator Last,
449 PreprocessingRecord &PPRec,
450 FileID FID) {
451 for (; First != Last; ++First) {
452 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
453 continue;
454
455 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000456 if (!PPE)
457 continue;
458
Guy Benyei11169dd2012-12-18 14:30:41 +0000459 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
460 if (Visit(MakeMacroExpansionCursor(ME, TU)))
461 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000462
Guy Benyei11169dd2012-12-18 14:30:41 +0000463 continue;
464 }
Richard Smith66a81862015-05-04 02:25:31 +0000465
466 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000467 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
468 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000469
Guy Benyei11169dd2012-12-18 14:30:41 +0000470 continue;
471 }
472
473 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
474 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
475 return true;
476
477 continue;
478 }
479 }
480
481 return false;
482}
483
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000484/// Visit the children of the given cursor.
Guy Benyei11169dd2012-12-18 14:30:41 +0000485///
486/// \returns true if the visitation should be aborted, false if it
487/// should continue.
488bool CursorVisitor::VisitChildren(CXCursor Cursor) {
489 if (clang_isReference(Cursor.kind) &&
490 Cursor.kind != CXCursor_CXXBaseSpecifier) {
491 // By definition, references have no children.
492 return false;
493 }
494
495 // Set the Parent field to Cursor, then back to its old value once we're
496 // done.
497 SetParentRAII SetParent(Parent, StmtParent, Cursor);
498
499 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000500 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000501 if (!D)
502 return false;
503
504 return VisitAttributes(D) || Visit(D);
505 }
506
507 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000508 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 return Visit(S);
510
511 return false;
512 }
513
514 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000515 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000516 return Visit(E);
517
518 return false;
519 }
520
521 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000522 CXTranslationUnit TU = getCursorTU(Cursor);
523 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000524
525 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
526 for (unsigned I = 0; I != 2; ++I) {
527 if (VisitOrder[I]) {
528 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
529 RegionOfInterest.isInvalid()) {
530 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
531 TLEnd = CXXUnit->top_level_end();
532 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000533 const Optional<bool> V = handleDeclForVisitation(*TL);
534 if (!V.hasValue())
535 continue;
536 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000537 }
538 } else if (VisitDeclContext(
539 CXXUnit->getASTContext().getTranslationUnitDecl()))
540 return true;
541 continue;
542 }
543
544 // Walk the preprocessing record.
545 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
546 visitPreprocessedEntitiesInRegion();
547 }
548
549 return false;
550 }
551
552 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000553 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000554 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
555 return Visit(BaseTSInfo->getTypeLoc());
556 }
557 }
558 }
559
560 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000561 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000562 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000563 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000564 return Visit(cxcursor::MakeCursorObjCClassRef(
565 ObjT->getInterface(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000566 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 }
568
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000569 // If pointing inside a macro definition, check if the token is an identifier
570 // that was ever defined as a macro. In such a case, create a "pseudo" macro
571 // expansion cursor for that token.
572 SourceLocation BeginLoc = RegionOfInterest.getBegin();
573 if (Cursor.kind == CXCursor_MacroDefinition &&
574 BeginLoc == RegionOfInterest.getEnd()) {
575 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000576 const MacroInfo *MI =
577 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000578 if (MacroDefinitionRecord *MacroDef =
579 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000580 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
581 }
582
Guy Benyei11169dd2012-12-18 14:30:41 +0000583 // Nothing to visit at the moment.
584 return false;
585}
586
587bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
588 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
589 if (Visit(TSInfo->getTypeLoc()))
590 return true;
591
592 if (Stmt *Body = B->getBody())
593 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
594
595 return false;
596}
597
Ted Kremenek03325582013-02-21 01:29:01 +0000598Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000599 if (RegionOfInterest.isValid()) {
600 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
601 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000602 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000603
604 switch (CompareRegionOfInterest(Range)) {
605 case RangeBefore:
606 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000607 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000608
609 case RangeAfter:
610 // This declaration comes after the region of interest; we're done.
611 return false;
612
613 case RangeOverlap:
614 // This declaration overlaps the region of interest; visit it.
615 break;
616 }
617 }
618 return true;
619}
620
621bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
622 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
623
624 // FIXME: Eventually remove. This part of a hack to support proper
625 // iteration over all Decls contained lexically within an ObjC container.
626 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
627 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
628
629 for ( ; I != E; ++I) {
630 Decl *D = *I;
631 if (D->getLexicalDeclContext() != DC)
632 continue;
Adrian Prantl2073dd22019-11-04 14:28:14 -0800633 // Filter out synthesized property accessor redeclarations.
634 if (isa<ObjCImplDecl>(DC))
635 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
636 if (OMD->isSynthesizedAccessorStub())
637 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000638 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 if (!V.hasValue())
640 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000641 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000642 }
643 return false;
644}
645
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000646Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
647 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
648
649 // Ignore synthesized ivars here, otherwise if we have something like:
650 // @synthesize prop = _prop;
651 // and '_prop' is not declared, we will encounter a '_prop' ivar before
652 // encountering the 'prop' synthesize declaration and we will think that
653 // we passed the region-of-interest.
654 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
655 if (ivarD->getSynthesize())
656 return None;
657 }
658
659 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
660 // declarations is a mismatch with the compiler semantics.
661 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
662 auto *ID = cast<ObjCInterfaceDecl>(D);
663 if (!ID->isThisDeclarationADefinition())
664 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
665
666 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
667 auto *PD = cast<ObjCProtocolDecl>(D);
668 if (!PD->isThisDeclarationADefinition())
669 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
670 }
671
672 const Optional<bool> V = shouldVisitCursor(Cursor);
673 if (!V.hasValue())
674 return None;
675 if (!V.getValue())
676 return false;
677 if (Visit(Cursor, true))
678 return true;
679 return None;
680}
681
Guy Benyei11169dd2012-12-18 14:30:41 +0000682bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
683 llvm_unreachable("Translation units are visited directly by Visit()");
684}
685
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000686bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
687 if (VisitTemplateParameters(D->getTemplateParameters()))
688 return true;
689
690 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
691}
692
Guy Benyei11169dd2012-12-18 14:30:41 +0000693bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
694 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
695 return Visit(TSInfo->getTypeLoc());
696
697 return false;
698}
699
700bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
701 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
702 return Visit(TSInfo->getTypeLoc());
703
704 return false;
705}
706
707bool CursorVisitor::VisitTagDecl(TagDecl *D) {
708 return VisitDeclContext(D);
709}
710
711bool CursorVisitor::VisitClassTemplateSpecializationDecl(
712 ClassTemplateSpecializationDecl *D) {
713 bool ShouldVisitBody = false;
714 switch (D->getSpecializationKind()) {
715 case TSK_Undeclared:
716 case TSK_ImplicitInstantiation:
717 // Nothing to visit
718 return false;
719
720 case TSK_ExplicitInstantiationDeclaration:
721 case TSK_ExplicitInstantiationDefinition:
722 break;
723
724 case TSK_ExplicitSpecialization:
725 ShouldVisitBody = true;
726 break;
727 }
728
729 // Visit the template arguments used in the specialization.
730 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
731 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000732 if (TemplateSpecializationTypeLoc TSTLoc =
733 TL.getAs<TemplateSpecializationTypeLoc>()) {
734 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
735 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000736 return true;
737 }
738 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000739
740 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000741}
742
743bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
744 ClassTemplatePartialSpecializationDecl *D) {
745 // FIXME: Visit the "outer" template parameter lists on the TagDecl
746 // before visiting these template parameters.
747 if (VisitTemplateParameters(D->getTemplateParameters()))
748 return true;
749
750 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000751 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
752 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
753 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000754 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
755 return true;
756
757 return VisitCXXRecordDecl(D);
758}
759
760bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Saar Razff1e0fc2020-01-15 02:48:42 +0200761 if (const auto *TC = D->getTypeConstraint())
762 if (Visit(MakeCXCursor(TC->getImmediatelyDeclaredConstraint(), StmtParent,
763 TU, RegionOfInterest)))
764 return true;
765
Guy Benyei11169dd2012-12-18 14:30:41 +0000766 // Visit the default argument.
767 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
768 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
769 if (Visit(DefArg->getTypeLoc()))
770 return true;
771
772 return false;
773}
774
775bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
776 if (Expr *Init = D->getInitExpr())
777 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
778 return false;
779}
780
781bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000782 unsigned NumParamList = DD->getNumTemplateParameterLists();
783 for (unsigned i = 0; i < NumParamList; i++) {
784 TemplateParameterList* Params = DD->getTemplateParameterList(i);
785 if (VisitTemplateParameters(Params))
786 return true;
787 }
788
Guy Benyei11169dd2012-12-18 14:30:41 +0000789 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
790 if (Visit(TSInfo->getTypeLoc()))
791 return true;
792
793 // Visit the nested-name-specifier, if present.
794 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
795 if (VisitNestedNameSpecifierLoc(QualifierLoc))
796 return true;
797
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000798 return false;
799}
800
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000801static bool HasTrailingReturnType(FunctionDecl *ND) {
802 const QualType Ty = ND->getType();
803 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
804 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
805 return FT->hasTrailingReturn();
806 }
807
808 return false;
809}
810
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000811/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000812static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
813 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000814 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
815}
816
Guy Benyei11169dd2012-12-18 14:30:41 +0000817bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000818 unsigned NumParamList = ND->getNumTemplateParameterLists();
819 for (unsigned i = 0; i < NumParamList; i++) {
820 TemplateParameterList* Params = ND->getTemplateParameterList(i);
821 if (VisitTemplateParameters(Params))
822 return true;
823 }
824
Guy Benyei11169dd2012-12-18 14:30:41 +0000825 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
826 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000827 // written. This requires a bit of work.
828 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
829 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000830 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000831
832 // If we have a function declared directly (without the use of a typedef),
833 // visit just the return type. Otherwise, just visit the function's type
834 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000835 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
836 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000837 (!FTL && Visit(TL)))
838 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000839
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000840 // Visit the nested-name-specifier, if present.
841 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
842 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000843 return true;
844
845 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000846 if (!isa<CXXDestructorDecl>(ND))
847 if (VisitDeclarationNameInfo(ND->getNameInfo()))
848 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000849
850 // FIXME: Visit explicitly-specified template arguments!
851
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000852 // Visit the function parameters, if we have a function type.
853 if (FTL && VisitFunctionTypeLoc(FTL, true))
854 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000855
856 // Visit the function's trailing return type.
857 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
858 return true;
859
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000860 // FIXME: Attributes?
861 }
862
Guy Benyei11169dd2012-12-18 14:30:41 +0000863 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
864 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
865 // Find the initializers that were written in the source.
866 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000867 for (auto *I : Constructor->inits()) {
868 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000869 continue;
870
Aaron Ballman0ad78302014-03-13 17:34:31 +0000871 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000872 }
873
874 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000875 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
876 &CompareCXXCtorInitializers);
877
Guy Benyei11169dd2012-12-18 14:30:41 +0000878 // Visit the initializers in source order
879 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
880 CXXCtorInitializer *Init = WrittenInits[I];
881 if (Init->isAnyMemberInitializer()) {
882 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
883 Init->getMemberLocation(), TU)))
884 return true;
885 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
886 if (Visit(TInfo->getTypeLoc()))
887 return true;
888 }
889
890 // Visit the initializer value.
891 if (Expr *Initializer = Init->getInit())
892 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
893 return true;
894 }
895 }
896
897 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
898 return true;
899 }
900
901 return false;
902}
903
904bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
905 if (VisitDeclaratorDecl(D))
906 return true;
907
908 if (Expr *BitWidth = D->getBitWidth())
909 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
910
Benjamin Kramer99f97592017-11-15 12:20:41 +0000911 if (Expr *Init = D->getInClassInitializer())
912 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
913
Guy Benyei11169dd2012-12-18 14:30:41 +0000914 return false;
915}
916
917bool CursorVisitor::VisitVarDecl(VarDecl *D) {
918 if (VisitDeclaratorDecl(D))
919 return true;
920
921 if (Expr *Init = D->getInit())
922 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
923
924 return false;
925}
926
927bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
928 if (VisitDeclaratorDecl(D))
929 return true;
930
931 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
932 if (Expr *DefArg = D->getDefaultArgument())
933 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
934
935 return false;
936}
937
938bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
939 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
940 // before visiting these template parameters.
941 if (VisitTemplateParameters(D->getTemplateParameters()))
942 return true;
943
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000944 auto* FD = D->getTemplatedDecl();
945 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000946}
947
948bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
949 // FIXME: Visit the "outer" template parameter lists on the TagDecl
950 // before visiting these template parameters.
951 if (VisitTemplateParameters(D->getTemplateParameters()))
952 return true;
953
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000954 auto* CD = D->getTemplatedDecl();
955 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000956}
957
958bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
959 if (VisitTemplateParameters(D->getTemplateParameters()))
960 return true;
961
962 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
963 VisitTemplateArgumentLoc(D->getDefaultArgument()))
964 return true;
965
966 return false;
967}
968
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000969bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
970 // Visit the bound, if it's explicit.
971 if (D->hasExplicitBound()) {
972 if (auto TInfo = D->getTypeSourceInfo()) {
973 if (Visit(TInfo->getTypeLoc()))
974 return true;
975 }
976 }
977
978 return false;
979}
980
Guy Benyei11169dd2012-12-18 14:30:41 +0000981bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000982 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 if (Visit(TSInfo->getTypeLoc()))
984 return true;
985
David Majnemer59f77922016-06-24 04:05:48 +0000986 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000987 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000988 return true;
989 }
990
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000991 return ND->isThisDeclarationADefinition() &&
992 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000993}
994
995template <typename DeclIt>
996static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
997 SourceManager &SM, SourceLocation EndLoc,
998 SmallVectorImpl<Decl *> &Decls) {
999 DeclIt next = *DI_current;
1000 while (++next != DE_current) {
1001 Decl *D_next = *next;
1002 if (!D_next)
1003 break;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001004 SourceLocation L = D_next->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00001005 if (!L.isValid())
1006 break;
1007 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1008 *DI_current = next;
1009 Decls.push_back(D_next);
1010 continue;
1011 }
1012 break;
1013 }
1014}
1015
Guy Benyei11169dd2012-12-18 14:30:41 +00001016bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1017 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1018 // an @implementation can lexically contain Decls that are not properly
1019 // nested in the AST. When we identify such cases, we need to retrofit
1020 // this nesting here.
1021 if (!DI_current && !FileDI_current)
1022 return VisitDeclContext(D);
1023
1024 // Scan the Decls that immediately come after the container
1025 // in the current DeclContext. If any fall within the
1026 // container's lexical region, stash them into a vector
1027 // for later processing.
1028 SmallVector<Decl *, 24> DeclsInContainer;
1029 SourceLocation EndLoc = D->getSourceRange().getEnd();
1030 SourceManager &SM = AU->getSourceManager();
1031 if (EndLoc.isValid()) {
1032 if (DI_current) {
1033 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1034 DeclsInContainer);
1035 } else {
1036 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1037 DeclsInContainer);
1038 }
1039 }
1040
1041 // The common case.
1042 if (DeclsInContainer.empty())
1043 return VisitDeclContext(D);
1044
1045 // Get all the Decls in the DeclContext, and sort them with the
1046 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001047 for (auto *SubDecl : D->decls()) {
1048 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001049 SubDecl->getBeginLoc().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001050 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001051 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001052 }
1053
1054 // Now sort the Decls so that they appear in lexical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001055 llvm::sort(DeclsInContainer,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001056 [&SM](Decl *A, Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001057 SourceLocation L_A = A->getBeginLoc();
1058 SourceLocation L_B = B->getBeginLoc();
1059 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001060 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1061 B->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001062 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001063
1064 // Now visit the decls.
1065 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1066 E = DeclsInContainer.end(); I != E; ++I) {
1067 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001068 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001069 if (!V.hasValue())
1070 continue;
1071 if (!V.getValue())
1072 return false;
1073 if (Visit(Cursor, true))
1074 return true;
1075 }
1076 return false;
1077}
1078
1079bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1080 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1081 TU)))
1082 return true;
1083
Douglas Gregore9d95f12015-07-07 03:57:35 +00001084 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1085 return true;
1086
Guy Benyei11169dd2012-12-18 14:30:41 +00001087 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1088 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1089 E = ND->protocol_end(); I != E; ++I, ++PL)
1090 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1091 return true;
1092
1093 return VisitObjCContainerDecl(ND);
1094}
1095
1096bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1097 if (!PID->isThisDeclarationADefinition())
1098 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1099
1100 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1101 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1102 E = PID->protocol_end(); I != E; ++I, ++PL)
1103 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1104 return true;
1105
1106 return VisitObjCContainerDecl(PID);
1107}
1108
1109bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1110 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1111 return true;
1112
1113 // FIXME: This implements a workaround with @property declarations also being
1114 // installed in the DeclContext for the @interface. Eventually this code
1115 // should be removed.
1116 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1117 if (!CDecl || !CDecl->IsClassExtension())
1118 return false;
1119
1120 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1121 if (!ID)
1122 return false;
1123
1124 IdentifierInfo *PropertyId = PD->getIdentifier();
1125 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001126 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1127 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001128
1129 if (!prevDecl)
1130 return false;
1131
1132 // Visit synthesized methods since they will be skipped when visiting
1133 // the @interface.
1134 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1135 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1136 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1137 return true;
1138
1139 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1140 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1141 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1142 return true;
1143
1144 return false;
1145}
1146
Douglas Gregore9d95f12015-07-07 03:57:35 +00001147bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1148 if (!typeParamList)
1149 return false;
1150
1151 for (auto *typeParam : *typeParamList) {
1152 // Visit the type parameter.
1153 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1154 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001155 }
1156
1157 return false;
1158}
1159
Guy Benyei11169dd2012-12-18 14:30:41 +00001160bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1161 if (!D->isThisDeclarationADefinition()) {
1162 // Forward declaration is treated like a reference.
1163 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1164 }
1165
Douglas Gregore9d95f12015-07-07 03:57:35 +00001166 // Objective-C type parameters.
1167 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1168 return true;
1169
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 // Issue callbacks for super class.
1171 if (D->getSuperClass() &&
1172 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1173 D->getSuperClassLoc(),
1174 TU)))
1175 return true;
1176
Douglas Gregore9d95f12015-07-07 03:57:35 +00001177 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1178 if (Visit(SuperClassTInfo->getTypeLoc()))
1179 return true;
1180
Guy Benyei11169dd2012-12-18 14:30:41 +00001181 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1182 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1183 E = D->protocol_end(); I != E; ++I, ++PL)
1184 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1185 return true;
1186
1187 return VisitObjCContainerDecl(D);
1188}
1189
1190bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1191 return VisitObjCContainerDecl(D);
1192}
1193
1194bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1195 // 'ID' could be null when dealing with invalid code.
1196 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1197 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1198 return true;
1199
1200 return VisitObjCImplDecl(D);
1201}
1202
1203bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1204#if 0
1205 // Issue callbacks for super class.
1206 // FIXME: No source location information!
1207 if (D->getSuperClass() &&
1208 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1209 D->getSuperClassLoc(),
1210 TU)))
1211 return true;
1212#endif
1213
1214 return VisitObjCImplDecl(D);
1215}
1216
1217bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1218 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1219 if (PD->isIvarNameSpecified())
1220 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1221
1222 return false;
1223}
1224
1225bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1226 return VisitDeclContext(D);
1227}
1228
1229bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1230 // Visit nested-name-specifier.
1231 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1232 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1233 return true;
1234
1235 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1236 D->getTargetNameLoc(), TU));
1237}
1238
1239bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1240 // Visit nested-name-specifier.
1241 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1242 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1243 return true;
1244 }
1245
1246 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1247 return true;
1248
1249 return VisitDeclarationNameInfo(D->getNameInfo());
1250}
1251
1252bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1253 // Visit nested-name-specifier.
1254 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1255 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1256 return true;
1257
1258 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1259 D->getIdentLocation(), TU));
1260}
1261
1262bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1263 // Visit nested-name-specifier.
1264 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1265 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1266 return true;
1267 }
1268
1269 return VisitDeclarationNameInfo(D->getNameInfo());
1270}
1271
1272bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1273 UnresolvedUsingTypenameDecl *D) {
1274 // Visit nested-name-specifier.
1275 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1276 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1277 return true;
1278
1279 return false;
1280}
1281
Olivier Goffart81978012016-06-09 16:15:55 +00001282bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1283 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1284 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001285 if (StringLiteral *Message = D->getMessage())
1286 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1287 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001288 return false;
1289}
1290
Olivier Goffartd211c642016-11-04 06:29:27 +00001291bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1292 if (NamedDecl *FriendD = D->getFriendDecl()) {
1293 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1294 return true;
1295 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1296 if (Visit(TI->getTypeLoc()))
1297 return true;
1298 }
1299 return false;
1300}
1301
Guy Benyei11169dd2012-12-18 14:30:41 +00001302bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1303 switch (Name.getName().getNameKind()) {
1304 case clang::DeclarationName::Identifier:
1305 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001306 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001307 case clang::DeclarationName::CXXOperatorName:
1308 case clang::DeclarationName::CXXUsingDirective:
1309 return false;
Richard Smith35845152017-02-07 01:37:30 +00001310
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 case clang::DeclarationName::CXXConstructorName:
1312 case clang::DeclarationName::CXXDestructorName:
1313 case clang::DeclarationName::CXXConversionFunctionName:
1314 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1315 return Visit(TSInfo->getTypeLoc());
1316 return false;
1317
1318 case clang::DeclarationName::ObjCZeroArgSelector:
1319 case clang::DeclarationName::ObjCOneArgSelector:
1320 case clang::DeclarationName::ObjCMultiArgSelector:
1321 // FIXME: Per-identifier location info?
1322 return false;
1323 }
1324
1325 llvm_unreachable("Invalid DeclarationName::Kind!");
1326}
1327
1328bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1329 SourceRange Range) {
1330 // FIXME: This whole routine is a hack to work around the lack of proper
1331 // source information in nested-name-specifiers (PR5791). Since we do have
1332 // a beginning source location, we can visit the first component of the
1333 // nested-name-specifier, if it's a single-token component.
1334 if (!NNS)
1335 return false;
1336
1337 // Get the first component in the nested-name-specifier.
1338 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1339 NNS = Prefix;
1340
1341 switch (NNS->getKind()) {
1342 case NestedNameSpecifier::Namespace:
1343 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1344 TU));
1345
1346 case NestedNameSpecifier::NamespaceAlias:
1347 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1348 Range.getBegin(), TU));
1349
1350 case NestedNameSpecifier::TypeSpec: {
1351 // If the type has a form where we know that the beginning of the source
1352 // range matches up with a reference cursor. Visit the appropriate reference
1353 // cursor.
1354 const Type *T = NNS->getAsType();
1355 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1356 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1357 if (const TagType *Tag = dyn_cast<TagType>(T))
1358 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1359 if (const TemplateSpecializationType *TST
1360 = dyn_cast<TemplateSpecializationType>(T))
1361 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1362 break;
1363 }
1364
1365 case NestedNameSpecifier::TypeSpecWithTemplate:
1366 case NestedNameSpecifier::Global:
1367 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001368 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 break;
1370 }
1371
1372 return false;
1373}
1374
1375bool
1376CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1377 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1378 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1379 Qualifiers.push_back(Qualifier);
1380
1381 while (!Qualifiers.empty()) {
1382 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1383 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1384 switch (NNS->getKind()) {
1385 case NestedNameSpecifier::Namespace:
1386 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1387 Q.getLocalBeginLoc(),
1388 TU)))
1389 return true;
1390
1391 break;
1392
1393 case NestedNameSpecifier::NamespaceAlias:
1394 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1395 Q.getLocalBeginLoc(),
1396 TU)))
1397 return true;
1398
1399 break;
1400
1401 case NestedNameSpecifier::TypeSpec:
1402 case NestedNameSpecifier::TypeSpecWithTemplate:
1403 if (Visit(Q.getTypeLoc()))
1404 return true;
1405
1406 break;
1407
1408 case NestedNameSpecifier::Global:
1409 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001410 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 break;
1412 }
1413 }
1414
1415 return false;
1416}
1417
1418bool CursorVisitor::VisitTemplateParameters(
1419 const TemplateParameterList *Params) {
1420 if (!Params)
1421 return false;
1422
1423 for (TemplateParameterList::const_iterator P = Params->begin(),
1424 PEnd = Params->end();
1425 P != PEnd; ++P) {
1426 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1427 return true;
1428 }
1429
1430 return false;
1431}
1432
1433bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1434 switch (Name.getKind()) {
1435 case TemplateName::Template:
1436 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1437
1438 case TemplateName::OverloadedTemplate:
1439 // Visit the overloaded template set.
1440 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1441 return true;
1442
1443 return false;
1444
Richard Smithb23c5e82019-05-09 03:31:27 +00001445 case TemplateName::AssumedTemplate:
1446 // FIXME: Visit DeclarationName?
1447 return false;
1448
Guy Benyei11169dd2012-12-18 14:30:41 +00001449 case TemplateName::DependentTemplate:
1450 // FIXME: Visit nested-name-specifier.
1451 return false;
1452
1453 case TemplateName::QualifiedTemplate:
1454 // FIXME: Visit nested-name-specifier.
1455 return Visit(MakeCursorTemplateRef(
1456 Name.getAsQualifiedTemplateName()->getDecl(),
1457 Loc, TU));
1458
1459 case TemplateName::SubstTemplateTemplateParm:
1460 return Visit(MakeCursorTemplateRef(
1461 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1462 Loc, TU));
1463
1464 case TemplateName::SubstTemplateTemplateParmPack:
1465 return Visit(MakeCursorTemplateRef(
1466 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1467 Loc, TU));
1468 }
1469
1470 llvm_unreachable("Invalid TemplateName::Kind!");
1471}
1472
1473bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1474 switch (TAL.getArgument().getKind()) {
1475 case TemplateArgument::Null:
1476 case TemplateArgument::Integral:
1477 case TemplateArgument::Pack:
1478 return false;
1479
1480 case TemplateArgument::Type:
1481 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1482 return Visit(TSInfo->getTypeLoc());
1483 return false;
1484
1485 case TemplateArgument::Declaration:
1486 if (Expr *E = TAL.getSourceDeclExpression())
1487 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1488 return false;
1489
1490 case TemplateArgument::NullPtr:
1491 if (Expr *E = TAL.getSourceNullPtrExpression())
1492 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1493 return false;
1494
1495 case TemplateArgument::Expression:
1496 if (Expr *E = TAL.getSourceExpression())
1497 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1498 return false;
1499
1500 case TemplateArgument::Template:
1501 case TemplateArgument::TemplateExpansion:
1502 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1503 return true;
1504
1505 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1506 TAL.getTemplateNameLoc());
1507 }
1508
1509 llvm_unreachable("Invalid TemplateArgument::Kind!");
1510}
1511
1512bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1513 return VisitDeclContext(D);
1514}
1515
1516bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1517 return Visit(TL.getUnqualifiedLoc());
1518}
1519
1520bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1521 ASTContext &Context = AU->getASTContext();
1522
1523 // Some builtin types (such as Objective-C's "id", "sel", and
1524 // "Class") have associated declarations. Create cursors for those.
1525 QualType VisitType;
1526 switch (TL.getTypePtr()->getKind()) {
1527
1528 case BuiltinType::Void:
1529 case BuiltinType::NullPtr:
1530 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001531#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1532 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001533#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001534#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1535 case BuiltinType::Id:
1536#include "clang/Basic/OpenCLExtensionTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001537 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001538 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001539 case BuiltinType::OCLClkEvent:
1540 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001541 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00001542#define SVE_TYPE(Name, Id, SingletonId) \
1543 case BuiltinType::Id:
1544#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00001545#define BUILTIN_TYPE(Id, SingletonId)
1546#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1547#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1548#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1549#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1550#include "clang/AST/BuiltinTypes.def"
1551 break;
1552
1553 case BuiltinType::ObjCId:
1554 VisitType = Context.getObjCIdType();
1555 break;
1556
1557 case BuiltinType::ObjCClass:
1558 VisitType = Context.getObjCClassType();
1559 break;
1560
1561 case BuiltinType::ObjCSel:
1562 VisitType = Context.getObjCSelType();
1563 break;
1564 }
1565
1566 if (!VisitType.isNull()) {
1567 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1568 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1569 TU));
1570 }
1571
1572 return false;
1573}
1574
1575bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1576 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1577}
1578
1579bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1580 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1581}
1582
1583bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1584 if (TL.isDefinition())
1585 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1586
1587 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1588}
1589
1590bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1591 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1592}
1593
1594bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001595 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001596}
1597
Manman Rene6be26c2016-09-13 17:25:08 +00001598bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001599 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001600 return true;
1601 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1602 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1603 TU)))
1604 return true;
1605 }
1606
1607 return false;
1608}
1609
Guy Benyei11169dd2012-12-18 14:30:41 +00001610bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1611 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1612 return true;
1613
Douglas Gregore9d95f12015-07-07 03:57:35 +00001614 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1615 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1616 return true;
1617 }
1618
Guy Benyei11169dd2012-12-18 14:30:41 +00001619 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1620 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1621 TU)))
1622 return true;
1623 }
1624
1625 return false;
1626}
1627
1628bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1629 return Visit(TL.getPointeeLoc());
1630}
1631
1632bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1633 return Visit(TL.getInnerLoc());
1634}
1635
Leonard Chanc72aaf62019-05-07 03:20:17 +00001636bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
1637 return Visit(TL.getInnerLoc());
1638}
1639
Guy Benyei11169dd2012-12-18 14:30:41 +00001640bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1641 return Visit(TL.getPointeeLoc());
1642}
1643
1644bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1645 return Visit(TL.getPointeeLoc());
1646}
1647
1648bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1649 return Visit(TL.getPointeeLoc());
1650}
1651
1652bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1653 return Visit(TL.getPointeeLoc());
1654}
1655
1656bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1657 return Visit(TL.getPointeeLoc());
1658}
1659
1660bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1661 return Visit(TL.getModifiedLoc());
1662}
1663
1664bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1665 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001666 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001667 return true;
1668
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001669 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1670 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1672 return true;
1673
1674 return false;
1675}
1676
1677bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1678 if (Visit(TL.getElementLoc()))
1679 return true;
1680
1681 if (Expr *Size = TL.getSizeExpr())
1682 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1683
1684 return false;
1685}
1686
Reid Kleckner8a365022013-06-24 17:51:48 +00001687bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1688 return Visit(TL.getOriginalLoc());
1689}
1690
Reid Kleckner0503a872013-12-05 01:23:43 +00001691bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1692 return Visit(TL.getOriginalLoc());
1693}
1694
Richard Smith600b5262017-01-26 20:40:47 +00001695bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1696 DeducedTemplateSpecializationTypeLoc TL) {
1697 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1698 TL.getTemplateNameLoc()))
1699 return true;
1700
1701 return false;
1702}
1703
Guy Benyei11169dd2012-12-18 14:30:41 +00001704bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1705 TemplateSpecializationTypeLoc TL) {
1706 // Visit the template name.
1707 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1708 TL.getTemplateNameLoc()))
1709 return true;
1710
1711 // Visit the template arguments.
1712 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1713 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1714 return true;
1715
1716 return false;
1717}
1718
1719bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1720 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1721}
1722
1723bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1724 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1725 return Visit(TSInfo->getTypeLoc());
1726
1727 return false;
1728}
1729
1730bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1731 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1732 return Visit(TSInfo->getTypeLoc());
1733
1734 return false;
1735}
1736
1737bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001738 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001739}
1740
1741bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1742 DependentTemplateSpecializationTypeLoc TL) {
1743 // Visit the nested-name-specifier, if there is one.
1744 if (TL.getQualifierLoc() &&
1745 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1746 return true;
1747
1748 // Visit the template arguments.
1749 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1750 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1751 return true;
1752
1753 return false;
1754}
1755
1756bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1757 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1758 return true;
1759
1760 return Visit(TL.getNamedTypeLoc());
1761}
1762
1763bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1764 return Visit(TL.getPatternLoc());
1765}
1766
1767bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1768 if (Expr *E = TL.getUnderlyingExpr())
1769 return Visit(MakeCXCursor(E, StmtParent, TU));
1770
1771 return false;
1772}
1773
1774bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1775 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1776}
1777
1778bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1779 return Visit(TL.getValueLoc());
1780}
1781
Xiuli Pan9c14e282016-01-09 12:53:17 +00001782bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1783 return Visit(TL.getValueLoc());
1784}
1785
Guy Benyei11169dd2012-12-18 14:30:41 +00001786#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1787bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1788 return Visit##PARENT##Loc(TL); \
1789}
1790
1791DEFAULT_TYPELOC_IMPL(Complex, Type)
1792DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1793DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1794DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1795DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001796DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001797DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001798DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1799DEFAULT_TYPELOC_IMPL(Vector, Type)
1800DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1801DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1802DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1803DEFAULT_TYPELOC_IMPL(Record, TagType)
1804DEFAULT_TYPELOC_IMPL(Enum, TagType)
1805DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1806DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1807DEFAULT_TYPELOC_IMPL(Auto, Type)
1808
1809bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1810 // Visit the nested-name-specifier, if present.
1811 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1812 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1813 return true;
1814
1815 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001816 for (const auto &I : D->bases()) {
1817 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001818 return true;
1819 }
1820 }
1821
1822 return VisitTagDecl(D);
1823}
1824
1825bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001826 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001827 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1828 !I->isImplicit()) &&
1829 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001830 return true;
1831
1832 return false;
1833}
1834
1835//===----------------------------------------------------------------------===//
1836// Data-recursive visitor methods.
1837//===----------------------------------------------------------------------===//
1838
1839namespace {
1840#define DEF_JOB(NAME, DATA, KIND)\
1841class NAME : public VisitorJob {\
1842public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001843 NAME(const DATA *d, CXCursor parent) : \
1844 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001845 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001846 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001847};
1848
1849DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1850DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1851DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1852DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001853DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1854DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1855DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1856#undef DEF_JOB
1857
James Y Knight04ec5bf2015-12-24 02:59:37 +00001858class ExplicitTemplateArgsVisit : public VisitorJob {
1859public:
1860 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1861 const TemplateArgumentLoc *End, CXCursor parent)
1862 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1863 End) {}
1864 static bool classof(const VisitorJob *VJ) {
1865 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1866 }
1867 const TemplateArgumentLoc *begin() const {
1868 return static_cast<const TemplateArgumentLoc *>(data[0]);
1869 }
1870 const TemplateArgumentLoc *end() {
1871 return static_cast<const TemplateArgumentLoc *>(data[1]);
1872 }
1873};
Guy Benyei11169dd2012-12-18 14:30:41 +00001874class DeclVisit : public VisitorJob {
1875public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001876 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001877 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001878 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 static bool classof(const VisitorJob *VJ) {
1880 return VJ->getKind() == DeclVisitKind;
1881 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001882 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001883 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001884};
1885class TypeLocVisit : public VisitorJob {
1886public:
1887 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1888 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1889 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1890
1891 static bool classof(const VisitorJob *VJ) {
1892 return VJ->getKind() == TypeLocVisitKind;
1893 }
1894
1895 TypeLoc get() const {
1896 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001897 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001898 }
1899};
1900
1901class LabelRefVisit : public VisitorJob {
1902public:
1903 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1904 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1905 labelLoc.getPtrEncoding()) {}
1906
1907 static bool classof(const VisitorJob *VJ) {
1908 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1909 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001910 const LabelDecl *get() const {
1911 return static_cast<const LabelDecl *>(data[0]);
1912 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001913 SourceLocation getLoc() const {
1914 return SourceLocation::getFromPtrEncoding(data[1]); }
1915};
1916
1917class NestedNameSpecifierLocVisit : public VisitorJob {
1918public:
1919 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1920 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1921 Qualifier.getNestedNameSpecifier(),
1922 Qualifier.getOpaqueData()) { }
1923
1924 static bool classof(const VisitorJob *VJ) {
1925 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1926 }
1927
1928 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001929 return NestedNameSpecifierLoc(
1930 const_cast<NestedNameSpecifier *>(
1931 static_cast<const NestedNameSpecifier *>(data[0])),
1932 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001933 }
1934};
1935
1936class DeclarationNameInfoVisit : public VisitorJob {
1937public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001938 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001939 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001940 static bool classof(const VisitorJob *VJ) {
1941 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1942 }
1943 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001944 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001945 switch (S->getStmtClass()) {
1946 default:
1947 llvm_unreachable("Unhandled Stmt");
1948 case clang::Stmt::MSDependentExistsStmtClass:
1949 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1950 case Stmt::CXXDependentScopeMemberExprClass:
1951 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1952 case Stmt::DependentScopeDeclRefExprClass:
1953 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001954 case Stmt::OMPCriticalDirectiveClass:
1955 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001956 }
1957 }
1958};
1959class MemberRefVisit : public VisitorJob {
1960public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001961 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001962 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1963 L.getPtrEncoding()) {}
1964 static bool classof(const VisitorJob *VJ) {
1965 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1966 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001967 const FieldDecl *get() const {
1968 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001969 }
1970 SourceLocation getLoc() const {
1971 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1972 }
1973};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001974class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001975 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001976 VisitorWorkList &WL;
1977 CXCursor Parent;
1978public:
1979 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1980 : WL(wl), Parent(parent) {}
1981
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001982 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1983 void VisitBlockExpr(const BlockExpr *B);
1984 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1985 void VisitCompoundStmt(const CompoundStmt *S);
1986 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1987 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1988 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1989 void VisitCXXNewExpr(const CXXNewExpr *E);
1990 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1991 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1992 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1993 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1994 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1995 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1996 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1997 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001998 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001999 void VisitDeclRefExpr(const DeclRefExpr *D);
2000 void VisitDeclStmt(const DeclStmt *S);
2001 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
2002 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
2003 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
2004 void VisitForStmt(const ForStmt *FS);
2005 void VisitGotoStmt(const GotoStmt *GS);
2006 void VisitIfStmt(const IfStmt *If);
2007 void VisitInitListExpr(const InitListExpr *IE);
2008 void VisitMemberExpr(const MemberExpr *M);
2009 void VisitOffsetOfExpr(const OffsetOfExpr *E);
2010 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
2011 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
2012 void VisitOverloadExpr(const OverloadExpr *E);
2013 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
2014 void VisitStmt(const Stmt *S);
2015 void VisitSwitchStmt(const SwitchStmt *S);
2016 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002017 void VisitTypeTraitExpr(const TypeTraitExpr *E);
2018 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
2019 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
2020 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2021 void VisitVAArgExpr(const VAArgExpr *E);
2022 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2023 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2024 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2025 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002026 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002027 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002028 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002029 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002030 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002031 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002032 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002033 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002034 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002035 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002036 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002037 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002038 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
cchen47d60942019-12-05 13:43:48 -05002039 void VisitOMPParallelMasterDirective(const OMPParallelMasterDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002040 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002041 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002042 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002043 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002044 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002045 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002046 void
2047 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002048 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002049 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataevc112e942020-02-28 09:52:15 -05002050 void VisitOMPDepobjDirective(const OMPDepobjDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002051 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002052 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002053 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002054 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002055 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002056 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002057 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002058 void
2059 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002060 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002061 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002062 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Alexey Bataev60e51c42019-10-10 20:13:02 +00002063 void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002064 void
2065 VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D);
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002066 void VisitOMPParallelMasterTaskLoopDirective(
2067 const OMPParallelMasterTaskLoopDirective *D);
Alexey Bataev14a388f2019-10-25 10:27:13 -04002068 void VisitOMPParallelMasterTaskLoopSimdDirective(
2069 const OMPParallelMasterTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002070 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002071 void VisitOMPDistributeParallelForDirective(
2072 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002073 void VisitOMPDistributeParallelForSimdDirective(
2074 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002075 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002076 void VisitOMPTargetParallelForSimdDirective(
2077 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002078 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002079 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002080 void VisitOMPTeamsDistributeSimdDirective(
2081 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002082 void VisitOMPTeamsDistributeParallelForSimdDirective(
2083 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002084 void VisitOMPTeamsDistributeParallelForDirective(
2085 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002086 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002087 void VisitOMPTargetTeamsDistributeDirective(
2088 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002089 void VisitOMPTargetTeamsDistributeParallelForDirective(
2090 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002091 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2092 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002093 void VisitOMPTargetTeamsDistributeSimdDirective(
2094 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002095
Guy Benyei11169dd2012-12-18 14:30:41 +00002096private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002097 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002099 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2100 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002101 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2102 void AddStmt(const Stmt *S);
2103 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002105 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002106 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002107};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002108} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002109
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002110void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 // 'S' should always be non-null, since it comes from the
2112 // statement we are visiting.
2113 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2114}
2115
2116void
2117EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2118 if (Qualifier)
2119 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2120}
2121
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002122void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002123 if (S)
2124 WL.push_back(StmtVisit(S, Parent));
2125}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002126void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 if (D)
2128 WL.push_back(DeclVisit(D, Parent, isFirst));
2129}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002130void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2131 unsigned NumTemplateArgs) {
2132 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002133}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002134void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002135 if (D)
2136 WL.push_back(MemberRefVisit(D, L, Parent));
2137}
2138void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2139 if (TI)
2140 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2141 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002142void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002143 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002144 for (const Stmt *SubStmt : S->children()) {
2145 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 }
2147 if (size == WL.size())
2148 return;
2149 // Now reverse the entries we just added. This will match the DFS
2150 // ordering performed by the worklist.
2151 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2152 std::reverse(I, E);
2153}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002154namespace {
2155class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2156 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002157 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002158 template <typename T>
2159 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002160public:
2161 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2162#define OPENMP_CLAUSE(Name, Class) \
2163 void Visit##Class(const Class *C);
2164#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002165 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002166 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002167};
2168
Alexey Bataev3392d762016-02-16 11:18:12 +00002169void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2170 const OMPClauseWithPreInit *C) {
2171 Visitor->AddStmt(C->getPreInitStmt());
2172}
2173
Alexey Bataev005248a2016-02-25 05:25:57 +00002174void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2175 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002176 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002177 Visitor->AddStmt(C->getPostUpdateExpr());
2178}
2179
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002180void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002181 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002182 Visitor->AddStmt(C->getCondition());
2183}
2184
Alexey Bataev3778b602014-07-17 07:32:53 +00002185void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2186 Visitor->AddStmt(C->getCondition());
2187}
2188
Alexey Bataev568a8332014-03-06 06:15:19 +00002189void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002190 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002191 Visitor->AddStmt(C->getNumThreads());
2192}
2193
Alexey Bataev62c87d22014-03-21 04:51:18 +00002194void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2195 Visitor->AddStmt(C->getSafelen());
2196}
2197
Alexey Bataev66b15b52015-08-21 11:14:16 +00002198void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2199 Visitor->AddStmt(C->getSimdlen());
2200}
2201
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002202void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2203 Visitor->AddStmt(C->getAllocator());
2204}
2205
Alexander Musman8bd31e62014-05-27 15:12:19 +00002206void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2207 Visitor->AddStmt(C->getNumForLoops());
2208}
2209
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002210void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002211
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002212void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2213
Alexey Bataev56dafe82014-06-20 07:16:17 +00002214void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002215 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002216 Visitor->AddStmt(C->getChunkSize());
2217}
2218
Alexey Bataev10e775f2015-07-30 11:36:16 +00002219void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2220 Visitor->AddStmt(C->getNumForLoops());
2221}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002222
Alexey Bataev236070f2014-06-20 11:19:47 +00002223void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2224
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002225void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2226
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002227void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2228
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002229void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2230
Alexey Bataevdea47612014-07-23 07:46:59 +00002231void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2232
Alexey Bataev67a4f222014-07-23 10:25:33 +00002233void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2234
Alexey Bataev459dec02014-07-24 06:46:57 +00002235void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2236
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002237void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2238
Alexey Bataevea9166b2020-02-06 16:30:23 -05002239void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
2240
Alexey Bataev04a830f2020-02-10 14:30:39 -05002241void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {}
2242
Alexey Bataev95598342020-02-10 15:49:05 -05002243void OMPClauseEnqueue::VisitOMPReleaseClause(const OMPReleaseClause *) {}
2244
Alexey Bataev9a8defc2020-02-11 11:10:43 -05002245void OMPClauseEnqueue::VisitOMPRelaxedClause(const OMPRelaxedClause *) {}
2246
Alexey Bataev346265e2015-09-25 10:37:12 +00002247void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2248
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002249void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2250
Alexey Bataevb825de12015-12-07 10:51:44 +00002251void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2252
Alexey Bataev375437a2020-03-02 14:21:20 -05002253void OMPClauseEnqueue::VisitOMPDestroyClause(const OMPDestroyClause *) {}
2254
Kelvin Li1408f912018-09-26 04:28:39 +00002255void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2256 const OMPUnifiedAddressClause *) {}
2257
Patrick Lyster4a370b92018-10-01 13:47:43 +00002258void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2259 const OMPUnifiedSharedMemoryClause *) {}
2260
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002261void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2262 const OMPReverseOffloadClause *) {}
2263
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002264void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2265 const OMPDynamicAllocatorsClause *) {}
2266
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002267void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2268 const OMPAtomicDefaultMemOrderClause *) {}
2269
Michael Wonge710d542015-08-07 16:16:36 +00002270void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2271 Visitor->AddStmt(C->getDevice());
2272}
2273
Kelvin Li099bb8c2015-11-24 20:50:12 +00002274void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002275 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002276 Visitor->AddStmt(C->getNumTeams());
2277}
2278
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002279void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002280 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002281 Visitor->AddStmt(C->getThreadLimit());
2282}
2283
Alexey Bataeva0569352015-12-01 10:17:31 +00002284void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2285 Visitor->AddStmt(C->getPriority());
2286}
2287
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002288void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2289 Visitor->AddStmt(C->getGrainsize());
2290}
2291
Alexey Bataev382967a2015-12-08 12:06:20 +00002292void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2293 Visitor->AddStmt(C->getNumTasks());
2294}
2295
Alexey Bataev28c75412015-12-15 08:19:24 +00002296void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2297 Visitor->AddStmt(C->getHint());
2298}
2299
Alexey Bataev756c1962013-09-24 03:17:45 +00002300template<typename T>
2301void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002302 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002303 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002304 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002305}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002306
Alexey Bataeve04483e2019-03-27 14:14:31 +00002307void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2308 VisitOMPClauseList(C);
2309 Visitor->AddStmt(C->getAllocator());
2310}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002311void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002312 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002313 for (const auto *E : C->private_copies()) {
2314 Visitor->AddStmt(E);
2315 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002316}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002317void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2318 const OMPFirstprivateClause *C) {
2319 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002320 VisitOMPClauseWithPreInit(C);
2321 for (const auto *E : C->private_copies()) {
2322 Visitor->AddStmt(E);
2323 }
2324 for (const auto *E : C->inits()) {
2325 Visitor->AddStmt(E);
2326 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002327}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002328void OMPClauseEnqueue::VisitOMPLastprivateClause(
2329 const OMPLastprivateClause *C) {
2330 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002331 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002332 for (auto *E : C->private_copies()) {
2333 Visitor->AddStmt(E);
2334 }
2335 for (auto *E : C->source_exprs()) {
2336 Visitor->AddStmt(E);
2337 }
2338 for (auto *E : C->destination_exprs()) {
2339 Visitor->AddStmt(E);
2340 }
2341 for (auto *E : C->assignment_ops()) {
2342 Visitor->AddStmt(E);
2343 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002344}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002345void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002346 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002347}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002348void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2349 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002350 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002351 for (auto *E : C->privates()) {
2352 Visitor->AddStmt(E);
2353 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002354 for (auto *E : C->lhs_exprs()) {
2355 Visitor->AddStmt(E);
2356 }
2357 for (auto *E : C->rhs_exprs()) {
2358 Visitor->AddStmt(E);
2359 }
2360 for (auto *E : C->reduction_ops()) {
2361 Visitor->AddStmt(E);
2362 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002363}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002364void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2365 const OMPTaskReductionClause *C) {
2366 VisitOMPClauseList(C);
2367 VisitOMPClauseWithPostUpdate(C);
2368 for (auto *E : C->privates()) {
2369 Visitor->AddStmt(E);
2370 }
2371 for (auto *E : C->lhs_exprs()) {
2372 Visitor->AddStmt(E);
2373 }
2374 for (auto *E : C->rhs_exprs()) {
2375 Visitor->AddStmt(E);
2376 }
2377 for (auto *E : C->reduction_ops()) {
2378 Visitor->AddStmt(E);
2379 }
2380}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002381void OMPClauseEnqueue::VisitOMPInReductionClause(
2382 const OMPInReductionClause *C) {
2383 VisitOMPClauseList(C);
2384 VisitOMPClauseWithPostUpdate(C);
2385 for (auto *E : C->privates()) {
2386 Visitor->AddStmt(E);
2387 }
2388 for (auto *E : C->lhs_exprs()) {
2389 Visitor->AddStmt(E);
2390 }
2391 for (auto *E : C->rhs_exprs()) {
2392 Visitor->AddStmt(E);
2393 }
2394 for (auto *E : C->reduction_ops()) {
2395 Visitor->AddStmt(E);
2396 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002397 for (auto *E : C->taskgroup_descriptors())
2398 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002399}
Alexander Musman8dba6642014-04-22 13:09:42 +00002400void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2401 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002402 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002403 for (const auto *E : C->privates()) {
2404 Visitor->AddStmt(E);
2405 }
Alexander Musman3276a272015-03-21 10:12:56 +00002406 for (const auto *E : C->inits()) {
2407 Visitor->AddStmt(E);
2408 }
2409 for (const auto *E : C->updates()) {
2410 Visitor->AddStmt(E);
2411 }
2412 for (const auto *E : C->finals()) {
2413 Visitor->AddStmt(E);
2414 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002415 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002416 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002417}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002418void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2419 VisitOMPClauseList(C);
2420 Visitor->AddStmt(C->getAlignment());
2421}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002422void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2423 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002424 for (auto *E : C->source_exprs()) {
2425 Visitor->AddStmt(E);
2426 }
2427 for (auto *E : C->destination_exprs()) {
2428 Visitor->AddStmt(E);
2429 }
2430 for (auto *E : C->assignment_ops()) {
2431 Visitor->AddStmt(E);
2432 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002433}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002434void
2435OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2436 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002437 for (auto *E : C->source_exprs()) {
2438 Visitor->AddStmt(E);
2439 }
2440 for (auto *E : C->destination_exprs()) {
2441 Visitor->AddStmt(E);
2442 }
2443 for (auto *E : C->assignment_ops()) {
2444 Visitor->AddStmt(E);
2445 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002446}
Alexey Bataev6125da92014-07-21 11:26:11 +00002447void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2448 VisitOMPClauseList(C);
2449}
Alexey Bataevc112e942020-02-28 09:52:15 -05002450void OMPClauseEnqueue::VisitOMPDepobjClause(const OMPDepobjClause *C) {
2451 Visitor->AddStmt(C->getDepobj());
2452}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002453void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2454 VisitOMPClauseList(C);
2455}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002456void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2457 VisitOMPClauseList(C);
2458}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002459void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2460 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002461 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002462 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002463}
Alexey Bataev3392d762016-02-16 11:18:12 +00002464void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2465 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002466void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2467 VisitOMPClauseList(C);
2468}
Samuel Antaoec172c62016-05-26 17:49:04 +00002469void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2470 VisitOMPClauseList(C);
2471}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002472void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2473 VisitOMPClauseList(C);
2474}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002475void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2476 VisitOMPClauseList(C);
2477}
Alexey Bataevb6e70842019-12-16 15:54:17 -05002478void OMPClauseEnqueue::VisitOMPNontemporalClause(
2479 const OMPNontemporalClause *C) {
2480 VisitOMPClauseList(C);
Alexey Bataev0860db92019-12-19 10:01:10 -05002481 for (const auto *E : C->private_refs())
2482 Visitor->AddStmt(E);
Alexey Bataevb6e70842019-12-16 15:54:17 -05002483}
Alexey Bataevcb8e6912020-01-31 16:09:26 -05002484void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002485}
Alexey Bataev756c1962013-09-24 03:17:45 +00002486
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002487void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2488 unsigned size = WL.size();
2489 OMPClauseEnqueue Visitor(this);
2490 Visitor.Visit(S);
2491 if (size == WL.size())
2492 return;
2493 // Now reverse the entries we just added. This will match the DFS
2494 // ordering performed by the worklist.
2495 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2496 std::reverse(I, E);
2497}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002498void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2500}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002501void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 AddDecl(B->getBlockDecl());
2503}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002504void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 EnqueueChildren(E);
2506 AddTypeLoc(E->getTypeSourceInfo());
2507}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002508void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002509 for (auto &I : llvm::reverse(S->body()))
2510 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002511}
2512void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002513VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 AddStmt(S->getSubStmt());
2515 AddDeclarationNameInfo(S);
2516 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2517 AddNestedNameSpecifierLoc(QualifierLoc);
2518}
2519
2520void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002521VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002522 if (E->hasExplicitTemplateArgs())
2523 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 AddDeclarationNameInfo(E);
2525 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2526 AddNestedNameSpecifierLoc(QualifierLoc);
2527 if (!E->isImplicitAccess())
2528 AddStmt(E->getBase());
2529}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002530void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 // Enqueue the initializer , if any.
2532 AddStmt(E->getInitializer());
2533 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002534 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 // Enqueue the allocated type.
2536 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2537 // Enqueue the placement arguments.
2538 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2539 AddStmt(E->getPlacementArg(I-1));
2540}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002541void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2543 AddStmt(CE->getArg(I-1));
2544 AddStmt(CE->getCallee());
2545 AddStmt(CE->getArg(0));
2546}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002547void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2548 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 // Visit the name of the type being destroyed.
2550 AddTypeLoc(E->getDestroyedTypeInfo());
2551 // Visit the scope type that looks disturbingly like the nested-name-specifier
2552 // but isn't.
2553 AddTypeLoc(E->getScopeTypeInfo());
2554 // Visit the nested-name-specifier.
2555 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2556 AddNestedNameSpecifierLoc(QualifierLoc);
2557 // Visit base expression.
2558 AddStmt(E->getBase());
2559}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002560void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2561 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 AddTypeLoc(E->getTypeSourceInfo());
2563}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002564void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2565 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 EnqueueChildren(E);
2567 AddTypeLoc(E->getTypeSourceInfo());
2568}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002569void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 EnqueueChildren(E);
2571 if (E->isTypeOperand())
2572 AddTypeLoc(E->getTypeOperandSourceInfo());
2573}
2574
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002575void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2576 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 EnqueueChildren(E);
2578 AddTypeLoc(E->getTypeSourceInfo());
2579}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002580void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 EnqueueChildren(E);
2582 if (E->isTypeOperand())
2583 AddTypeLoc(E->getTypeOperandSourceInfo());
2584}
2585
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002586void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 EnqueueChildren(S);
2588 AddDecl(S->getExceptionDecl());
2589}
2590
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002591void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002592 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002593 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002594 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002595}
2596
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002597void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002598 if (DR->hasExplicitTemplateArgs())
2599 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 WL.push_back(DeclRefExprParts(DR, Parent));
2601}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002602void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2603 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002604 if (E->hasExplicitTemplateArgs())
2605 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 AddDeclarationNameInfo(E);
2607 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2608}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002609void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 unsigned size = WL.size();
2611 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002612 for (const auto *D : S->decls()) {
2613 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 isFirst = false;
2615 }
2616 if (size == WL.size())
2617 return;
2618 // Now reverse the entries we just added. This will match the DFS
2619 // ordering performed by the worklist.
2620 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2621 std::reverse(I, E);
2622}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002623void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002625 for (const DesignatedInitExpr::Designator &D :
2626 llvm::reverse(E->designators())) {
2627 if (D.isFieldDesignator()) {
2628 if (FieldDecl *Field = D.getField())
2629 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 continue;
2631 }
David Majnemerf7e36092016-06-23 00:15:04 +00002632 if (D.isArrayDesignator()) {
2633 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 continue;
2635 }
David Majnemerf7e36092016-06-23 00:15:04 +00002636 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2637 AddStmt(E->getArrayRangeEnd(D));
2638 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 }
2640}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002641void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 EnqueueChildren(E);
2643 AddTypeLoc(E->getTypeInfoAsWritten());
2644}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002645void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 AddStmt(FS->getBody());
2647 AddStmt(FS->getInc());
2648 AddStmt(FS->getCond());
2649 AddDecl(FS->getConditionVariable());
2650 AddStmt(FS->getInit());
2651}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002652void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2654}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002655void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 AddStmt(If->getElse());
2657 AddStmt(If->getThen());
2658 AddStmt(If->getCond());
2659 AddDecl(If->getConditionVariable());
2660}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002661void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 // We care about the syntactic form of the initializer list, only.
2663 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2664 IE = Syntactic;
2665 EnqueueChildren(IE);
2666}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002667void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 WL.push_back(MemberExprParts(M, Parent));
2669
2670 // If the base of the member access expression is an implicit 'this', don't
2671 // visit it.
2672 // FIXME: If we ever want to show these implicit accesses, this will be
2673 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002674 if (M->isImplicitAccess())
2675 return;
2676
2677 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002678 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002679 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2680 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2681 if (FD->isAnonymousStructOrUnion()) {
2682 AddStmt(SubME->getBase());
2683 return;
2684 }
2685 }
2686 }
2687
2688 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002689}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002690void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 AddTypeLoc(E->getEncodedTypeSourceInfo());
2692}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002693void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 EnqueueChildren(M);
2695 AddTypeLoc(M->getClassReceiverTypeInfo());
2696}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002697void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 // Visit the components of the offsetof expression.
2699 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 const OffsetOfNode &Node = E->getComponent(I-1);
2701 switch (Node.getKind()) {
2702 case OffsetOfNode::Array:
2703 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2704 break;
2705 case OffsetOfNode::Field:
2706 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2707 break;
2708 case OffsetOfNode::Identifier:
2709 case OffsetOfNode::Base:
2710 continue;
2711 }
2712 }
2713 // Visit the type into which we're computing the offset.
2714 AddTypeLoc(E->getTypeSourceInfo());
2715}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002716void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002717 if (E->hasExplicitTemplateArgs())
2718 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 WL.push_back(OverloadExprParts(E, Parent));
2720}
2721void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002722 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 EnqueueChildren(E);
2724 if (E->isArgumentType())
2725 AddTypeLoc(E->getArgumentTypeInfo());
2726}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002727void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002728 EnqueueChildren(S);
2729}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002730void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002731 AddStmt(S->getBody());
2732 AddStmt(S->getCond());
2733 AddDecl(S->getConditionVariable());
2734}
2735
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002736void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 AddStmt(W->getBody());
2738 AddStmt(W->getCond());
2739 AddDecl(W->getConditionVariable());
2740}
2741
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002742void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002743 for (unsigned I = E->getNumArgs(); I > 0; --I)
2744 AddTypeLoc(E->getArg(I-1));
2745}
2746
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002747void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 AddTypeLoc(E->getQueriedTypeSourceInfo());
2749}
2750
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002751void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 EnqueueChildren(E);
2753}
2754
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002755void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 VisitOverloadExpr(U);
2757 if (!U->isImplicitAccess())
2758 AddStmt(U->getBase());
2759}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002760void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 AddStmt(E->getSubExpr());
2762 AddTypeLoc(E->getWrittenTypeInfo());
2763}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002764void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002765 WL.push_back(SizeOfPackExprParts(E, Parent));
2766}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002767void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002768 // If the opaque value has a source expression, just transparently
2769 // visit that. This is useful for (e.g.) pseudo-object expressions.
2770 if (Expr *SourceExpr = E->getSourceExpr())
2771 return Visit(SourceExpr);
2772}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002773void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002774 AddStmt(E->getBody());
2775 WL.push_back(LambdaExprParts(E, Parent));
2776}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002777void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 // Treat the expression like its syntactic form.
2779 Visit(E->getSyntacticForm());
2780}
2781
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002782void EnqueueVisitor::VisitOMPExecutableDirective(
2783 const OMPExecutableDirective *D) {
2784 EnqueueChildren(D);
2785 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2786 E = D->clauses().end();
2787 I != E; ++I)
2788 EnqueueChildren(*I);
2789}
2790
Alexander Musman3aaab662014-08-19 11:27:13 +00002791void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2792 VisitOMPExecutableDirective(D);
2793}
2794
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002795void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2796 VisitOMPExecutableDirective(D);
2797}
2798
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002799void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002800 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002801}
2802
Alexey Bataevf29276e2014-06-18 04:14:57 +00002803void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002804 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002805}
2806
Alexander Musmanf82886e2014-09-18 05:12:34 +00002807void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2808 VisitOMPLoopDirective(D);
2809}
2810
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002811void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2812 VisitOMPExecutableDirective(D);
2813}
2814
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002815void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2816 VisitOMPExecutableDirective(D);
2817}
2818
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002819void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2820 VisitOMPExecutableDirective(D);
2821}
2822
Alexander Musman80c22892014-07-17 08:54:58 +00002823void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2824 VisitOMPExecutableDirective(D);
2825}
2826
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002827void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2828 VisitOMPExecutableDirective(D);
2829 AddDeclarationNameInfo(D);
2830}
2831
Alexey Bataev4acb8592014-07-07 13:01:15 +00002832void
2833EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002834 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002835}
2836
Alexander Musmane4e893b2014-09-23 09:33:00 +00002837void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2838 const OMPParallelForSimdDirective *D) {
2839 VisitOMPLoopDirective(D);
2840}
2841
cchen47d60942019-12-05 13:43:48 -05002842void EnqueueVisitor::VisitOMPParallelMasterDirective(
2843 const OMPParallelMasterDirective *D) {
2844 VisitOMPExecutableDirective(D);
2845}
2846
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002847void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2848 const OMPParallelSectionsDirective *D) {
2849 VisitOMPExecutableDirective(D);
2850}
2851
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002852void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2853 VisitOMPExecutableDirective(D);
2854}
2855
Alexey Bataev68446b72014-07-18 07:47:19 +00002856void
2857EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2858 VisitOMPExecutableDirective(D);
2859}
2860
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002861void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2862 VisitOMPExecutableDirective(D);
2863}
2864
Alexey Bataev2df347a2014-07-18 10:17:07 +00002865void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2866 VisitOMPExecutableDirective(D);
2867}
2868
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002869void EnqueueVisitor::VisitOMPTaskgroupDirective(
2870 const OMPTaskgroupDirective *D) {
2871 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002872 if (const Expr *E = D->getReductionRef())
2873 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002874}
2875
Alexey Bataev6125da92014-07-21 11:26:11 +00002876void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2877 VisitOMPExecutableDirective(D);
2878}
2879
Alexey Bataevc112e942020-02-28 09:52:15 -05002880void EnqueueVisitor::VisitOMPDepobjDirective(const OMPDepobjDirective *D) {
2881 VisitOMPExecutableDirective(D);
2882}
2883
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002884void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2885 VisitOMPExecutableDirective(D);
2886}
2887
Alexey Bataev0162e452014-07-22 10:10:35 +00002888void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2889 VisitOMPExecutableDirective(D);
2890}
2891
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002892void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2893 VisitOMPExecutableDirective(D);
2894}
2895
Alexey Bataevc112e942020-02-28 09:52:15 -05002896void EnqueueVisitor::VisitOMPTargetDataDirective(
2897 const OMPTargetDataDirective *D) {
Michael Wong65f367f2015-07-21 13:44:28 +00002898 VisitOMPExecutableDirective(D);
2899}
2900
Samuel Antaodf67fc42016-01-19 19:15:56 +00002901void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2902 const OMPTargetEnterDataDirective *D) {
2903 VisitOMPExecutableDirective(D);
2904}
2905
Samuel Antao72590762016-01-19 20:04:50 +00002906void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2907 const OMPTargetExitDataDirective *D) {
2908 VisitOMPExecutableDirective(D);
2909}
2910
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002911void EnqueueVisitor::VisitOMPTargetParallelDirective(
2912 const OMPTargetParallelDirective *D) {
2913 VisitOMPExecutableDirective(D);
2914}
2915
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002916void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2917 const OMPTargetParallelForDirective *D) {
2918 VisitOMPLoopDirective(D);
2919}
2920
Alexey Bataev13314bf2014-10-09 04:18:56 +00002921void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2922 VisitOMPExecutableDirective(D);
2923}
2924
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002925void EnqueueVisitor::VisitOMPCancellationPointDirective(
2926 const OMPCancellationPointDirective *D) {
2927 VisitOMPExecutableDirective(D);
2928}
2929
Alexey Bataev80909872015-07-02 11:25:17 +00002930void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2931 VisitOMPExecutableDirective(D);
2932}
2933
Alexey Bataev49f6e782015-12-01 04:18:41 +00002934void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2935 VisitOMPLoopDirective(D);
2936}
2937
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002938void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2939 const OMPTaskLoopSimdDirective *D) {
2940 VisitOMPLoopDirective(D);
2941}
2942
Alexey Bataev60e51c42019-10-10 20:13:02 +00002943void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
2944 const OMPMasterTaskLoopDirective *D) {
2945 VisitOMPLoopDirective(D);
2946}
2947
Alexey Bataevb8552ab2019-10-18 16:47:35 +00002948void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
2949 const OMPMasterTaskLoopSimdDirective *D) {
2950 VisitOMPLoopDirective(D);
2951}
2952
Alexey Bataev5bbcead2019-10-14 17:17:41 +00002953void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
2954 const OMPParallelMasterTaskLoopDirective *D) {
2955 VisitOMPLoopDirective(D);
2956}
2957
Alexey Bataev14a388f2019-10-25 10:27:13 -04002958void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
2959 const OMPParallelMasterTaskLoopSimdDirective *D) {
2960 VisitOMPLoopDirective(D);
2961}
2962
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002963void EnqueueVisitor::VisitOMPDistributeDirective(
2964 const OMPDistributeDirective *D) {
2965 VisitOMPLoopDirective(D);
2966}
2967
Carlo Bertolli9925f152016-06-27 14:55:37 +00002968void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2969 const OMPDistributeParallelForDirective *D) {
2970 VisitOMPLoopDirective(D);
2971}
2972
Kelvin Li4a39add2016-07-05 05:00:15 +00002973void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2974 const OMPDistributeParallelForSimdDirective *D) {
2975 VisitOMPLoopDirective(D);
2976}
2977
Kelvin Li787f3fc2016-07-06 04:45:38 +00002978void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2979 const OMPDistributeSimdDirective *D) {
2980 VisitOMPLoopDirective(D);
2981}
2982
Kelvin Lia579b912016-07-14 02:54:56 +00002983void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2984 const OMPTargetParallelForSimdDirective *D) {
2985 VisitOMPLoopDirective(D);
2986}
2987
Kelvin Li986330c2016-07-20 22:57:10 +00002988void EnqueueVisitor::VisitOMPTargetSimdDirective(
2989 const OMPTargetSimdDirective *D) {
2990 VisitOMPLoopDirective(D);
2991}
2992
Kelvin Li02532872016-08-05 14:37:37 +00002993void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2994 const OMPTeamsDistributeDirective *D) {
2995 VisitOMPLoopDirective(D);
2996}
2997
Kelvin Li4e325f72016-10-25 12:50:55 +00002998void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2999 const OMPTeamsDistributeSimdDirective *D) {
3000 VisitOMPLoopDirective(D);
3001}
3002
Kelvin Li579e41c2016-11-30 23:51:03 +00003003void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
3004 const OMPTeamsDistributeParallelForSimdDirective *D) {
3005 VisitOMPLoopDirective(D);
3006}
3007
Kelvin Li7ade93f2016-12-09 03:24:30 +00003008void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
3009 const OMPTeamsDistributeParallelForDirective *D) {
3010 VisitOMPLoopDirective(D);
3011}
3012
Kelvin Libf594a52016-12-17 05:48:59 +00003013void EnqueueVisitor::VisitOMPTargetTeamsDirective(
3014 const OMPTargetTeamsDirective *D) {
3015 VisitOMPExecutableDirective(D);
3016}
3017
Kelvin Li83c451e2016-12-25 04:52:54 +00003018void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
3019 const OMPTargetTeamsDistributeDirective *D) {
3020 VisitOMPLoopDirective(D);
3021}
3022
Kelvin Li80e8f562016-12-29 22:16:30 +00003023void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3024 const OMPTargetTeamsDistributeParallelForDirective *D) {
3025 VisitOMPLoopDirective(D);
3026}
3027
Kelvin Li1851df52017-01-03 05:23:48 +00003028void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3029 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3030 VisitOMPLoopDirective(D);
3031}
3032
Kelvin Lida681182017-01-10 18:08:18 +00003033void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3034 const OMPTargetTeamsDistributeSimdDirective *D) {
3035 VisitOMPLoopDirective(D);
3036}
3037
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003038void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
3040}
3041
3042bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3043 if (RegionOfInterest.isValid()) {
3044 SourceRange Range = getRawCursorExtent(C);
3045 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3046 return false;
3047 }
3048 return true;
3049}
3050
3051bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3052 while (!WL.empty()) {
3053 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003054 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003055
3056 // Set the Parent field, then back to its old value once we're done.
3057 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3058
3059 switch (LI.getKind()) {
3060 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003061 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 if (!D)
3063 continue;
3064
3065 // For now, perform default visitation for Decls.
3066 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3067 cast<DeclVisit>(&LI)->isFirst())))
3068 return true;
3069
3070 continue;
3071 }
3072 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003073 for (const TemplateArgumentLoc &Arg :
3074 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3075 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 return true;
3077 }
3078 continue;
3079 }
3080 case VisitorJob::TypeLocVisitKind: {
3081 // Perform default visitation for TypeLocs.
3082 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3083 return true;
3084 continue;
3085 }
3086 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003087 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 if (LabelStmt *stmt = LS->getStmt()) {
3089 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3090 TU))) {
3091 return true;
3092 }
3093 }
3094 continue;
3095 }
3096
3097 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3098 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3099 if (VisitNestedNameSpecifierLoc(V->get()))
3100 return true;
3101 continue;
3102 }
3103
3104 case VisitorJob::DeclarationNameInfoVisitKind: {
3105 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3106 ->get()))
3107 return true;
3108 continue;
3109 }
3110 case VisitorJob::MemberRefVisitKind: {
3111 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3112 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3113 return true;
3114 continue;
3115 }
3116 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003117 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 if (!S)
3119 continue;
3120
3121 // Update the current cursor.
3122 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3123 if (!IsInRegionOfInterest(Cursor))
3124 continue;
3125 switch (Visitor(Cursor, Parent, ClientData)) {
3126 case CXChildVisit_Break: return true;
3127 case CXChildVisit_Continue: break;
3128 case CXChildVisit_Recurse:
3129 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003130 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 EnqueueWorkList(WL, S);
3132 break;
3133 }
3134 continue;
3135 }
3136 case VisitorJob::MemberExprPartsKind: {
3137 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003138 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003139
3140 // Visit the nested-name-specifier
3141 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3142 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3143 return true;
3144
3145 // Visit the declaration name.
3146 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3147 return true;
3148
3149 // Visit the explicitly-specified template arguments, if any.
3150 if (M->hasExplicitTemplateArgs()) {
3151 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3152 *ArgEnd = Arg + M->getNumTemplateArgs();
3153 Arg != ArgEnd; ++Arg) {
3154 if (VisitTemplateArgumentLoc(*Arg))
3155 return true;
3156 }
3157 }
3158 continue;
3159 }
3160 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003161 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 // Visit nested-name-specifier, if present.
3163 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3164 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3165 return true;
3166 // Visit declaration name.
3167 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3168 return true;
3169 continue;
3170 }
3171 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003172 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 // Visit the nested-name-specifier.
3174 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3175 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3176 return true;
3177 // Visit the declaration name.
3178 if (VisitDeclarationNameInfo(O->getNameInfo()))
3179 return true;
3180 // Visit the overloaded declaration reference.
3181 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3182 return true;
3183 continue;
3184 }
3185 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003186 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 NamedDecl *Pack = E->getPack();
3188 if (isa<TemplateTypeParmDecl>(Pack)) {
3189 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3190 E->getPackLoc(), TU)))
3191 return true;
3192
3193 continue;
3194 }
3195
3196 if (isa<TemplateTemplateParmDecl>(Pack)) {
3197 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3198 E->getPackLoc(), TU)))
3199 return true;
3200
3201 continue;
3202 }
3203
3204 // Non-type template parameter packs and function parameter packs are
3205 // treated like DeclRefExpr cursors.
3206 continue;
3207 }
3208
3209 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003210 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003211 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003212 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3213 CEnd = E->explicit_capture_end();
3214 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003215 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003216 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003217
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3219 C->getLocation(),
3220 TU)))
3221 return true;
3222 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003223 // Visit init captures
3224 for (auto InitExpr : E->capture_inits()) {
3225 if (Visit(InitExpr))
3226 return true;
3227 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003228
Haojian Wuef87c262018-12-18 15:29:12 +00003229 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003230 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003231 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3232 if (E->hasExplicitParameters()) {
3233 // Visit parameters.
3234 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3235 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003236 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003237 }
3238 if (E->hasExplicitResultType()) {
3239 // Visit result type.
3240 if (Visit(Proto.getReturnLoc()))
3241 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003242 }
3243 }
3244 break;
3245 }
3246
3247 case VisitorJob::PostChildrenVisitKind:
3248 if (PostChildrenVisitor(Parent, ClientData))
3249 return true;
3250 break;
3251 }
3252 }
3253 return false;
3254}
3255
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003256bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003257 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 if (!WorkListFreeList.empty()) {
3259 WL = WorkListFreeList.back();
3260 WL->clear();
3261 WorkListFreeList.pop_back();
3262 }
3263 else {
3264 WL = new VisitorWorkList();
3265 WorkListCache.push_back(WL);
3266 }
3267 EnqueueWorkList(*WL, S);
3268 bool result = RunVisitorWorkList(*WL);
3269 WorkListFreeList.push_back(WL);
3270 return result;
3271}
3272
3273namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003274typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003275RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3276 const DeclarationNameInfo &NI, SourceRange QLoc,
3277 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3279 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3280 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3281
3282 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3283
3284 RefNamePieces Pieces;
3285
3286 if (WantQualifier && QLoc.isValid())
3287 Pieces.push_back(QLoc);
3288
3289 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3290 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003291
3292 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3293 Pieces.push_back(*TemplateArgsLoc);
3294
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 if (Kind == DeclarationName::CXXOperatorName) {
3296 Pieces.push_back(SourceLocation::getFromRawEncoding(
3297 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3298 Pieces.push_back(SourceLocation::getFromRawEncoding(
3299 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3300 }
3301
3302 if (WantSinglePiece) {
3303 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3304 Pieces.clear();
3305 Pieces.push_back(R);
3306 }
3307
3308 return Pieces;
3309}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003310}
Guy Benyei11169dd2012-12-18 14:30:41 +00003311
3312//===----------------------------------------------------------------------===//
3313// Misc. API hooks.
3314//===----------------------------------------------------------------------===//
3315
Chandler Carruth66660742014-06-27 16:37:27 +00003316namespace {
3317struct RegisterFatalErrorHandler {
3318 RegisterFatalErrorHandler() {
Jan Korousf7d23762019-09-12 22:55:55 +00003319 clang_install_aborting_llvm_fatal_error_handler();
Chandler Carruth66660742014-06-27 16:37:27 +00003320 }
3321};
3322}
3323
3324static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3325
Guy Benyei11169dd2012-12-18 14:30:41 +00003326CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3327 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003328 // We use crash recovery to make some of our APIs more reliable, implicitly
3329 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003330 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3331 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003332
Chandler Carruth66660742014-06-27 16:37:27 +00003333 // Look through the managed static to trigger construction of the managed
3334 // static which registers our fatal error handler. This ensures it is only
3335 // registered once.
3336 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003337
Adrian Prantlbc068582015-07-08 01:00:30 +00003338 // Initialize targets for clang module support.
3339 llvm::InitializeAllTargets();
3340 llvm::InitializeAllTargetMCs();
3341 llvm::InitializeAllAsmPrinters();
3342 llvm::InitializeAllAsmParsers();
3343
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003344 CIndexer *CIdxr = new CIndexer();
3345
Guy Benyei11169dd2012-12-18 14:30:41 +00003346 if (excludeDeclarationsFromPCH)
3347 CIdxr->setOnlyLocalDecls();
3348 if (displayDiagnostics)
3349 CIdxr->setDisplayDiagnostics();
3350
3351 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3352 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3353 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3354 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3355 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3356 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3357
3358 return CIdxr;
3359}
3360
3361void clang_disposeIndex(CXIndex CIdx) {
3362 if (CIdx)
3363 delete static_cast<CIndexer *>(CIdx);
3364}
3365
3366void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3367 if (CIdx)
3368 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3369}
3370
3371unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3372 if (CIdx)
3373 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3374 return 0;
3375}
3376
Alex Lorenz08615792017-12-04 21:56:36 +00003377void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3378 const char *Path) {
3379 if (CIdx)
3380 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3381}
3382
Guy Benyei11169dd2012-12-18 14:30:41 +00003383void clang_toggleCrashRecovery(unsigned isEnabled) {
3384 if (isEnabled)
3385 llvm::CrashRecoveryContext::Enable();
3386 else
3387 llvm::CrashRecoveryContext::Disable();
3388}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003389
Guy Benyei11169dd2012-12-18 14:30:41 +00003390CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3391 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003392 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003393 enum CXErrorCode Result =
3394 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003395 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003396 assert((TU && Result == CXError_Success) ||
3397 (!TU && Result != CXError_Success));
3398 return TU;
3399}
3400
3401enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3402 const char *ast_filename,
3403 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003404 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003405 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003406
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003407 if (!CIdx || !ast_filename || !out_TU)
3408 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003409
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003410 LOG_FUNC_SECTION {
3411 *Log << ast_filename;
3412 }
3413
Guy Benyei11169dd2012-12-18 14:30:41 +00003414 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3415 FileSystemOptions FileSystemOpts;
3416
Justin Bognerd512c1e2014-10-15 00:33:06 +00003417 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3418 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003419 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003420 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3421 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003422 FileSystemOpts, /*UseDebugInfo=*/false,
3423 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003424 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003425 /*AllowPCHWithCompilerErrors=*/true,
3426 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003427 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003428 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003429}
3430
3431unsigned clang_defaultEditingTranslationUnitOptions() {
3432 return CXTranslationUnit_PrecompiledPreamble |
3433 CXTranslationUnit_CacheCompletionResults;
3434}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003435
Guy Benyei11169dd2012-12-18 14:30:41 +00003436CXTranslationUnit
3437clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3438 const char *source_filename,
3439 int num_command_line_args,
3440 const char * const *command_line_args,
3441 unsigned num_unsaved_files,
3442 struct CXUnsavedFile *unsaved_files) {
3443 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3444 return clang_parseTranslationUnit(CIdx, source_filename,
3445 command_line_args, num_command_line_args,
3446 unsaved_files, num_unsaved_files,
3447 Options);
3448}
3449
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003450static CXErrorCode
3451clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3452 const char *const *command_line_args,
3453 int num_command_line_args,
3454 ArrayRef<CXUnsavedFile> unsaved_files,
3455 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003456 // Set up the initial return values.
3457 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003458 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003459
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003460 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003461 if (!CIdx || !out_TU)
3462 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003463
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3465
3466 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3467 setThreadBackgroundPriority();
3468
3469 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003470 bool CreatePreambleOnFirstParse =
3471 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003472 // FIXME: Add a flag for modules.
3473 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003474 = (options & (CXTranslationUnit_Incomplete |
3475 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003476 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003477 = options & CXTranslationUnit_CacheCompletionResults;
3478 bool IncludeBriefCommentsInCodeCompletion
3479 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003480 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3481 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003482 bool RetainExcludedCB = options &
3483 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003484 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3485 if (options & CXTranslationUnit_SkipFunctionBodies) {
3486 SkipFunctionBodies =
3487 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3488 ? SkipFunctionBodiesScope::Preamble
3489 : SkipFunctionBodiesScope::PreambleAndMainFile;
3490 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003491
3492 // Configure the diagnostics.
3493 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003494 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003495
Manuel Klimek016c0242016-03-01 10:56:19 +00003496 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003497 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003498
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003499 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3500 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3501 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3502
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 // Recover resources if we crash before exiting this function.
3504 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3505 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003506 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003507
Ahmed Charlesb8984322014-03-07 20:03:18 +00003508 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3509 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003510
3511 // Recover resources if we crash before exiting this function.
3512 llvm::CrashRecoveryContextCleanupRegistrar<
3513 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3514
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003515 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003516 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003517 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003518 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003519 }
3520
Ahmed Charlesb8984322014-03-07 20:03:18 +00003521 std::unique_ptr<std::vector<const char *>> Args(
3522 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003523
3524 // Recover resources if we crash before exiting this method.
3525 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3526 ArgsCleanup(Args.get());
3527
3528 // Since the Clang C library is primarily used by batch tools dealing with
3529 // (often very broken) source code, where spell-checking can have a
3530 // significant negative impact on performance (particularly when
3531 // precompiled headers are involved), we disable it by default.
3532 // Only do this if we haven't found a spell-checking-related argument.
3533 bool FoundSpellCheckingArgument = false;
3534 for (int I = 0; I != num_command_line_args; ++I) {
3535 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3536 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3537 FoundSpellCheckingArgument = true;
3538 break;
3539 }
3540 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003541 Args->insert(Args->end(), command_line_args,
3542 command_line_args + num_command_line_args);
3543
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003544 if (!FoundSpellCheckingArgument)
3545 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3546
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 // The 'source_filename' argument is optional. If the caller does not
3548 // specify it then it is assumed that the source file is specified
3549 // in the actual argument list.
3550 // Put the source file after command_line_args otherwise if '-x' flag is
3551 // present it will be unused.
3552 if (source_filename)
3553 Args->push_back(source_filename);
3554
3555 // Do we need the detailed preprocessing record?
3556 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3557 Args->push_back("-Xclang");
3558 Args->push_back("-detailed-preprocessing-record");
3559 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003560
3561 // Suppress any editor placeholder diagnostics.
3562 Args->push_back("-fallow-editor-placeholders");
3563
Guy Benyei11169dd2012-12-18 14:30:41 +00003564 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003565 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003566 // Unless the user specified that they want the preamble on the first parse
3567 // set it up to be created on the first reparse. This makes the first parse
3568 // faster, trading for a slower (first) reparse.
3569 unsigned PrecompilePreambleAfterNParses =
3570 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003571
Alex Lorenz08615792017-12-04 21:56:36 +00003572 LibclangInvocationReporter InvocationReporter(
3573 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003574 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3575 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003576 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003577 Args->data(), Args->data() + Args->size(),
3578 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003579 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003580 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003581 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3582 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003583 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003584 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003585 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3586 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003587
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003588 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003589 if (!Unit && !ErrUnit)
3590 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003591
Guy Benyei11169dd2012-12-18 14:30:41 +00003592 if (NumErrors != Diags->getClient()->getNumErrors()) {
3593 // Make sure to check that 'Unit' is non-NULL.
3594 if (CXXIdx->getDisplayDiagnostics())
3595 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3596 }
3597
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003598 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3599 return CXError_ASTReadError;
3600
David Blaikieea4395e2017-01-06 19:49:01 +00003601 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003602 if (CXTranslationUnitImpl *TU = *out_TU) {
3603 TU->ParsingOptions = options;
3604 TU->Arguments.reserve(Args->size());
3605 for (const char *Arg : *Args)
3606 TU->Arguments.push_back(Arg);
3607 return CXError_Success;
3608 }
3609 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003610}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003611
3612CXTranslationUnit
3613clang_parseTranslationUnit(CXIndex CIdx,
3614 const char *source_filename,
3615 const char *const *command_line_args,
3616 int num_command_line_args,
3617 struct CXUnsavedFile *unsaved_files,
3618 unsigned num_unsaved_files,
3619 unsigned options) {
3620 CXTranslationUnit TU;
3621 enum CXErrorCode Result = clang_parseTranslationUnit2(
3622 CIdx, source_filename, command_line_args, num_command_line_args,
3623 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003624 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003625 assert((TU && Result == CXError_Success) ||
3626 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003627 return TU;
3628}
3629
3630enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003631 CXIndex CIdx, const char *source_filename,
3632 const char *const *command_line_args, int num_command_line_args,
3633 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3634 unsigned options, CXTranslationUnit *out_TU) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003635 noteBottomOfStack();
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003636 SmallVector<const char *, 4> Args;
3637 Args.push_back("clang");
3638 Args.append(command_line_args, command_line_args + num_command_line_args);
3639 return clang_parseTranslationUnit2FullArgv(
3640 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3641 num_unsaved_files, options, out_TU);
3642}
3643
3644enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3645 CXIndex CIdx, const char *source_filename,
3646 const char *const *command_line_args, int num_command_line_args,
3647 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3648 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003649 LOG_FUNC_SECTION {
3650 *Log << source_filename << ": ";
3651 for (int i = 0; i != num_command_line_args; ++i)
3652 *Log << command_line_args[i] << " ";
3653 }
3654
Alp Toker9d85b182014-07-07 01:23:14 +00003655 if (num_unsaved_files && !unsaved_files)
3656 return CXError_InvalidArguments;
3657
Alp Toker5c532982014-07-07 22:42:03 +00003658 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003659 auto ParseTranslationUnitImpl = [=, &result] {
Alexandre Ganea471d0602019-11-29 10:52:13 -05003660 noteBottomOfStack();
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003661 result = clang_parseTranslationUnit_Impl(
3662 CIdx, source_filename, command_line_args, num_command_line_args,
3663 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3664 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003665
Guy Benyei11169dd2012-12-18 14:30:41 +00003666 llvm::CrashRecoveryContext CRC;
3667
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003668 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003669 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3670 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3671 fprintf(stderr, " 'command_line_args' : [");
3672 for (int i = 0; i != num_command_line_args; ++i) {
3673 if (i)
3674 fprintf(stderr, ", ");
3675 fprintf(stderr, "'%s'", command_line_args[i]);
3676 }
3677 fprintf(stderr, "],\n");
3678 fprintf(stderr, " 'unsaved_files' : [");
3679 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3680 if (i)
3681 fprintf(stderr, ", ");
3682 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3683 unsaved_files[i].Length);
3684 }
3685 fprintf(stderr, "],\n");
3686 fprintf(stderr, " 'options' : %d,\n", options);
3687 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003688
3689 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003690 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003691 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003692 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 }
Alp Toker5c532982014-07-07 22:42:03 +00003694
3695 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003696}
3697
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003698CXString clang_Type_getObjCEncoding(CXType CT) {
3699 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3700 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3701 std::string encoding;
3702 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3703 encoding);
3704
3705 return cxstring::createDup(encoding);
3706}
3707
3708static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3709 if (C.kind == CXCursor_MacroDefinition) {
3710 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3711 return MDR->getName();
3712 } else if (C.kind == CXCursor_MacroExpansion) {
3713 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3714 return ME.getName();
3715 }
3716 return nullptr;
3717}
3718
3719unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3720 const IdentifierInfo *II = getMacroIdentifier(C);
3721 if (!II) {
3722 return false;
3723 }
3724 ASTUnit *ASTU = getCursorASTUnit(C);
3725 Preprocessor &PP = ASTU->getPreprocessor();
3726 if (const MacroInfo *MI = PP.getMacroInfo(II))
3727 return MI->isFunctionLike();
3728 return false;
3729}
3730
3731unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3732 const IdentifierInfo *II = getMacroIdentifier(C);
3733 if (!II) {
3734 return false;
3735 }
3736 ASTUnit *ASTU = getCursorASTUnit(C);
3737 Preprocessor &PP = ASTU->getPreprocessor();
3738 if (const MacroInfo *MI = PP.getMacroInfo(II))
3739 return MI->isBuiltinMacro();
3740 return false;
3741}
3742
3743unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3744 const Decl *D = getCursorDecl(C);
3745 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3746 if (!FD) {
3747 return false;
3748 }
3749 return FD->isInlined();
3750}
3751
3752static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3753 if (callExpr->getNumArgs() != 1) {
3754 return nullptr;
3755 }
3756
3757 StringLiteral *S = nullptr;
3758 auto *arg = callExpr->getArg(0);
3759 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3760 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3761 auto *subExpr = I->getSubExprAsWritten();
3762
3763 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3764 return nullptr;
3765 }
3766
3767 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3768 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3769 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3770 } else {
3771 return nullptr;
3772 }
3773 return S;
3774}
3775
David Blaikie59272572016-04-13 18:23:33 +00003776struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003777 CXEvalResultKind EvalType;
3778 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003779 unsigned long long unsignedVal;
3780 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003781 double floatVal;
3782 char *stringVal;
3783 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003784 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003785 ~ExprEvalResult() {
3786 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3787 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003788 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003789 }
3790 }
3791};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003792
3793void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003794 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003795}
3796
3797CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3798 if (!E) {
3799 return CXEval_UnExposed;
3800 }
3801 return ((ExprEvalResult *)E)->EvalType;
3802}
3803
3804int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003805 return clang_EvalResult_getAsLongLong(E);
3806}
3807
3808long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003809 if (!E) {
3810 return 0;
3811 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003812 ExprEvalResult *Result = (ExprEvalResult*)E;
3813 if (Result->IsUnsignedInt)
3814 return Result->EvalData.unsignedVal;
3815 return Result->EvalData.intVal;
3816}
3817
3818unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3819 return ((ExprEvalResult *)E)->IsUnsignedInt;
3820}
3821
3822unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3823 if (!E) {
3824 return 0;
3825 }
3826
3827 ExprEvalResult *Result = (ExprEvalResult*)E;
3828 if (Result->IsUnsignedInt)
3829 return Result->EvalData.unsignedVal;
3830 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003831}
3832
3833double clang_EvalResult_getAsDouble(CXEvalResult E) {
3834 if (!E) {
3835 return 0;
3836 }
3837 return ((ExprEvalResult *)E)->EvalData.floatVal;
3838}
3839
3840const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3841 if (!E) {
3842 return nullptr;
3843 }
3844 return ((ExprEvalResult *)E)->EvalData.stringVal;
3845}
3846
3847static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3848 Expr::EvalResult ER;
3849 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003850 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003851 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003852
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003853 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003854 if (expr->isValueDependent())
3855 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003856 if (!expr->EvaluateAsRValue(ER, ctx))
3857 return nullptr;
3858
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003859 QualType rettype;
3860 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003861 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003862 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003863 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003864
David Blaikiebbc00882016-04-13 18:36:19 +00003865 if (ER.Val.isInt()) {
3866 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003867
3868 auto& val = ER.Val.getInt();
3869 if (val.isUnsigned()) {
3870 result->IsUnsignedInt = true;
3871 result->EvalData.unsignedVal = val.getZExtValue();
3872 } else {
3873 result->EvalData.intVal = val.getExtValue();
3874 }
3875
David Blaikiebbc00882016-04-13 18:36:19 +00003876 return result.release();
3877 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003878
David Blaikiebbc00882016-04-13 18:36:19 +00003879 if (ER.Val.isFloat()) {
3880 llvm::SmallVector<char, 100> Buffer;
3881 ER.Val.getFloat().toString(Buffer);
3882 std::string floatStr(Buffer.data(), Buffer.size());
3883 result->EvalType = CXEval_Float;
3884 bool ignored;
3885 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003886 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003887 llvm::APFloat::rmNearestTiesToEven, &ignored);
3888 result->EvalData.floatVal = apFloat.convertToDouble();
3889 return result.release();
3890 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003891
David Blaikiebbc00882016-04-13 18:36:19 +00003892 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3893 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3894 auto *subExpr = I->getSubExprAsWritten();
3895 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3896 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003897 const StringLiteral *StrE = nullptr;
3898 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003899 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003900
3901 if (ObjCExpr) {
3902 StrE = ObjCExpr->getString();
3903 result->EvalType = CXEval_ObjCStrLiteral;
3904 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003905 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003906 result->EvalType = CXEval_StrLiteral;
3907 }
3908
3909 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003910 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003911 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3912 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003913 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003914 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003915 }
3916 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3917 expr->getStmtClass() == Stmt::StringLiteralClass) {
3918 const StringLiteral *StrE = nullptr;
3919 const ObjCStringLiteral *ObjCExpr;
3920 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003921
David Blaikiebbc00882016-04-13 18:36:19 +00003922 if (ObjCExpr) {
3923 StrE = ObjCExpr->getString();
3924 result->EvalType = CXEval_ObjCStrLiteral;
3925 } else {
3926 StrE = cast<StringLiteral>(expr);
3927 result->EvalType = CXEval_StrLiteral;
3928 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003929
David Blaikiebbc00882016-04-13 18:36:19 +00003930 std::string strRef(StrE->getString().str());
3931 result->EvalData.stringVal = new char[strRef.size() + 1];
3932 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3933 result->EvalData.stringVal[strRef.size()] = '\0';
3934 return result.release();
3935 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003936
David Blaikiebbc00882016-04-13 18:36:19 +00003937 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3938 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003939
David Blaikiebbc00882016-04-13 18:36:19 +00003940 rettype = CC->getType();
3941 if (rettype.getAsString() == "CFStringRef" &&
3942 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003943
David Blaikiebbc00882016-04-13 18:36:19 +00003944 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3945 StringLiteral *S = getCFSTR_value(callExpr);
3946 if (S) {
3947 std::string strLiteral(S->getString().str());
3948 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003949
David Blaikiebbc00882016-04-13 18:36:19 +00003950 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3951 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3952 strLiteral.size());
3953 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003954 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003955 }
3956 }
3957
David Blaikiebbc00882016-04-13 18:36:19 +00003958 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3959 callExpr = static_cast<CallExpr *>(expr);
3960 rettype = callExpr->getCallReturnType(ctx);
3961
3962 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3963 return nullptr;
3964
3965 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3966 if (callExpr->getNumArgs() == 1 &&
3967 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3968 return nullptr;
3969 } else if (rettype.getAsString() == "CFStringRef") {
3970
3971 StringLiteral *S = getCFSTR_value(callExpr);
3972 if (S) {
3973 std::string strLiteral(S->getString().str());
3974 result->EvalType = CXEval_CFStr;
3975 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3976 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3977 strLiteral.size());
3978 result->EvalData.stringVal[strLiteral.size()] = '\0';
3979 return result.release();
3980 }
3981 }
3982 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3983 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3984 ValueDecl *V = D->getDecl();
3985 if (V->getKind() == Decl::Function) {
3986 std::string strName = V->getNameAsString();
3987 result->EvalType = CXEval_Other;
3988 result->EvalData.stringVal = new char[strName.size() + 1];
3989 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3990 result->EvalData.stringVal[strName.size()] = '\0';
3991 return result.release();
3992 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003993 }
3994
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003995 return nullptr;
3996}
3997
Alex Lorenz65317e12019-01-08 22:32:51 +00003998static const Expr *evaluateDeclExpr(const Decl *D) {
3999 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00004000 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00004001 if (auto *Var = dyn_cast<VarDecl>(D))
4002 return Var->getInit();
4003 else if (auto *Field = dyn_cast<FieldDecl>(D))
4004 return Field->getInClassInitializer();
4005 return nullptr;
4006}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00004007
Alex Lorenz65317e12019-01-08 22:32:51 +00004008static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
4009 assert(CS && "invalid compound statement");
4010 for (auto *bodyIterator : CS->body()) {
4011 if (const auto *E = dyn_cast<Expr>(bodyIterator))
4012 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00004013 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00004014 return nullptr;
4015}
4016
Alex Lorenz65317e12019-01-08 22:32:51 +00004017CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
4018 if (const Expr *E =
4019 clang_getCursorKind(C) == CXCursor_CompoundStmt
4020 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
4021 : evaluateDeclExpr(getCursorDecl(C)))
4022 return const_cast<CXEvalResult>(
4023 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4024 return nullptr;
4025}
4026
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004027unsigned clang_Cursor_hasAttrs(CXCursor C) {
4028 const Decl *D = getCursorDecl(C);
4029 if (!D) {
4030 return 0;
4031 }
4032
4033 if (D->hasAttrs()) {
4034 return 1;
4035 }
4036
4037 return 0;
4038}
Guy Benyei11169dd2012-12-18 14:30:41 +00004039unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4040 return CXSaveTranslationUnit_None;
4041}
4042
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004043static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4044 const char *FileName,
4045 unsigned options) {
4046 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004047 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4048 setThreadBackgroundPriority();
4049
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004050 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4051 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00004052}
4053
4054int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4055 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004056 LOG_FUNC_SECTION {
4057 *Log << TU << ' ' << FileName;
4058 }
4059
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004060 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004061 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004062 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004063 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004064
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004065 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4067 if (!CXXUnit->hasSema())
4068 return CXSaveError_InvalidTU;
4069
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004070 CXSaveError result;
4071 auto SaveTranslationUnitImpl = [=, &result]() {
4072 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4073 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004074
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004075 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004076 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004077
4078 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4079 PrintLibclangResourceUsage(TU);
4080
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004081 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004082 }
4083
4084 // We have an AST that has invalid nodes due to compiler errors.
4085 // Use a crash recovery thread for protection.
4086
4087 llvm::CrashRecoveryContext CRC;
4088
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004089 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004090 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4091 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4092 fprintf(stderr, " 'options' : %d,\n", options);
4093 fprintf(stderr, "}\n");
4094
4095 return CXSaveError_Unknown;
4096
4097 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4098 PrintLibclangResourceUsage(TU);
4099 }
4100
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004101 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004102}
4103
4104void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4105 if (CTUnit) {
4106 // If the translation unit has been marked as unsafe to free, just discard
4107 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004108 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4109 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004110 return;
4111
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004112 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004113 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4115 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004116 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004117 delete CTUnit;
4118 }
4119}
4120
Erik Verbruggen346066b2017-05-30 14:25:54 +00004121unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4122 if (CTUnit) {
4123 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4124
4125 if (Unit && Unit->isUnsafeToFree())
4126 return false;
4127
4128 Unit->ResetForParse();
4129 return true;
4130 }
4131
4132 return false;
4133}
4134
Guy Benyei11169dd2012-12-18 14:30:41 +00004135unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4136 return CXReparse_None;
4137}
4138
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004139static CXErrorCode
4140clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4141 ArrayRef<CXUnsavedFile> unsaved_files,
4142 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004143 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004144 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004145 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004146 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004147 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004148
4149 // Reset the associated diagnostics.
4150 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004151 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004152
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004153 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004154 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4155 setThreadBackgroundPriority();
4156
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004157 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004158 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004159
4160 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4161 new std::vector<ASTUnit::RemappedFile>());
4162
Guy Benyei11169dd2012-12-18 14:30:41 +00004163 // Recover resources if we crash before exiting this function.
4164 llvm::CrashRecoveryContextCleanupRegistrar<
4165 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004166
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004167 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004168 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004169 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004170 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004172
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004173 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4174 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004175 return CXError_Success;
4176 if (isASTReadError(CXXUnit))
4177 return CXError_ASTReadError;
4178 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004179}
4180
4181int clang_reparseTranslationUnit(CXTranslationUnit TU,
4182 unsigned num_unsaved_files,
4183 struct CXUnsavedFile *unsaved_files,
4184 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004185 LOG_FUNC_SECTION {
4186 *Log << TU;
4187 }
4188
Alp Toker9d85b182014-07-07 01:23:14 +00004189 if (num_unsaved_files && !unsaved_files)
4190 return CXError_InvalidArguments;
4191
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004192 CXErrorCode result;
4193 auto ReparseTranslationUnitImpl = [=, &result]() {
4194 result = clang_reparseTranslationUnit_Impl(
4195 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4196 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004197
Guy Benyei11169dd2012-12-18 14:30:41 +00004198 llvm::CrashRecoveryContext CRC;
4199
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004200 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004201 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004202 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004203 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4205 PrintLibclangResourceUsage(TU);
4206
Alp Toker5c532982014-07-07 22:42:03 +00004207 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004208}
4209
4210
4211CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004212 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004213 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004214 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004215 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004216
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004217 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004218 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004219}
4220
4221CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004222 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004223 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004224 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004225 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004226
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004227 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004228 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4229}
4230
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004231CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4232 if (isNotUsableTU(CTUnit)) {
4233 LOG_BAD_TU(CTUnit);
4234 return nullptr;
4235 }
4236
4237 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4238 impl->TranslationUnit = CTUnit;
4239 return impl;
4240}
4241
4242CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4243 if (!TargetInfo)
4244 return cxstring::createEmpty();
4245
4246 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4247 assert(!isNotUsableTU(CTUnit) &&
4248 "Unexpected unusable translation unit in TargetInfo");
4249
4250 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4251 std::string Triple =
4252 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4253 return cxstring::createDup(Triple);
4254}
4255
4256int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4257 if (!TargetInfo)
4258 return -1;
4259
4260 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4261 assert(!isNotUsableTU(CTUnit) &&
4262 "Unexpected unusable translation unit in TargetInfo");
4263
4264 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4265 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4266}
4267
4268void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4269 if (!TargetInfo)
4270 return;
4271
4272 delete TargetInfo;
4273}
4274
Guy Benyei11169dd2012-12-18 14:30:41 +00004275//===----------------------------------------------------------------------===//
4276// CXFile Operations.
4277//===----------------------------------------------------------------------===//
4278
Guy Benyei11169dd2012-12-18 14:30:41 +00004279CXString clang_getFileName(CXFile SFile) {
4280 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004281 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004282
4283 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004284 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004285}
4286
4287time_t clang_getFileTime(CXFile SFile) {
4288 if (!SFile)
4289 return 0;
4290
4291 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4292 return FEnt->getModificationTime();
4293}
4294
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004295CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004296 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004297 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004298 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004299 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004300
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004301 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004302
4303 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004304 auto File = FMgr.getFile(file_name);
4305 if (!File)
4306 return nullptr;
4307 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004308}
4309
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004310const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4311 size_t *size) {
4312 if (isNotUsableTU(TU)) {
4313 LOG_BAD_TU(TU);
4314 return nullptr;
4315 }
4316
4317 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4318 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4319 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004320 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004321 if (Invalid) {
4322 if (size)
4323 *size = 0;
4324 return nullptr;
4325 }
4326 if (size)
4327 *size = buf->getBufferSize();
4328 return buf->getBufferStart();
4329}
4330
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004331unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4332 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004333 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004334 LOG_BAD_TU(TU);
4335 return 0;
4336 }
4337
4338 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 return 0;
4340
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004341 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004342 FileEntry *FEnt = static_cast<FileEntry *>(file);
4343 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4344 .isFileMultipleIncludeGuarded(FEnt);
4345}
4346
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004347int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4348 if (!file || !outID)
4349 return 1;
4350
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004351 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004352 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4353 outID->data[0] = ID.getDevice();
4354 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004355 outID->data[2] = FEnt->getModificationTime();
4356 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004357}
4358
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004359int clang_File_isEqual(CXFile file1, CXFile file2) {
4360 if (file1 == file2)
4361 return true;
4362
4363 if (!file1 || !file2)
4364 return false;
4365
4366 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4367 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4368 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4369}
4370
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004371CXString clang_File_tryGetRealPathName(CXFile SFile) {
4372 if (!SFile)
4373 return cxstring::createNull();
4374
4375 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4376 return cxstring::createRef(FEnt->tryGetRealPathName());
4377}
4378
Guy Benyei11169dd2012-12-18 14:30:41 +00004379//===----------------------------------------------------------------------===//
4380// CXCursor Operations.
4381//===----------------------------------------------------------------------===//
4382
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004383static const Decl *getDeclFromExpr(const Stmt *E) {
4384 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 return getDeclFromExpr(CE->getSubExpr());
4386
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004387 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004388 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004389 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004391 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004393 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 if (PRE->isExplicitProperty())
4395 return PRE->getExplicitProperty();
4396 // It could be messaging both getter and setter as in:
4397 // ++myobj.myprop;
4398 // in which case prefer to associate the setter since it is less obvious
4399 // from inspecting the source that the setter is going to get called.
4400 if (PRE->isMessagingSetter())
4401 return PRE->getImplicitPropertySetter();
4402 return PRE->getImplicitPropertyGetter();
4403 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004404 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004406 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 if (Expr *Src = OVE->getSourceExpr())
4408 return getDeclFromExpr(Src);
4409
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004410 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004412 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004413 if (!CE->isElidable())
4414 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004415 if (const CXXInheritedCtorInitExpr *CE =
4416 dyn_cast<CXXInheritedCtorInitExpr>(E))
4417 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004418 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 return OME->getMethodDecl();
4420
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004421 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004423 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4425 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004426 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4428 isa<ParmVarDecl>(SizeOfPack->getPack()))
4429 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004430
4431 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004432}
4433
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004434static SourceLocation getLocationFromExpr(const Expr *E) {
4435 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 return getLocationFromExpr(CE->getSubExpr());
4437
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004438 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004440 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004442 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004444 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004446 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004448 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004450
4451 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004452}
4453
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004454extern "C" {
4455
Guy Benyei11169dd2012-12-18 14:30:41 +00004456unsigned clang_visitChildren(CXCursor parent,
4457 CXCursorVisitor visitor,
4458 CXClientData client_data) {
4459 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4460 /*VisitPreprocessorLast=*/false);
4461 return CursorVis.VisitChildren(parent);
4462}
4463
4464#ifndef __has_feature
4465#define __has_feature(x) 0
4466#endif
4467#if __has_feature(blocks)
4468typedef enum CXChildVisitResult
4469 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4470
4471static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4472 CXClientData client_data) {
4473 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4474 return block(cursor, parent);
4475}
4476#else
4477// If we are compiled with a compiler that doesn't have native blocks support,
4478// define and call the block manually, so the
4479typedef struct _CXChildVisitResult
4480{
4481 void *isa;
4482 int flags;
4483 int reserved;
4484 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4485 CXCursor);
4486} *CXCursorVisitorBlock;
4487
4488static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4489 CXClientData client_data) {
4490 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4491 return block->invoke(block, cursor, parent);
4492}
4493#endif
4494
4495
4496unsigned clang_visitChildrenWithBlock(CXCursor parent,
4497 CXCursorVisitorBlock block) {
4498 return clang_visitChildren(parent, visitWithBlock, block);
4499}
4500
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004501static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004503 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004504
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004505 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004507 if (const ObjCPropertyImplDecl *PropImpl =
4508 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004510 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004511
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004512 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004514 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004515
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004516 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 }
4518
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004519 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004520 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004521
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004522 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4524 // and returns different names. NamedDecl returns the class name and
4525 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004526 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004527
4528 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004529 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004530
4531 SmallString<1024> S;
4532 llvm::raw_svector_ostream os(S);
4533 ND->printName(os);
4534
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004535 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004536}
4537
4538CXString clang_getCursorSpelling(CXCursor C) {
4539 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004540 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004541
4542 if (clang_isReference(C.kind)) {
4543 switch (C.kind) {
4544 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004545 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004546 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 }
4548 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004549 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004550 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 }
4552 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004553 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004554 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004555 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004556 }
4557 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004558 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004559 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 }
4561 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004562 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 assert(Type && "Missing type decl");
4564
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004565 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 getAsString());
4567 }
4568 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004569 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 assert(Template && "Missing template decl");
4571
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004572 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 }
4574
4575 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004576 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 assert(NS && "Missing namespace decl");
4578
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004579 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004580 }
4581
4582 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004583 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 assert(Field && "Missing member decl");
4585
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004586 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 }
4588
4589 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004590 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 assert(Label && "Missing label");
4592
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004593 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 }
4595
4596 case CXCursor_OverloadedDeclRef: {
4597 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004598 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4599 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004600 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004601 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004603 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004604 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 OverloadedTemplateStorage *Ovl
4606 = Storage.get<OverloadedTemplateStorage*>();
4607 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004608 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004609 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 }
4611
4612 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004613 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 assert(Var && "Missing variable decl");
4615
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004616 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 }
4618
4619 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004620 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 }
4622 }
4623
4624 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004625 const Expr *E = getCursorExpr(C);
4626
4627 if (C.kind == CXCursor_ObjCStringLiteral ||
4628 C.kind == CXCursor_StringLiteral) {
4629 const StringLiteral *SLit;
4630 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4631 SLit = OSL->getString();
4632 } else {
4633 SLit = cast<StringLiteral>(E);
4634 }
4635 SmallString<256> Buf;
4636 llvm::raw_svector_ostream OS(Buf);
4637 SLit->outputString(OS);
4638 return cxstring::createDup(OS.str());
4639 }
4640
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004641 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 if (D)
4643 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004644 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 }
4646
4647 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004648 const Stmt *S = getCursorStmt(C);
4649 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004650 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004651
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004652 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 }
4654
4655 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004656 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 ->getNameStart());
4658
4659 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004660 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 ->getNameStart());
4662
4663 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004664 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004665
4666 if (clang_isDeclaration(C.kind))
4667 return getDeclSpelling(getCursorDecl(C));
4668
4669 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004670 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004671 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 }
4673
4674 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004675 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004676 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004677 }
4678
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004679 if (C.kind == CXCursor_PackedAttr) {
4680 return cxstring::createRef("packed");
4681 }
4682
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004683 if (C.kind == CXCursor_VisibilityAttr) {
4684 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4685 switch (AA->getVisibility()) {
4686 case VisibilityAttr::VisibilityType::Default:
4687 return cxstring::createRef("default");
4688 case VisibilityAttr::VisibilityType::Hidden:
4689 return cxstring::createRef("hidden");
4690 case VisibilityAttr::VisibilityType::Protected:
4691 return cxstring::createRef("protected");
4692 }
4693 llvm_unreachable("unknown visibility type");
4694 }
4695
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004696 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004697}
4698
4699CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4700 unsigned pieceIndex,
4701 unsigned options) {
4702 if (clang_Cursor_isNull(C))
4703 return clang_getNullRange();
4704
4705 ASTContext &Ctx = getCursorContext(C);
4706
4707 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004708 const Stmt *S = getCursorStmt(C);
4709 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 if (pieceIndex > 0)
4711 return clang_getNullRange();
4712 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4713 }
4714
4715 return clang_getNullRange();
4716 }
4717
4718 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004719 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004720 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4721 if (pieceIndex >= ME->getNumSelectorLocs())
4722 return clang_getNullRange();
4723 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4724 }
4725 }
4726
4727 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4728 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004729 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004730 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4731 if (pieceIndex >= MD->getNumSelectorLocs())
4732 return clang_getNullRange();
4733 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4734 }
4735 }
4736
4737 if (C.kind == CXCursor_ObjCCategoryDecl ||
4738 C.kind == CXCursor_ObjCCategoryImplDecl) {
4739 if (pieceIndex > 0)
4740 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004741 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4743 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004744 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4746 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4747 }
4748
4749 if (C.kind == CXCursor_ModuleImportDecl) {
4750 if (pieceIndex > 0)
4751 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004752 if (const ImportDecl *ImportD =
4753 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004754 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4755 if (!Locs.empty())
4756 return cxloc::translateSourceRange(Ctx,
4757 SourceRange(Locs.front(), Locs.back()));
4758 }
4759 return clang_getNullRange();
4760 }
4761
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004762 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004763 C.kind == CXCursor_ConversionFunction ||
4764 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004765 if (pieceIndex > 0)
4766 return clang_getNullRange();
4767 if (const FunctionDecl *FD =
4768 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4769 DeclarationNameInfo FunctionName = FD->getNameInfo();
4770 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4771 }
4772 return clang_getNullRange();
4773 }
4774
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 // FIXME: A CXCursor_InclusionDirective should give the location of the
4776 // filename, but we don't keep track of this.
4777
4778 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4779 // but we don't keep track of this.
4780
4781 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4782 // but we don't keep track of this.
4783
4784 // Default handling, give the location of the cursor.
4785
4786 if (pieceIndex > 0)
4787 return clang_getNullRange();
4788
4789 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4790 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4791 return cxloc::translateSourceRange(Ctx, Loc);
4792}
4793
Eli Bendersky44a206f2014-07-31 18:04:56 +00004794CXString clang_Cursor_getMangling(CXCursor C) {
4795 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4796 return cxstring::createEmpty();
4797
Eli Bendersky44a206f2014-07-31 18:04:56 +00004798 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004799 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004800 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4801 return cxstring::createEmpty();
4802
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004803 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004804 ASTNameGenerator ASTNameGen(Ctx);
4805 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004806}
4807
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004808CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4809 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4810 return nullptr;
4811
4812 const Decl *D = getCursorDecl(C);
4813 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4814 return nullptr;
4815
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004816 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004817 ASTNameGenerator ASTNameGen(Ctx);
4818 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004819 return cxstring::createSet(Manglings);
4820}
4821
Dave Lee1a532c92017-09-22 16:58:57 +00004822CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4823 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4824 return nullptr;
4825
4826 const Decl *D = getCursorDecl(C);
4827 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4828 return nullptr;
4829
4830 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004831 ASTNameGenerator ASTNameGen(Ctx);
4832 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004833 return cxstring::createSet(Manglings);
4834}
4835
Jonathan Coe45ef5032018-01-16 10:19:56 +00004836CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4837 if (clang_Cursor_isNull(C))
4838 return 0;
4839 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4840}
4841
4842void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4843 if (Policy)
4844 delete static_cast<PrintingPolicy *>(Policy);
4845}
4846
4847unsigned
4848clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4849 enum CXPrintingPolicyProperty Property) {
4850 if (!Policy)
4851 return 0;
4852
4853 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4854 switch (Property) {
4855 case CXPrintingPolicy_Indentation:
4856 return P->Indentation;
4857 case CXPrintingPolicy_SuppressSpecifiers:
4858 return P->SuppressSpecifiers;
4859 case CXPrintingPolicy_SuppressTagKeyword:
4860 return P->SuppressTagKeyword;
4861 case CXPrintingPolicy_IncludeTagDefinition:
4862 return P->IncludeTagDefinition;
4863 case CXPrintingPolicy_SuppressScope:
4864 return P->SuppressScope;
4865 case CXPrintingPolicy_SuppressUnwrittenScope:
4866 return P->SuppressUnwrittenScope;
4867 case CXPrintingPolicy_SuppressInitializers:
4868 return P->SuppressInitializers;
4869 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4870 return P->ConstantArraySizeAsWritten;
4871 case CXPrintingPolicy_AnonymousTagLocations:
4872 return P->AnonymousTagLocations;
4873 case CXPrintingPolicy_SuppressStrongLifetime:
4874 return P->SuppressStrongLifetime;
4875 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4876 return P->SuppressLifetimeQualifiers;
4877 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4878 return P->SuppressTemplateArgsInCXXConstructors;
4879 case CXPrintingPolicy_Bool:
4880 return P->Bool;
4881 case CXPrintingPolicy_Restrict:
4882 return P->Restrict;
4883 case CXPrintingPolicy_Alignof:
4884 return P->Alignof;
4885 case CXPrintingPolicy_UnderscoreAlignof:
4886 return P->UnderscoreAlignof;
4887 case CXPrintingPolicy_UseVoidForZeroParams:
4888 return P->UseVoidForZeroParams;
4889 case CXPrintingPolicy_TerseOutput:
4890 return P->TerseOutput;
4891 case CXPrintingPolicy_PolishForDeclaration:
4892 return P->PolishForDeclaration;
4893 case CXPrintingPolicy_Half:
4894 return P->Half;
4895 case CXPrintingPolicy_MSWChar:
4896 return P->MSWChar;
4897 case CXPrintingPolicy_IncludeNewlines:
4898 return P->IncludeNewlines;
4899 case CXPrintingPolicy_MSVCFormatting:
4900 return P->MSVCFormatting;
4901 case CXPrintingPolicy_ConstantsAsWritten:
4902 return P->ConstantsAsWritten;
4903 case CXPrintingPolicy_SuppressImplicitBase:
4904 return P->SuppressImplicitBase;
4905 case CXPrintingPolicy_FullyQualifiedName:
4906 return P->FullyQualifiedName;
4907 }
4908
4909 assert(false && "Invalid CXPrintingPolicyProperty");
4910 return 0;
4911}
4912
4913void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4914 enum CXPrintingPolicyProperty Property,
4915 unsigned Value) {
4916 if (!Policy)
4917 return;
4918
4919 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4920 switch (Property) {
4921 case CXPrintingPolicy_Indentation:
4922 P->Indentation = Value;
4923 return;
4924 case CXPrintingPolicy_SuppressSpecifiers:
4925 P->SuppressSpecifiers = Value;
4926 return;
4927 case CXPrintingPolicy_SuppressTagKeyword:
4928 P->SuppressTagKeyword = Value;
4929 return;
4930 case CXPrintingPolicy_IncludeTagDefinition:
4931 P->IncludeTagDefinition = Value;
4932 return;
4933 case CXPrintingPolicy_SuppressScope:
4934 P->SuppressScope = Value;
4935 return;
4936 case CXPrintingPolicy_SuppressUnwrittenScope:
4937 P->SuppressUnwrittenScope = Value;
4938 return;
4939 case CXPrintingPolicy_SuppressInitializers:
4940 P->SuppressInitializers = Value;
4941 return;
4942 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4943 P->ConstantArraySizeAsWritten = Value;
4944 return;
4945 case CXPrintingPolicy_AnonymousTagLocations:
4946 P->AnonymousTagLocations = Value;
4947 return;
4948 case CXPrintingPolicy_SuppressStrongLifetime:
4949 P->SuppressStrongLifetime = Value;
4950 return;
4951 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4952 P->SuppressLifetimeQualifiers = Value;
4953 return;
4954 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4955 P->SuppressTemplateArgsInCXXConstructors = Value;
4956 return;
4957 case CXPrintingPolicy_Bool:
4958 P->Bool = Value;
4959 return;
4960 case CXPrintingPolicy_Restrict:
4961 P->Restrict = Value;
4962 return;
4963 case CXPrintingPolicy_Alignof:
4964 P->Alignof = Value;
4965 return;
4966 case CXPrintingPolicy_UnderscoreAlignof:
4967 P->UnderscoreAlignof = Value;
4968 return;
4969 case CXPrintingPolicy_UseVoidForZeroParams:
4970 P->UseVoidForZeroParams = Value;
4971 return;
4972 case CXPrintingPolicy_TerseOutput:
4973 P->TerseOutput = Value;
4974 return;
4975 case CXPrintingPolicy_PolishForDeclaration:
4976 P->PolishForDeclaration = Value;
4977 return;
4978 case CXPrintingPolicy_Half:
4979 P->Half = Value;
4980 return;
4981 case CXPrintingPolicy_MSWChar:
4982 P->MSWChar = Value;
4983 return;
4984 case CXPrintingPolicy_IncludeNewlines:
4985 P->IncludeNewlines = Value;
4986 return;
4987 case CXPrintingPolicy_MSVCFormatting:
4988 P->MSVCFormatting = Value;
4989 return;
4990 case CXPrintingPolicy_ConstantsAsWritten:
4991 P->ConstantsAsWritten = Value;
4992 return;
4993 case CXPrintingPolicy_SuppressImplicitBase:
4994 P->SuppressImplicitBase = Value;
4995 return;
4996 case CXPrintingPolicy_FullyQualifiedName:
4997 P->FullyQualifiedName = Value;
4998 return;
4999 }
5000
5001 assert(false && "Invalid CXPrintingPolicyProperty");
5002}
5003
5004CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
5005 if (clang_Cursor_isNull(C))
5006 return cxstring::createEmpty();
5007
5008 if (clang_isDeclaration(C.kind)) {
5009 const Decl *D = getCursorDecl(C);
5010 if (!D)
5011 return cxstring::createEmpty();
5012
5013 SmallString<128> Str;
5014 llvm::raw_svector_ostream OS(Str);
5015 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
5016 D->print(OS, UserPolicy ? *UserPolicy
5017 : getCursorContext(C).getPrintingPolicy());
5018
5019 return cxstring::createDup(OS.str());
5020 }
5021
5022 return cxstring::createEmpty();
5023}
5024
Guy Benyei11169dd2012-12-18 14:30:41 +00005025CXString clang_getCursorDisplayName(CXCursor C) {
5026 if (!clang_isDeclaration(C.kind))
5027 return clang_getCursorSpelling(C);
5028
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005029 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00005031 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005032
5033 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005034 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 D = FunTmpl->getTemplatedDecl();
5036
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005037 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 SmallString<64> Str;
5039 llvm::raw_svector_ostream OS(Str);
5040 OS << *Function;
5041 if (Function->getPrimaryTemplate())
5042 OS << "<>";
5043 OS << "(";
5044 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5045 if (I)
5046 OS << ", ";
5047 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5048 }
5049
5050 if (Function->isVariadic()) {
5051 if (Function->getNumParams())
5052 OS << ", ";
5053 OS << "...";
5054 }
5055 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005056 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 }
5058
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005059 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 SmallString<64> Str;
5061 llvm::raw_svector_ostream OS(Str);
5062 OS << *ClassTemplate;
5063 OS << "<";
5064 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5065 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5066 if (I)
5067 OS << ", ";
5068
5069 NamedDecl *Param = Params->getParam(I);
5070 if (Param->getIdentifier()) {
5071 OS << Param->getIdentifier()->getName();
5072 continue;
5073 }
5074
5075 // There is no parameter name, which makes this tricky. Try to come up
5076 // with something useful that isn't too long.
5077 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Saar Razff1e0fc2020-01-15 02:48:42 +02005078 if (const auto *TC = TTP->getTypeConstraint()) {
5079 TC->getConceptNameInfo().printName(OS, Policy);
5080 if (TC->hasExplicitTemplateArgs())
5081 OS << "<...>";
5082 } else
5083 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 else if (NonTypeTemplateParmDecl *NTTP
5085 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5086 OS << NTTP->getType().getAsString(Policy);
5087 else
5088 OS << "template<...> class";
5089 }
5090
5091 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005092 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 }
5094
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005095 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5097 // If the type was explicitly written, use that.
5098 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005099 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005100
Benjamin Kramer9170e912013-02-22 15:46:01 +00005101 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 llvm::raw_svector_ostream OS(Str);
5103 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005104 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5105 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005106 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 }
5108
5109 return clang_getCursorSpelling(C);
5110}
5111
5112CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5113 switch (Kind) {
5114 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005178 case CXCursor_FixedPointLiteral:
5179 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005194 case CXCursor_OMPArraySectionExpr:
5195 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005237 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005245 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005246 case CXCursor_ObjCAvailabilityCheckExpr:
5247 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005248 case CXCursor_ObjCSelfExpr:
5249 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005251 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005253 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005255 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005257 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005259 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005261 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005263 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005265 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005267 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005269 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005271 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005273 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005275 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005276 case CXCursor_BuiltinBitCastExpr:
5277 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005279 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005281 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005283 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005285 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005287 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005289 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005291 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005293 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005295 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005297 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005299 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005301 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005303 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005304 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005305 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005307 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005309 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005311 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005313 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005314 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005315 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005317 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005319 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005320 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005321 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005323 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005324 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005325 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005327 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005328 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005329 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005330 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005331 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005332 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005333 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005335 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005336 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005337 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005338 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005339 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005340 case CXCursor_SEHLeaveStmt:
5341 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005342 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005343 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005345 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005346 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005347 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005348 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005349 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005350 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005351 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005352 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005353 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005354 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005355 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005356 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005357 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005358 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005359 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005360 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005361 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005362 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005363 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005364 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005365 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005366 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005367 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005368 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005369 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005370 case CXCursor_PackedAttr:
5371 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005372 case CXCursor_PureAttr:
5373 return cxstring::createRef("attribute(pure)");
5374 case CXCursor_ConstAttr:
5375 return cxstring::createRef("attribute(const)");
5376 case CXCursor_NoDuplicateAttr:
5377 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005378 case CXCursor_CUDAConstantAttr:
5379 return cxstring::createRef("attribute(constant)");
5380 case CXCursor_CUDADeviceAttr:
5381 return cxstring::createRef("attribute(device)");
5382 case CXCursor_CUDAGlobalAttr:
5383 return cxstring::createRef("attribute(global)");
5384 case CXCursor_CUDAHostAttr:
5385 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005386 case CXCursor_CUDASharedAttr:
5387 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005388 case CXCursor_VisibilityAttr:
5389 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005390 case CXCursor_DLLExport:
5391 return cxstring::createRef("attribute(dllexport)");
5392 case CXCursor_DLLImport:
5393 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005394 case CXCursor_NSReturnsRetained:
5395 return cxstring::createRef("attribute(ns_returns_retained)");
5396 case CXCursor_NSReturnsNotRetained:
5397 return cxstring::createRef("attribute(ns_returns_not_retained)");
5398 case CXCursor_NSReturnsAutoreleased:
5399 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5400 case CXCursor_NSConsumesSelf:
5401 return cxstring::createRef("attribute(ns_consumes_self)");
5402 case CXCursor_NSConsumed:
5403 return cxstring::createRef("attribute(ns_consumed)");
5404 case CXCursor_ObjCException:
5405 return cxstring::createRef("attribute(objc_exception)");
5406 case CXCursor_ObjCNSObject:
5407 return cxstring::createRef("attribute(NSObject)");
5408 case CXCursor_ObjCIndependentClass:
5409 return cxstring::createRef("attribute(objc_independent_class)");
5410 case CXCursor_ObjCPreciseLifetime:
5411 return cxstring::createRef("attribute(objc_precise_lifetime)");
5412 case CXCursor_ObjCReturnsInnerPointer:
5413 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5414 case CXCursor_ObjCRequiresSuper:
5415 return cxstring::createRef("attribute(objc_requires_super)");
5416 case CXCursor_ObjCRootClass:
5417 return cxstring::createRef("attribute(objc_root_class)");
5418 case CXCursor_ObjCSubclassingRestricted:
5419 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5420 case CXCursor_ObjCExplicitProtocolImpl:
5421 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5422 case CXCursor_ObjCDesignatedInitializer:
5423 return cxstring::createRef("attribute(objc_designated_initializer)");
5424 case CXCursor_ObjCRuntimeVisible:
5425 return cxstring::createRef("attribute(objc_runtime_visible)");
5426 case CXCursor_ObjCBoxable:
5427 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005428 case CXCursor_FlagEnum:
5429 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005431 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005432 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005433 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005434 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005435 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005436 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005437 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005438 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005439 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005440 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005441 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005442 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005443 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005444 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005445 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005446 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005447 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005448 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005449 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005450 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005451 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005452 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005453 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005454 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005455 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005457 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005458 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005459 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005460 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005461 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005462 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005463 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005464 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005465 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005466 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005467 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005468 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005469 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005470 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005471 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005472 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005473 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005474 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005475 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005476 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005477 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005478 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005479 return cxstring::createRef("OMPParallelDirective");
5480 case CXCursor_OMPSimdDirective:
5481 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005482 case CXCursor_OMPForDirective:
5483 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005484 case CXCursor_OMPForSimdDirective:
5485 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005486 case CXCursor_OMPSectionsDirective:
5487 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005488 case CXCursor_OMPSectionDirective:
5489 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005490 case CXCursor_OMPSingleDirective:
5491 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005492 case CXCursor_OMPMasterDirective:
5493 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005494 case CXCursor_OMPCriticalDirective:
5495 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005496 case CXCursor_OMPParallelForDirective:
5497 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005498 case CXCursor_OMPParallelForSimdDirective:
5499 return cxstring::createRef("OMPParallelForSimdDirective");
cchen47d60942019-12-05 13:43:48 -05005500 case CXCursor_OMPParallelMasterDirective:
5501 return cxstring::createRef("OMPParallelMasterDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005502 case CXCursor_OMPParallelSectionsDirective:
5503 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005504 case CXCursor_OMPTaskDirective:
5505 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005506 case CXCursor_OMPTaskyieldDirective:
5507 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005508 case CXCursor_OMPBarrierDirective:
5509 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005510 case CXCursor_OMPTaskwaitDirective:
5511 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005512 case CXCursor_OMPTaskgroupDirective:
5513 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005514 case CXCursor_OMPFlushDirective:
5515 return cxstring::createRef("OMPFlushDirective");
Alexey Bataevc112e942020-02-28 09:52:15 -05005516 case CXCursor_OMPDepobjDirective:
5517 return cxstring::createRef("OMPDepobjDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005518 case CXCursor_OMPOrderedDirective:
5519 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005520 case CXCursor_OMPAtomicDirective:
5521 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005522 case CXCursor_OMPTargetDirective:
5523 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005524 case CXCursor_OMPTargetDataDirective:
5525 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005526 case CXCursor_OMPTargetEnterDataDirective:
5527 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005528 case CXCursor_OMPTargetExitDataDirective:
5529 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005530 case CXCursor_OMPTargetParallelDirective:
5531 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005532 case CXCursor_OMPTargetParallelForDirective:
5533 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005534 case CXCursor_OMPTargetUpdateDirective:
5535 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005536 case CXCursor_OMPTeamsDirective:
5537 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005538 case CXCursor_OMPCancellationPointDirective:
5539 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005540 case CXCursor_OMPCancelDirective:
5541 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005542 case CXCursor_OMPTaskLoopDirective:
5543 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005544 case CXCursor_OMPTaskLoopSimdDirective:
5545 return cxstring::createRef("OMPTaskLoopSimdDirective");
Alexey Bataev60e51c42019-10-10 20:13:02 +00005546 case CXCursor_OMPMasterTaskLoopDirective:
5547 return cxstring::createRef("OMPMasterTaskLoopDirective");
Alexey Bataevb8552ab2019-10-18 16:47:35 +00005548 case CXCursor_OMPMasterTaskLoopSimdDirective:
5549 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
Alexey Bataev5bbcead2019-10-14 17:17:41 +00005550 case CXCursor_OMPParallelMasterTaskLoopDirective:
5551 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
Alexey Bataev14a388f2019-10-25 10:27:13 -04005552 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5553 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005554 case CXCursor_OMPDistributeDirective:
5555 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005556 case CXCursor_OMPDistributeParallelForDirective:
5557 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005558 case CXCursor_OMPDistributeParallelForSimdDirective:
5559 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005560 case CXCursor_OMPDistributeSimdDirective:
5561 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005562 case CXCursor_OMPTargetParallelForSimdDirective:
5563 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005564 case CXCursor_OMPTargetSimdDirective:
5565 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005566 case CXCursor_OMPTeamsDistributeDirective:
5567 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005568 case CXCursor_OMPTeamsDistributeSimdDirective:
5569 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005570 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5571 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005572 case CXCursor_OMPTeamsDistributeParallelForDirective:
5573 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005574 case CXCursor_OMPTargetTeamsDirective:
5575 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005576 case CXCursor_OMPTargetTeamsDistributeDirective:
5577 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005578 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5579 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005580 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5581 return cxstring::createRef(
5582 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005583 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5584 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005585 case CXCursor_OverloadCandidate:
5586 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005587 case CXCursor_TypeAliasTemplateDecl:
5588 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005589 case CXCursor_StaticAssert:
5590 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005591 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005592 return cxstring::createRef("FriendDecl");
5593 case CXCursor_ConvergentAttr:
5594 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005595 case CXCursor_WarnUnusedAttr:
5596 return cxstring::createRef("attribute(warn_unused)");
5597 case CXCursor_WarnUnusedResultAttr:
5598 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005599 case CXCursor_AlignedAttr:
5600 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005601 }
5602
5603 llvm_unreachable("Unhandled CXCursorKind");
5604}
5605
5606struct GetCursorData {
5607 SourceLocation TokenBeginLoc;
5608 bool PointsAtMacroArgExpansion;
5609 bool VisitedObjCPropertyImplDecl;
5610 SourceLocation VisitedDeclaratorDeclStartLoc;
5611 CXCursor &BestCursor;
5612
5613 GetCursorData(SourceManager &SM,
5614 SourceLocation tokenBegin, CXCursor &outputCursor)
5615 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5616 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5617 VisitedObjCPropertyImplDecl = false;
5618 }
5619};
5620
5621static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5622 CXCursor parent,
5623 CXClientData client_data) {
5624 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5625 CXCursor *BestCursor = &Data->BestCursor;
5626
5627 // If we point inside a macro argument we should provide info of what the
5628 // token is so use the actual cursor, don't replace it with a macro expansion
5629 // cursor.
5630 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5631 return CXChildVisit_Recurse;
5632
5633 if (clang_isDeclaration(cursor.kind)) {
5634 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005635 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005636 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5637 if (MD->isImplicit())
5638 return CXChildVisit_Break;
5639
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005640 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005641 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5642 // Check that when we have multiple @class references in the same line,
5643 // that later ones do not override the previous ones.
5644 // If we have:
5645 // @class Foo, Bar;
5646 // source ranges for both start at '@', so 'Bar' will end up overriding
5647 // 'Foo' even though the cursor location was at 'Foo'.
5648 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5649 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005650 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005651 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5652 if (PrevID != ID &&
5653 !PrevID->isThisDeclarationADefinition() &&
5654 !ID->isThisDeclarationADefinition())
5655 return CXChildVisit_Break;
5656 }
5657
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005658 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005659 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5660 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5661 // Check that when we have multiple declarators in the same line,
5662 // that later ones do not override the previous ones.
5663 // If we have:
5664 // int Foo, Bar;
5665 // source ranges for both start at 'int', so 'Bar' will end up overriding
5666 // 'Foo' even though the cursor location was at 'Foo'.
5667 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5668 return CXChildVisit_Break;
5669 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5670
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005671 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005672 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5673 (void)PropImp;
5674 // Check that when we have multiple @synthesize in the same line,
5675 // that later ones do not override the previous ones.
5676 // If we have:
5677 // @synthesize Foo, Bar;
5678 // source ranges for both start at '@', so 'Bar' will end up overriding
5679 // 'Foo' even though the cursor location was at 'Foo'.
5680 if (Data->VisitedObjCPropertyImplDecl)
5681 return CXChildVisit_Break;
5682 Data->VisitedObjCPropertyImplDecl = true;
5683 }
5684 }
5685
5686 if (clang_isExpression(cursor.kind) &&
5687 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005688 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005689 // Avoid having the cursor of an expression replace the declaration cursor
5690 // when the expression source range overlaps the declaration range.
5691 // This can happen for C++ constructor expressions whose range generally
5692 // include the variable declaration, e.g.:
5693 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5694 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5695 D->getLocation() == Data->TokenBeginLoc)
5696 return CXChildVisit_Break;
5697 }
5698 }
5699
5700 // If our current best cursor is the construction of a temporary object,
5701 // don't replace that cursor with a type reference, because we want
5702 // clang_getCursor() to point at the constructor.
5703 if (clang_isExpression(BestCursor->kind) &&
5704 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5705 cursor.kind == CXCursor_TypeRef) {
5706 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5707 // as having the actual point on the type reference.
5708 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5709 return CXChildVisit_Recurse;
5710 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005711
5712 // If we already have an Objective-C superclass reference, don't
5713 // update it further.
5714 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5715 return CXChildVisit_Break;
5716
Guy Benyei11169dd2012-12-18 14:30:41 +00005717 *BestCursor = cursor;
5718 return CXChildVisit_Recurse;
5719}
5720
5721CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005722 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005723 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005724 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005725 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005726
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005727 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005728 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5729
5730 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5731 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5732
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005733 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005734 CXFile SearchFile;
5735 unsigned SearchLine, SearchColumn;
5736 CXFile ResultFile;
5737 unsigned ResultLine, ResultColumn;
5738 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5739 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5740 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005741
5742 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5743 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005744 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005745 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005746 SearchFileName = clang_getFileName(SearchFile);
5747 ResultFileName = clang_getFileName(ResultFile);
5748 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5749 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005750 *Log << llvm::format("(%s:%d:%d) = %s",
5751 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5752 clang_getCString(KindSpelling))
5753 << llvm::format("(%s:%d:%d):%s%s",
5754 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5755 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005756 clang_disposeString(SearchFileName);
5757 clang_disposeString(ResultFileName);
5758 clang_disposeString(KindSpelling);
5759 clang_disposeString(USR);
5760
5761 CXCursor Definition = clang_getCursorDefinition(Result);
5762 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5763 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5764 CXString DefinitionKindSpelling
5765 = clang_getCursorKindSpelling(Definition.kind);
5766 CXFile DefinitionFile;
5767 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005768 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005769 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005770 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005771 *Log << llvm::format(" -> %s(%s:%d:%d)",
5772 clang_getCString(DefinitionKindSpelling),
5773 clang_getCString(DefinitionFileName),
5774 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005775 clang_disposeString(DefinitionFileName);
5776 clang_disposeString(DefinitionKindSpelling);
5777 }
5778 }
5779
5780 return Result;
5781}
5782
5783CXCursor clang_getNullCursor(void) {
5784 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5785}
5786
5787unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005788 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5789 // can't set consistently. For example, when visiting a DeclStmt we will set
5790 // it but we don't set it on the result of clang_getCursorDefinition for
5791 // a reference of the same declaration.
5792 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5793 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5794 // to provide that kind of info.
5795 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005796 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005797 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005798 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005799
Guy Benyei11169dd2012-12-18 14:30:41 +00005800 return X == Y;
5801}
5802
5803unsigned clang_hashCursor(CXCursor C) {
5804 unsigned Index = 0;
5805 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5806 Index = 1;
5807
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005808 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005809 std::make_pair(C.kind, C.data[Index]));
5810}
5811
5812unsigned clang_isInvalid(enum CXCursorKind K) {
5813 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5814}
5815
5816unsigned clang_isDeclaration(enum CXCursorKind K) {
5817 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005818 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5819}
5820
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005821unsigned clang_isInvalidDeclaration(CXCursor C) {
5822 if (clang_isDeclaration(C.kind)) {
5823 if (const Decl *D = getCursorDecl(C))
5824 return D->isInvalidDecl();
5825 }
5826
5827 return 0;
5828}
5829
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005830unsigned clang_isReference(enum CXCursorKind K) {
5831 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5832}
Guy Benyei11169dd2012-12-18 14:30:41 +00005833
5834unsigned clang_isExpression(enum CXCursorKind K) {
5835 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5836}
5837
5838unsigned clang_isStatement(enum CXCursorKind K) {
5839 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5840}
5841
5842unsigned clang_isAttribute(enum CXCursorKind K) {
5843 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5844}
5845
5846unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5847 return K == CXCursor_TranslationUnit;
5848}
5849
5850unsigned clang_isPreprocessing(enum CXCursorKind K) {
5851 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5852}
5853
5854unsigned clang_isUnexposed(enum CXCursorKind K) {
5855 switch (K) {
5856 case CXCursor_UnexposedDecl:
5857 case CXCursor_UnexposedExpr:
5858 case CXCursor_UnexposedStmt:
5859 case CXCursor_UnexposedAttr:
5860 return true;
5861 default:
5862 return false;
5863 }
5864}
5865
5866CXCursorKind clang_getCursorKind(CXCursor C) {
5867 return C.kind;
5868}
5869
5870CXSourceLocation clang_getCursorLocation(CXCursor C) {
5871 if (clang_isReference(C.kind)) {
5872 switch (C.kind) {
5873 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005874 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005875 = getCursorObjCSuperClassRef(C);
5876 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5877 }
5878
5879 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005880 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005881 = getCursorObjCProtocolRef(C);
5882 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5883 }
5884
5885 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005886 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005887 = getCursorObjCClassRef(C);
5888 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5889 }
5890
5891 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005892 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005893 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5894 }
5895
5896 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005897 std::pair<const TemplateDecl *, SourceLocation> P =
5898 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005899 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5900 }
5901
5902 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005903 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005904 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5905 }
5906
5907 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005908 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005909 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5910 }
5911
5912 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005913 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005914 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5915 }
5916
5917 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005918 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005919 if (!BaseSpec)
5920 return clang_getNullLocation();
5921
5922 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5923 return cxloc::translateSourceLocation(getCursorContext(C),
5924 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005925
Guy Benyei11169dd2012-12-18 14:30:41 +00005926 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005927 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005928 }
5929
5930 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005931 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005932 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5933 }
5934
5935 case CXCursor_OverloadedDeclRef:
5936 return cxloc::translateSourceLocation(getCursorContext(C),
5937 getCursorOverloadedDeclRef(C).second);
5938
5939 default:
5940 // FIXME: Need a way to enumerate all non-reference cases.
5941 llvm_unreachable("Missed a reference kind");
5942 }
5943 }
5944
5945 if (clang_isExpression(C.kind))
5946 return cxloc::translateSourceLocation(getCursorContext(C),
5947 getLocationFromExpr(getCursorExpr(C)));
5948
5949 if (clang_isStatement(C.kind))
5950 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005951 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005952
5953 if (C.kind == CXCursor_PreprocessingDirective) {
5954 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5955 return cxloc::translateSourceLocation(getCursorContext(C), L);
5956 }
5957
5958 if (C.kind == CXCursor_MacroExpansion) {
5959 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005960 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005961 return cxloc::translateSourceLocation(getCursorContext(C), L);
5962 }
5963
5964 if (C.kind == CXCursor_MacroDefinition) {
5965 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5966 return cxloc::translateSourceLocation(getCursorContext(C), L);
5967 }
5968
5969 if (C.kind == CXCursor_InclusionDirective) {
5970 SourceLocation L
5971 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5972 return cxloc::translateSourceLocation(getCursorContext(C), L);
5973 }
5974
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005975 if (clang_isAttribute(C.kind)) {
5976 SourceLocation L
5977 = cxcursor::getCursorAttr(C)->getLocation();
5978 return cxloc::translateSourceLocation(getCursorContext(C), L);
5979 }
5980
Guy Benyei11169dd2012-12-18 14:30:41 +00005981 if (!clang_isDeclaration(C.kind))
5982 return clang_getNullLocation();
5983
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005984 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005985 if (!D)
5986 return clang_getNullLocation();
5987
5988 SourceLocation Loc = D->getLocation();
5989 // FIXME: Multiple variables declared in a single declaration
5990 // currently lack the information needed to correctly determine their
5991 // ranges when accounting for the type-specifier. We use context
5992 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5993 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005994 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005995 if (!cxcursor::isFirstInDeclGroup(C))
5996 Loc = VD->getLocation();
5997 }
5998
5999 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006000 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006001 Loc = MD->getSelectorStartLoc();
6002
6003 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
6004}
6005
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00006006} // end extern "C"
6007
Guy Benyei11169dd2012-12-18 14:30:41 +00006008CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
6009 assert(TU);
6010
6011 // Guard against an invalid SourceLocation, or we may assert in one
6012 // of the following calls.
6013 if (SLoc.isInvalid())
6014 return clang_getNullCursor();
6015
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006016 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006017
6018 // Translate the given source location to make it point at the beginning of
6019 // the token under the cursor.
6020 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
6021 CXXUnit->getASTContext().getLangOpts());
6022
6023 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
6024 if (SLoc.isValid()) {
6025 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
6026 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
6027 /*VisitPreprocessorLast=*/true,
6028 /*VisitIncludedEntities=*/false,
6029 SourceLocation(SLoc));
6030 CursorVis.visitFileRegion();
6031 }
6032
6033 return Result;
6034}
6035
6036static SourceRange getRawCursorExtent(CXCursor C) {
6037 if (clang_isReference(C.kind)) {
6038 switch (C.kind) {
6039 case CXCursor_ObjCSuperClassRef:
6040 return getCursorObjCSuperClassRef(C).second;
6041
6042 case CXCursor_ObjCProtocolRef:
6043 return getCursorObjCProtocolRef(C).second;
6044
6045 case CXCursor_ObjCClassRef:
6046 return getCursorObjCClassRef(C).second;
6047
6048 case CXCursor_TypeRef:
6049 return getCursorTypeRef(C).second;
6050
6051 case CXCursor_TemplateRef:
6052 return getCursorTemplateRef(C).second;
6053
6054 case CXCursor_NamespaceRef:
6055 return getCursorNamespaceRef(C).second;
6056
6057 case CXCursor_MemberRef:
6058 return getCursorMemberRef(C).second;
6059
6060 case CXCursor_CXXBaseSpecifier:
6061 return getCursorCXXBaseSpecifier(C)->getSourceRange();
6062
6063 case CXCursor_LabelRef:
6064 return getCursorLabelRef(C).second;
6065
6066 case CXCursor_OverloadedDeclRef:
6067 return getCursorOverloadedDeclRef(C).second;
6068
6069 case CXCursor_VariableRef:
6070 return getCursorVariableRef(C).second;
6071
6072 default:
6073 // FIXME: Need a way to enumerate all non-reference cases.
6074 llvm_unreachable("Missed a reference kind");
6075 }
6076 }
6077
6078 if (clang_isExpression(C.kind))
6079 return getCursorExpr(C)->getSourceRange();
6080
6081 if (clang_isStatement(C.kind))
6082 return getCursorStmt(C)->getSourceRange();
6083
6084 if (clang_isAttribute(C.kind))
6085 return getCursorAttr(C)->getRange();
6086
6087 if (C.kind == CXCursor_PreprocessingDirective)
6088 return cxcursor::getCursorPreprocessingDirective(C);
6089
6090 if (C.kind == CXCursor_MacroExpansion) {
6091 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006092 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 return TU->mapRangeFromPreamble(Range);
6094 }
6095
6096 if (C.kind == CXCursor_MacroDefinition) {
6097 ASTUnit *TU = getCursorASTUnit(C);
6098 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6099 return TU->mapRangeFromPreamble(Range);
6100 }
6101
6102 if (C.kind == CXCursor_InclusionDirective) {
6103 ASTUnit *TU = getCursorASTUnit(C);
6104 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6105 return TU->mapRangeFromPreamble(Range);
6106 }
6107
6108 if (C.kind == CXCursor_TranslationUnit) {
6109 ASTUnit *TU = getCursorASTUnit(C);
6110 FileID MainID = TU->getSourceManager().getMainFileID();
6111 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6112 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6113 return SourceRange(Start, End);
6114 }
6115
6116 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006117 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006118 if (!D)
6119 return SourceRange();
6120
6121 SourceRange R = D->getSourceRange();
6122 // FIXME: Multiple variables declared in a single declaration
6123 // currently lack the information needed to correctly determine their
6124 // ranges when accounting for the type-specifier. We use context
6125 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6126 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006127 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006128 if (!cxcursor::isFirstInDeclGroup(C))
6129 R.setBegin(VD->getLocation());
6130 }
6131 return R;
6132 }
6133 return SourceRange();
6134}
6135
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006136/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006137/// the decl-specifier-seq for declarations.
6138static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6139 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006140 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006141 if (!D)
6142 return SourceRange();
6143
6144 SourceRange R = D->getSourceRange();
6145
6146 // Adjust the start of the location for declarations preceded by
6147 // declaration specifiers.
6148 SourceLocation StartLoc;
6149 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6150 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006151 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006152 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006153 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006154 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006155 }
6156
6157 if (StartLoc.isValid() && R.getBegin().isValid() &&
6158 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6159 R.setBegin(StartLoc);
6160
6161 // FIXME: Multiple variables declared in a single declaration
6162 // currently lack the information needed to correctly determine their
6163 // ranges when accounting for the type-specifier. We use context
6164 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6165 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006166 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006167 if (!cxcursor::isFirstInDeclGroup(C))
6168 R.setBegin(VD->getLocation());
6169 }
6170
6171 return R;
6172 }
6173
6174 return getRawCursorExtent(C);
6175}
6176
Guy Benyei11169dd2012-12-18 14:30:41 +00006177CXSourceRange clang_getCursorExtent(CXCursor C) {
6178 SourceRange R = getRawCursorExtent(C);
6179 if (R.isInvalid())
6180 return clang_getNullRange();
6181
6182 return cxloc::translateSourceRange(getCursorContext(C), R);
6183}
6184
6185CXCursor clang_getCursorReferenced(CXCursor C) {
6186 if (clang_isInvalid(C.kind))
6187 return clang_getNullCursor();
6188
6189 CXTranslationUnit tu = getCursorTU(C);
6190 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006191 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006192 if (!D)
6193 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006194 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006195 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006196 if (const ObjCPropertyImplDecl *PropImpl =
6197 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006198 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6199 return MakeCXCursor(Property, tu);
6200
6201 return C;
6202 }
6203
6204 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006205 const Expr *E = getCursorExpr(C);
6206 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006207 if (D) {
6208 CXCursor declCursor = MakeCXCursor(D, tu);
6209 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6210 declCursor);
6211 return declCursor;
6212 }
6213
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006214 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006215 return MakeCursorOverloadedDeclRef(Ovl, tu);
6216
6217 return clang_getNullCursor();
6218 }
6219
6220 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006221 const Stmt *S = getCursorStmt(C);
6222 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006223 if (LabelDecl *label = Goto->getLabel())
6224 if (LabelStmt *labelS = label->getStmt())
6225 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6226
6227 return clang_getNullCursor();
6228 }
Richard Smith66a81862015-05-04 02:25:31 +00006229
Guy Benyei11169dd2012-12-18 14:30:41 +00006230 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006231 if (const MacroDefinitionRecord *Def =
6232 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006233 return MakeMacroDefinitionCursor(Def, tu);
6234 }
6235
6236 if (!clang_isReference(C.kind))
6237 return clang_getNullCursor();
6238
6239 switch (C.kind) {
6240 case CXCursor_ObjCSuperClassRef:
6241 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6242
6243 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006244 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6245 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006246 return MakeCXCursor(Def, tu);
6247
6248 return MakeCXCursor(Prot, tu);
6249 }
6250
6251 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006252 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6253 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006254 return MakeCXCursor(Def, tu);
6255
6256 return MakeCXCursor(Class, tu);
6257 }
6258
6259 case CXCursor_TypeRef:
6260 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6261
6262 case CXCursor_TemplateRef:
6263 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6264
6265 case CXCursor_NamespaceRef:
6266 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6267
6268 case CXCursor_MemberRef:
6269 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6270
6271 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006272 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006273 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6274 tu ));
6275 }
6276
6277 case CXCursor_LabelRef:
6278 // FIXME: We end up faking the "parent" declaration here because we
6279 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006280 return MakeCXCursor(getCursorLabelRef(C).first,
6281 cxtu::getASTUnit(tu)->getASTContext()
6282 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 tu);
6284
6285 case CXCursor_OverloadedDeclRef:
6286 return C;
6287
6288 case CXCursor_VariableRef:
6289 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6290
6291 default:
6292 // We would prefer to enumerate all non-reference cursor kinds here.
6293 llvm_unreachable("Unhandled reference cursor kind");
6294 }
6295}
6296
6297CXCursor clang_getCursorDefinition(CXCursor C) {
6298 if (clang_isInvalid(C.kind))
6299 return clang_getNullCursor();
6300
6301 CXTranslationUnit TU = getCursorTU(C);
6302
6303 bool WasReference = false;
6304 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6305 C = clang_getCursorReferenced(C);
6306 WasReference = true;
6307 }
6308
6309 if (C.kind == CXCursor_MacroExpansion)
6310 return clang_getCursorReferenced(C);
6311
6312 if (!clang_isDeclaration(C.kind))
6313 return clang_getNullCursor();
6314
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006315 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006316 if (!D)
6317 return clang_getNullCursor();
6318
6319 switch (D->getKind()) {
6320 // Declaration kinds that don't really separate the notions of
6321 // declaration and definition.
6322 case Decl::Namespace:
6323 case Decl::Typedef:
6324 case Decl::TypeAlias:
6325 case Decl::TypeAliasTemplate:
6326 case Decl::TemplateTypeParm:
6327 case Decl::EnumConstant:
6328 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006329 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006330 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006331 case Decl::IndirectField:
6332 case Decl::ObjCIvar:
6333 case Decl::ObjCAtDefsField:
6334 case Decl::ImplicitParam:
6335 case Decl::ParmVar:
6336 case Decl::NonTypeTemplateParm:
6337 case Decl::TemplateTemplateParm:
6338 case Decl::ObjCCategoryImpl:
6339 case Decl::ObjCImplementation:
6340 case Decl::AccessSpec:
6341 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006342 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006343 case Decl::ObjCPropertyImpl:
6344 case Decl::FileScopeAsm:
6345 case Decl::StaticAssert:
6346 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006347 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006348 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 case Decl::Label: // FIXME: Is this right??
6350 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006351 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006352 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006353 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006354 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006355 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006356 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006357 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006358 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006359 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006360 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006361 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006362 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006363 case Decl::Concept:
Tykerb0561b32019-11-17 11:41:55 +01006364 case Decl::LifetimeExtendedTemporary:
Saar Raza0f50d72020-01-18 09:11:43 +02006365 case Decl::RequiresExprBody:
Guy Benyei11169dd2012-12-18 14:30:41 +00006366 return C;
6367
6368 // Declaration kinds that don't make any sense here, but are
6369 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006370 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006371 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006372 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006373 break;
6374
6375 // Declaration kinds for which the definition is not resolvable.
6376 case Decl::UnresolvedUsingTypename:
6377 case Decl::UnresolvedUsingValue:
6378 break;
6379
6380 case Decl::UsingDirective:
6381 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6382 TU);
6383
6384 case Decl::NamespaceAlias:
6385 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6386
6387 case Decl::Enum:
6388 case Decl::Record:
6389 case Decl::CXXRecord:
6390 case Decl::ClassTemplateSpecialization:
6391 case Decl::ClassTemplatePartialSpecialization:
6392 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6393 return MakeCXCursor(Def, TU);
6394 return clang_getNullCursor();
6395
6396 case Decl::Function:
6397 case Decl::CXXMethod:
6398 case Decl::CXXConstructor:
6399 case Decl::CXXDestructor:
6400 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006401 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006402 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006403 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006404 return clang_getNullCursor();
6405 }
6406
Larisse Voufo39a1e502013-08-06 01:03:05 +00006407 case Decl::Var:
6408 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006409 case Decl::VarTemplatePartialSpecialization:
6410 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006411 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006412 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006413 return MakeCXCursor(Def, TU);
6414 return clang_getNullCursor();
6415 }
6416
6417 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006418 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006419 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6420 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6421 return clang_getNullCursor();
6422 }
6423
6424 case Decl::ClassTemplate: {
6425 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6426 ->getDefinition())
6427 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6428 TU);
6429 return clang_getNullCursor();
6430 }
6431
Larisse Voufo39a1e502013-08-06 01:03:05 +00006432 case Decl::VarTemplate: {
6433 if (VarDecl *Def =
6434 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6435 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6436 return clang_getNullCursor();
6437 }
6438
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 case Decl::Using:
6440 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6441 D->getLocation(), TU);
6442
6443 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006444 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006445 return clang_getCursorDefinition(
6446 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6447 TU));
6448
6449 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006450 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006451 if (Method->isThisDeclarationADefinition())
6452 return C;
6453
6454 // Dig out the method definition in the associated
6455 // @implementation, if we have it.
6456 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006457 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006458 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6459 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6460 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6461 Method->isInstanceMethod()))
6462 if (Def->isThisDeclarationADefinition())
6463 return MakeCXCursor(Def, TU);
6464
6465 return clang_getNullCursor();
6466 }
6467
6468 case Decl::ObjCCategory:
6469 if (ObjCCategoryImplDecl *Impl
6470 = cast<ObjCCategoryDecl>(D)->getImplementation())
6471 return MakeCXCursor(Impl, TU);
6472 return clang_getNullCursor();
6473
6474 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006475 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006476 return MakeCXCursor(Def, TU);
6477 return clang_getNullCursor();
6478
6479 case Decl::ObjCInterface: {
6480 // There are two notions of a "definition" for an Objective-C
6481 // class: the interface and its implementation. When we resolved a
6482 // reference to an Objective-C class, produce the @interface as
6483 // the definition; when we were provided with the interface,
6484 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006485 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006486 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006487 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006488 return MakeCXCursor(Def, TU);
6489 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6490 return MakeCXCursor(Impl, TU);
6491 return clang_getNullCursor();
6492 }
6493
6494 case Decl::ObjCProperty:
6495 // FIXME: We don't really know where to find the
6496 // ObjCPropertyImplDecls that implement this property.
6497 return clang_getNullCursor();
6498
6499 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006500 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006501 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006502 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006503 return MakeCXCursor(Def, TU);
6504
6505 return clang_getNullCursor();
6506
6507 case Decl::Friend:
6508 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6509 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6510 return clang_getNullCursor();
6511
6512 case Decl::FriendTemplate:
6513 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6514 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6515 return clang_getNullCursor();
6516 }
6517
6518 return clang_getNullCursor();
6519}
6520
6521unsigned clang_isCursorDefinition(CXCursor C) {
6522 if (!clang_isDeclaration(C.kind))
6523 return 0;
6524
6525 return clang_getCursorDefinition(C) == C;
6526}
6527
6528CXCursor clang_getCanonicalCursor(CXCursor C) {
6529 if (!clang_isDeclaration(C.kind))
6530 return C;
6531
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006532 if (const Decl *D = getCursorDecl(C)) {
6533 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006534 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6535 return MakeCXCursor(CatD, getCursorTU(C));
6536
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006537 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6538 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006539 return MakeCXCursor(IFD, getCursorTU(C));
6540
6541 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6542 }
6543
6544 return C;
6545}
6546
6547int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6548 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6549}
6550
6551unsigned clang_getNumOverloadedDecls(CXCursor C) {
6552 if (C.kind != CXCursor_OverloadedDeclRef)
6553 return 0;
6554
6555 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006556 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006557 return E->getNumDecls();
6558
6559 if (OverloadedTemplateStorage *S
6560 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6561 return S->size();
6562
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006563 const Decl *D = Storage.get<const Decl *>();
6564 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006565 return Using->shadow_size();
6566
6567 return 0;
6568}
6569
6570CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6571 if (cursor.kind != CXCursor_OverloadedDeclRef)
6572 return clang_getNullCursor();
6573
6574 if (index >= clang_getNumOverloadedDecls(cursor))
6575 return clang_getNullCursor();
6576
6577 CXTranslationUnit TU = getCursorTU(cursor);
6578 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006579 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006580 return MakeCXCursor(E->decls_begin()[index], TU);
6581
6582 if (OverloadedTemplateStorage *S
6583 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6584 return MakeCXCursor(S->begin()[index], TU);
6585
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006586 const Decl *D = Storage.get<const Decl *>();
6587 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006588 // FIXME: This is, unfortunately, linear time.
6589 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6590 std::advance(Pos, index);
6591 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6592 }
6593
6594 return clang_getNullCursor();
6595}
6596
6597void clang_getDefinitionSpellingAndExtent(CXCursor C,
6598 const char **startBuf,
6599 const char **endBuf,
6600 unsigned *startLine,
6601 unsigned *startColumn,
6602 unsigned *endLine,
6603 unsigned *endColumn) {
6604 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006605 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006606 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6607
6608 SourceManager &SM = FD->getASTContext().getSourceManager();
6609 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6610 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6611 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6612 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6613 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6614 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6615}
6616
6617
6618CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6619 unsigned PieceIndex) {
6620 RefNamePieces Pieces;
6621
6622 switch (C.kind) {
6623 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006624 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006625 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6626 E->getQualifierLoc().getSourceRange());
6627 break;
6628
6629 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006630 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6631 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6632 Pieces =
6633 buildPieces(NameFlags, false, E->getNameInfo(),
6634 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6635 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006636 break;
6637
6638 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006639 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006641 const Expr *Callee = OCE->getCallee();
6642 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006643 Callee = ICE->getSubExpr();
6644
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006645 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006646 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6647 DRE->getQualifierLoc().getSourceRange());
6648 }
6649 break;
6650
6651 default:
6652 break;
6653 }
6654
6655 if (Pieces.empty()) {
6656 if (PieceIndex == 0)
6657 return clang_getCursorExtent(C);
6658 } else if (PieceIndex < Pieces.size()) {
6659 SourceRange R = Pieces[PieceIndex];
6660 if (R.isValid())
6661 return cxloc::translateSourceRange(getCursorContext(C), R);
6662 }
6663
6664 return clang_getNullRange();
6665}
6666
6667void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006668 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6669 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006670}
6671
6672void clang_executeOnThread(void (*fn)(void*), void *user_data,
6673 unsigned stack_size) {
Alexandre Ganea471d0602019-11-29 10:52:13 -05006674 llvm::llvm_execute_on_thread(fn, user_data,
6675 stack_size == 0
6676 ? clang::DesiredStackSize
6677 : llvm::Optional<unsigned>(stack_size));
Guy Benyei11169dd2012-12-18 14:30:41 +00006678}
6679
Guy Benyei11169dd2012-12-18 14:30:41 +00006680//===----------------------------------------------------------------------===//
6681// Token-based Operations.
6682//===----------------------------------------------------------------------===//
6683
6684/* CXToken layout:
6685 * int_data[0]: a CXTokenKind
6686 * int_data[1]: starting token location
6687 * int_data[2]: token length
6688 * int_data[3]: reserved
6689 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6690 * otherwise unused.
6691 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006692CXTokenKind clang_getTokenKind(CXToken CXTok) {
6693 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6694}
6695
6696CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6697 switch (clang_getTokenKind(CXTok)) {
6698 case CXToken_Identifier:
6699 case CXToken_Keyword:
6700 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006701 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006702 ->getNameStart());
6703
6704 case CXToken_Literal: {
6705 // We have stashed the starting pointer in the ptr_data field. Use it.
6706 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006707 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006708 }
6709
6710 case CXToken_Punctuation:
6711 case CXToken_Comment:
6712 break;
6713 }
6714
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006715 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006716 LOG_BAD_TU(TU);
6717 return cxstring::createEmpty();
6718 }
6719
Guy Benyei11169dd2012-12-18 14:30:41 +00006720 // We have to find the starting buffer pointer the hard way, by
6721 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006722 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006723 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006724 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006725
6726 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6727 std::pair<FileID, unsigned> LocInfo
6728 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6729 bool Invalid = false;
6730 StringRef Buffer
6731 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6732 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006733 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006734
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006735 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006736}
6737
6738CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006739 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006740 LOG_BAD_TU(TU);
6741 return clang_getNullLocation();
6742 }
6743
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006744 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006745 if (!CXXUnit)
6746 return clang_getNullLocation();
6747
6748 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6749 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6750}
6751
6752CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006753 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006754 LOG_BAD_TU(TU);
6755 return clang_getNullRange();
6756 }
6757
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006758 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006759 if (!CXXUnit)
6760 return clang_getNullRange();
6761
6762 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6763 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6764}
6765
6766static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6767 SmallVectorImpl<CXToken> &CXTokens) {
6768 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6769 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006770 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006771 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006772 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006773
6774 // Cannot tokenize across files.
6775 if (BeginLocInfo.first != EndLocInfo.first)
6776 return;
6777
6778 // Create a lexer
6779 bool Invalid = false;
6780 StringRef Buffer
6781 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6782 if (Invalid)
6783 return;
6784
6785 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6786 CXXUnit->getASTContext().getLangOpts(),
6787 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6788 Lex.SetCommentRetentionState(true);
6789
6790 // Lex tokens until we hit the end of the range.
6791 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6792 Token Tok;
6793 bool previousWasAt = false;
6794 do {
6795 // Lex the next token
6796 Lex.LexFromRawLexer(Tok);
6797 if (Tok.is(tok::eof))
6798 break;
6799
6800 // Initialize the CXToken.
6801 CXToken CXTok;
6802
6803 // - Common fields
6804 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6805 CXTok.int_data[2] = Tok.getLength();
6806 CXTok.int_data[3] = 0;
6807
6808 // - Kind-specific fields
6809 if (Tok.isLiteral()) {
6810 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006811 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006812 } else if (Tok.is(tok::raw_identifier)) {
6813 // Lookup the identifier to determine whether we have a keyword.
6814 IdentifierInfo *II
6815 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6816
6817 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6818 CXTok.int_data[0] = CXToken_Keyword;
6819 }
6820 else {
6821 CXTok.int_data[0] = Tok.is(tok::identifier)
6822 ? CXToken_Identifier
6823 : CXToken_Keyword;
6824 }
6825 CXTok.ptr_data = II;
6826 } else if (Tok.is(tok::comment)) {
6827 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006828 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006829 } else {
6830 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006831 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006832 }
6833 CXTokens.push_back(CXTok);
6834 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006835 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006836}
6837
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006838CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6839 LOG_FUNC_SECTION {
6840 *Log << TU << ' ' << Location;
6841 }
6842
6843 if (isNotUsableTU(TU)) {
6844 LOG_BAD_TU(TU);
6845 return NULL;
6846 }
6847
6848 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6849 if (!CXXUnit)
6850 return NULL;
6851
6852 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6853 if (Begin.isInvalid())
6854 return NULL;
6855 SourceManager &SM = CXXUnit->getSourceManager();
6856 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6857 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6858
6859 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6860
6861 SmallVector<CXToken, 32> CXTokens;
6862 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6863
6864 if (CXTokens.empty())
6865 return NULL;
6866
6867 CXTokens.resize(1);
6868 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6869
6870 memmove(Token, CXTokens.data(), sizeof(CXToken));
6871 return Token;
6872}
6873
Guy Benyei11169dd2012-12-18 14:30:41 +00006874void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6875 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006876 LOG_FUNC_SECTION {
6877 *Log << TU << ' ' << Range;
6878 }
6879
Guy Benyei11169dd2012-12-18 14:30:41 +00006880 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006881 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006882 if (NumTokens)
6883 *NumTokens = 0;
6884
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006885 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006886 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006887 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006888 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006889
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006890 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006891 if (!CXXUnit || !Tokens || !NumTokens)
6892 return;
6893
6894 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6895
6896 SourceRange R = cxloc::translateCXSourceRange(Range);
6897 if (R.isInvalid())
6898 return;
6899
6900 SmallVector<CXToken, 32> CXTokens;
6901 getTokens(CXXUnit, R, CXTokens);
6902
6903 if (CXTokens.empty())
6904 return;
6905
Serge Pavlov52525732018-02-21 02:02:39 +00006906 *Tokens = static_cast<CXToken *>(
6907 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006908 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6909 *NumTokens = CXTokens.size();
6910}
6911
6912void clang_disposeTokens(CXTranslationUnit TU,
6913 CXToken *Tokens, unsigned NumTokens) {
6914 free(Tokens);
6915}
6916
Guy Benyei11169dd2012-12-18 14:30:41 +00006917//===----------------------------------------------------------------------===//
6918// Token annotation APIs.
6919//===----------------------------------------------------------------------===//
6920
Guy Benyei11169dd2012-12-18 14:30:41 +00006921static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6922 CXCursor parent,
6923 CXClientData client_data);
6924static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6925 CXClientData client_data);
6926
6927namespace {
6928class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006929 CXToken *Tokens;
6930 CXCursor *Cursors;
6931 unsigned NumTokens;
6932 unsigned TokIdx;
6933 unsigned PreprocessingTokIdx;
6934 CursorVisitor AnnotateVis;
6935 SourceManager &SrcMgr;
6936 bool HasContextSensitiveKeywords;
6937
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006938 struct PostChildrenAction {
6939 CXCursor cursor;
6940 enum Action { Invalid, Ignore, Postpone } action;
6941 };
6942 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6943
Guy Benyei11169dd2012-12-18 14:30:41 +00006944 struct PostChildrenInfo {
6945 CXCursor Cursor;
6946 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006947 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006948 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006949 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006950 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006951 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006952
6953 CXToken &getTok(unsigned Idx) {
6954 assert(Idx < NumTokens);
6955 return Tokens[Idx];
6956 }
6957 const CXToken &getTok(unsigned Idx) const {
6958 assert(Idx < NumTokens);
6959 return Tokens[Idx];
6960 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006961 bool MoreTokens() const { return TokIdx < NumTokens; }
6962 unsigned NextToken() const { return TokIdx; }
6963 void AdvanceToken() { ++TokIdx; }
6964 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006965 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006966 }
6967 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006968 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006969 }
6970 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006971 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006972 }
6973
6974 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006975 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006976 SourceRange);
6977
6978public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006979 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006980 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006981 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006982 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006983 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006984 AnnotateTokensVisitor, this,
6985 /*VisitPreprocessorLast=*/true,
6986 /*VisitIncludedEntities=*/false,
6987 RegionOfInterest,
6988 /*VisitDeclsOnly=*/false,
6989 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006990 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006991 HasContextSensitiveKeywords(false) { }
6992
6993 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6994 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006995 bool IsIgnoredChildCursor(CXCursor cursor) const;
6996 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6997
Guy Benyei11169dd2012-12-18 14:30:41 +00006998 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006999 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
7000 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
7001
Guy Benyei11169dd2012-12-18 14:30:41 +00007002 void AnnotateTokens();
7003
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007004 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00007005 /// context-sensitive keywords.
7006 bool hasContextSensitiveKeywords() const {
7007 return HasContextSensitiveKeywords;
7008 }
7009
7010 ~AnnotateTokensWorker() {
7011 assert(PostChildrenInfos.empty());
7012 }
7013};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007014}
Guy Benyei11169dd2012-12-18 14:30:41 +00007015
7016void AnnotateTokensWorker::AnnotateTokens() {
7017 // Walk the AST within the region of interest, annotating tokens
7018 // along the way.
7019 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007020}
Guy Benyei11169dd2012-12-18 14:30:41 +00007021
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007022bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
7023 if (PostChildrenInfos.empty())
7024 return false;
7025
7026 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
7027 if (ChildAction.cursor == cursor &&
7028 ChildAction.action == PostChildrenAction::Ignore) {
7029 return true;
7030 }
7031 }
7032
7033 return false;
7034}
7035
7036const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
7037 if (!clang_isExpression(Cursor.kind))
7038 return nullptr;
7039
7040 const Expr *E = getCursorExpr(Cursor);
7041 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7042 const OverloadedOperatorKind Kind = OCE->getOperator();
7043 if (Kind == OO_Call || Kind == OO_Subscript)
7044 return OCE;
7045 }
7046
7047 return nullptr;
7048}
7049
7050AnnotateTokensWorker::PostChildrenActions
7051AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
7052 PostChildrenActions actions;
7053
7054 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
7055 // visited before the arguments to the operator call. For the Call and
7056 // Subscript operator the range of this DeclRefExpr includes the whole call
7057 // expression, so that all tokens in that range would be mapped to the
7058 // operator function, including the tokens of the arguments. To avoid that,
7059 // ensure to visit this DeclRefExpr as last node.
7060 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
7061 const Expr *Callee = OCE->getCallee();
7062 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
7063 const Expr *SubExpr = ICE->getSubExpr();
7064 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00007065 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007066 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7067
7068 // Visit the DeclRefExpr as last.
7069 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7070 actions.push_back({cxChild, PostChildrenAction::Postpone});
7071
7072 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7073 // wide range as the DeclRefExpr. We can skip visiting this entirely.
7074 cxChild = MakeCXCursor(ICE, parentDecl, TU);
7075 actions.push_back({cxChild, PostChildrenAction::Ignore});
7076 }
7077 }
7078 }
7079
7080 return actions;
7081}
7082
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007083static inline void updateCursorAnnotation(CXCursor &Cursor,
7084 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007085 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007086 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007087 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00007088}
7089
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007090/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00007091//// between the cursor location and the source range is the same as
7092/// \arg compResult.
7093///
7094/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7095/// Pass RangeOverlap to annotate tokens inside a range.
7096void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7097 RangeComparisonResult compResult,
7098 SourceRange range) {
7099 while (MoreTokens()) {
7100 const unsigned I = NextToken();
7101 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007102 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7103 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007104
7105 SourceLocation TokLoc = GetTokenLoc(I);
7106 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007107 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007108 AdvanceToken();
7109 continue;
7110 }
7111 break;
7112 }
7113}
7114
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007115/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007116/// \returns true if it advanced beyond all macro tokens, false otherwise.
7117bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007118 CXCursor updateC,
7119 RangeComparisonResult compResult,
7120 SourceRange range) {
7121 assert(MoreTokens());
7122 assert(isFunctionMacroToken(NextToken()) &&
7123 "Should be called only for macro arg tokens");
7124
7125 // This works differently than annotateAndAdvanceTokens; because expanded
7126 // macro arguments can have arbitrary translation-unit source order, we do not
7127 // advance the token index one by one until a token fails the range test.
7128 // We only advance once past all of the macro arg tokens if all of them
7129 // pass the range test. If one of them fails we keep the token index pointing
7130 // at the start of the macro arg tokens so that the failing token will be
7131 // annotated by a subsequent annotation try.
7132
7133 bool atLeastOneCompFail = false;
7134
7135 unsigned I = NextToken();
7136 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7137 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7138 if (TokLoc.isFileID())
7139 continue; // not macro arg token, it's parens or comma.
7140 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7141 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7142 Cursors[I] = updateC;
7143 } else
7144 atLeastOneCompFail = true;
7145 }
7146
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007147 if (atLeastOneCompFail)
7148 return false;
7149
7150 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7151 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007152}
7153
7154enum CXChildVisitResult
7155AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007156 SourceRange cursorRange = getRawCursorExtent(cursor);
7157 if (cursorRange.isInvalid())
7158 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007159
7160 if (IsIgnoredChildCursor(cursor))
7161 return CXChildVisit_Continue;
7162
Guy Benyei11169dd2012-12-18 14:30:41 +00007163 if (!HasContextSensitiveKeywords) {
7164 // Objective-C properties can have context-sensitive keywords.
7165 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007166 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007167 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7168 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7169 }
7170 // Objective-C methods can have context-sensitive keywords.
7171 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7172 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007173 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007174 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7175 if (Method->getObjCDeclQualifier())
7176 HasContextSensitiveKeywords = true;
7177 else {
David Majnemer59f77922016-06-24 04:05:48 +00007178 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007179 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007180 HasContextSensitiveKeywords = true;
7181 break;
7182 }
7183 }
7184 }
7185 }
7186 }
7187 // C++ methods can have context-sensitive keywords.
7188 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007189 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007190 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7191 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7192 HasContextSensitiveKeywords = true;
7193 }
7194 }
7195 // C++ classes can have context-sensitive keywords.
7196 else if (cursor.kind == CXCursor_StructDecl ||
7197 cursor.kind == CXCursor_ClassDecl ||
7198 cursor.kind == CXCursor_ClassTemplate ||
7199 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007200 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007201 if (D->hasAttr<FinalAttr>())
7202 HasContextSensitiveKeywords = true;
7203 }
7204 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007205
7206 // Don't override a property annotation with its getter/setter method.
7207 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7208 parent.kind == CXCursor_ObjCPropertyDecl)
7209 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007210
7211 if (clang_isPreprocessing(cursor.kind)) {
7212 // Items in the preprocessing record are kept separate from items in
7213 // declarations, so we keep a separate token index.
7214 unsigned SavedTokIdx = TokIdx;
7215 TokIdx = PreprocessingTokIdx;
7216
7217 // Skip tokens up until we catch up to the beginning of the preprocessing
7218 // entry.
7219 while (MoreTokens()) {
7220 const unsigned I = NextToken();
7221 SourceLocation TokLoc = GetTokenLoc(I);
7222 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7223 case RangeBefore:
7224 AdvanceToken();
7225 continue;
7226 case RangeAfter:
7227 case RangeOverlap:
7228 break;
7229 }
7230 break;
7231 }
7232
7233 // Look at all of the tokens within this range.
7234 while (MoreTokens()) {
7235 const unsigned I = NextToken();
7236 SourceLocation TokLoc = GetTokenLoc(I);
7237 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7238 case RangeBefore:
7239 llvm_unreachable("Infeasible");
7240 case RangeAfter:
7241 break;
7242 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007243 // For macro expansions, just note where the beginning of the macro
7244 // expansion occurs.
7245 if (cursor.kind == CXCursor_MacroExpansion) {
7246 if (TokLoc == cursorRange.getBegin())
7247 Cursors[I] = cursor;
7248 AdvanceToken();
7249 break;
7250 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007251 // We may have already annotated macro names inside macro definitions.
7252 if (Cursors[I].kind != CXCursor_MacroExpansion)
7253 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007254 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007255 continue;
7256 }
7257 break;
7258 }
7259
7260 // Save the preprocessing token index; restore the non-preprocessing
7261 // token index.
7262 PreprocessingTokIdx = TokIdx;
7263 TokIdx = SavedTokIdx;
7264 return CXChildVisit_Recurse;
7265 }
7266
7267 if (cursorRange.isInvalid())
7268 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007269
7270 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007271 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007272 const enum CXCursorKind K = clang_getCursorKind(parent);
7273 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007274 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7275 // Attributes are annotated out-of-order, skip tokens until we reach it.
7276 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007277 ? clang_getNullCursor() : parent;
7278
7279 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7280
7281 // Avoid having the cursor of an expression "overwrite" the annotation of the
7282 // variable declaration that it belongs to.
7283 // This can happen for C++ constructor expressions whose range generally
7284 // include the variable declaration, e.g.:
7285 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007286 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007287 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007288 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007289 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007290 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7291 E->getBeginLoc() == D->getLocation() &&
7292 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007293 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007294 AdvanceToken();
7295 }
7296 }
7297 }
7298
7299 // Before recursing into the children keep some state that we are going
7300 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7301 // extra work after the child nodes are visited.
7302 // Note that we don't call VisitChildren here to avoid traversing statements
7303 // code-recursively which can blow the stack.
7304
7305 PostChildrenInfo Info;
7306 Info.Cursor = cursor;
7307 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007308 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007309 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007310 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007311 PostChildrenInfos.push_back(Info);
7312
7313 return CXChildVisit_Recurse;
7314}
7315
7316bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7317 if (PostChildrenInfos.empty())
7318 return false;
7319 const PostChildrenInfo &Info = PostChildrenInfos.back();
7320 if (!clang_equalCursors(Info.Cursor, cursor))
7321 return false;
7322
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007323 HandlePostPonedChildCursors(Info);
7324
Guy Benyei11169dd2012-12-18 14:30:41 +00007325 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7326 const unsigned AfterChildren = NextToken();
7327 SourceRange cursorRange = Info.CursorRange;
7328
7329 // Scan the tokens that are at the end of the cursor, but are not captured
7330 // but the child cursors.
7331 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7332
7333 // Scan the tokens that are at the beginning of the cursor, but are not
7334 // capture by the child cursors.
7335 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7336 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7337 break;
7338
7339 Cursors[I] = cursor;
7340 }
7341
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007342 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7343 // encountered the attribute cursor.
7344 if (clang_isAttribute(cursor.kind))
7345 TokIdx = Info.BeforeReachingCursorIdx;
7346
Guy Benyei11169dd2012-12-18 14:30:41 +00007347 PostChildrenInfos.pop_back();
7348 return false;
7349}
7350
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007351void AnnotateTokensWorker::HandlePostPonedChildCursors(
7352 const PostChildrenInfo &Info) {
7353 for (const auto &ChildAction : Info.ChildActions) {
7354 if (ChildAction.action == PostChildrenAction::Postpone) {
7355 HandlePostPonedChildCursor(ChildAction.cursor,
7356 Info.BeforeChildrenTokenIdx);
7357 }
7358 }
7359}
7360
7361void AnnotateTokensWorker::HandlePostPonedChildCursor(
7362 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007363 unsigned I = StartTokenIndex;
7364
7365 // The bracket tokens of a Call or Subscript operator are mapped to
7366 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7367 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7368 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007369 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7370 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007371 if (clang_Range_isNull(CXRefNameRange))
7372 break; // All ranges handled.
7373
7374 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7375 while (I < NumTokens) {
7376 const SourceLocation TokenLocation = GetTokenLoc(I);
7377 if (!TokenLocation.isValid())
7378 break;
7379
7380 // Adapt the end range, because LocationCompare() reports
7381 // RangeOverlap even for the not-inclusive end location.
7382 const SourceLocation fixedEnd =
7383 RefNameRange.getEnd().getLocWithOffset(-1);
7384 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7385
7386 const RangeComparisonResult ComparisonResult =
7387 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7388
7389 if (ComparisonResult == RangeOverlap) {
7390 Cursors[I++] = Cursor;
7391 } else if (ComparisonResult == RangeBefore) {
7392 ++I; // Not relevant token, check next one.
7393 } else if (ComparisonResult == RangeAfter) {
7394 break; // All tokens updated for current range, check next.
7395 }
7396 }
7397 }
7398}
7399
Guy Benyei11169dd2012-12-18 14:30:41 +00007400static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7401 CXCursor parent,
7402 CXClientData client_data) {
7403 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7404}
7405
7406static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7407 CXClientData client_data) {
7408 return static_cast<AnnotateTokensWorker*>(client_data)->
7409 postVisitChildren(cursor);
7410}
7411
7412namespace {
7413
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007414/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007415/// and mark tokens that are macro arguments. This info is used by the
7416/// AnnotateTokensWorker.
7417class MarkMacroArgTokensVisitor {
7418 SourceManager &SM;
7419 CXToken *Tokens;
7420 unsigned NumTokens;
7421 unsigned CurIdx;
7422
7423public:
7424 MarkMacroArgTokensVisitor(SourceManager &SM,
7425 CXToken *tokens, unsigned numTokens)
7426 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7427
7428 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7429 if (cursor.kind != CXCursor_MacroExpansion)
7430 return CXChildVisit_Continue;
7431
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007432 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007433 if (macroRange.getBegin() == macroRange.getEnd())
7434 return CXChildVisit_Continue; // it's not a function macro.
7435
7436 for (; CurIdx < NumTokens; ++CurIdx) {
7437 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7438 macroRange.getBegin()))
7439 break;
7440 }
7441
7442 if (CurIdx == NumTokens)
7443 return CXChildVisit_Break;
7444
7445 for (; CurIdx < NumTokens; ++CurIdx) {
7446 SourceLocation tokLoc = getTokenLoc(CurIdx);
7447 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7448 break;
7449
7450 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7451 }
7452
7453 if (CurIdx == NumTokens)
7454 return CXChildVisit_Break;
7455
7456 return CXChildVisit_Continue;
7457 }
7458
7459private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007460 CXToken &getTok(unsigned Idx) {
7461 assert(Idx < NumTokens);
7462 return Tokens[Idx];
7463 }
7464 const CXToken &getTok(unsigned Idx) const {
7465 assert(Idx < NumTokens);
7466 return Tokens[Idx];
7467 }
7468
Guy Benyei11169dd2012-12-18 14:30:41 +00007469 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007470 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007471 }
7472
7473 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7474 // The third field is reserved and currently not used. Use it here
7475 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007476 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007477 }
7478};
7479
7480} // end anonymous namespace
7481
7482static CXChildVisitResult
7483MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7484 CXClientData client_data) {
7485 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7486 parent);
7487}
7488
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007489/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007490/// \returns true if lexing was finished, false otherwise.
7491static bool lexNext(Lexer &Lex, Token &Tok,
7492 unsigned &NextIdx, unsigned NumTokens) {
7493 if (NextIdx >= NumTokens)
7494 return true;
7495
7496 ++NextIdx;
7497 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007498 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007499}
7500
Guy Benyei11169dd2012-12-18 14:30:41 +00007501static void annotatePreprocessorTokens(CXTranslationUnit TU,
7502 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007503 CXCursor *Cursors,
7504 CXToken *Tokens,
7505 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007506 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007507
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007508 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007509 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7510 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007511 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007512 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007513 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007514
7515 if (BeginLocInfo.first != EndLocInfo.first)
7516 return;
7517
7518 StringRef Buffer;
7519 bool Invalid = false;
7520 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7521 if (Buffer.empty() || Invalid)
7522 return;
7523
7524 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7525 CXXUnit->getASTContext().getLangOpts(),
7526 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7527 Buffer.end());
7528 Lex.SetCommentRetentionState(true);
7529
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007530 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007531 // Lex tokens in raw mode until we hit the end of the range, to avoid
7532 // entering #includes or expanding macros.
7533 while (true) {
7534 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007535 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7536 break;
7537 unsigned TokIdx = NextIdx-1;
7538 assert(Tok.getLocation() ==
7539 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007540
7541 reprocess:
7542 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007543 // We have found a preprocessing directive. Annotate the tokens
7544 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007545 //
7546 // FIXME: Some simple tests here could identify macro definitions and
7547 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007548
7549 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007550 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7551 break;
7552
Craig Topper69186e72014-06-08 08:38:04 +00007553 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007554 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007555 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7556 break;
7557
7558 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007559 IdentifierInfo &II =
7560 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007561 SourceLocation MappedTokLoc =
7562 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7563 MI = getMacroInfo(II, MappedTokLoc, TU);
7564 }
7565 }
7566
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007567 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007568 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007569 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7570 finished = true;
7571 break;
7572 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007573 // If we are in a macro definition, check if the token was ever a
7574 // macro name and annotate it if that's the case.
7575 if (MI) {
7576 SourceLocation SaveLoc = Tok.getLocation();
7577 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007578 MacroDefinitionRecord *MacroDef =
7579 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007580 Tok.setLocation(SaveLoc);
7581 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007582 Cursors[NextIdx - 1] =
7583 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007584 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007585 } while (!Tok.isAtStartOfLine());
7586
7587 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7588 assert(TokIdx <= LastIdx);
7589 SourceLocation EndLoc =
7590 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7591 CXCursor Cursor =
7592 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7593
7594 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007595 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007596
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007597 if (finished)
7598 break;
7599 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007600 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007601 }
7602}
7603
7604// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007605static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7606 CXToken *Tokens, unsigned NumTokens,
7607 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007608 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007609 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7610 setThreadBackgroundPriority();
7611
7612 // Determine the region of interest, which contains all of the tokens.
7613 SourceRange RegionOfInterest;
7614 RegionOfInterest.setBegin(
7615 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7616 RegionOfInterest.setEnd(
7617 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7618 Tokens[NumTokens-1])));
7619
Guy Benyei11169dd2012-12-18 14:30:41 +00007620 // Relex the tokens within the source range to look for preprocessing
7621 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007622 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007623
7624 // If begin location points inside a macro argument, set it to the expansion
7625 // location so we can have the full context when annotating semantically.
7626 {
7627 SourceManager &SM = CXXUnit->getSourceManager();
7628 SourceLocation Loc =
7629 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7630 if (Loc.isMacroID())
7631 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7632 }
7633
Guy Benyei11169dd2012-12-18 14:30:41 +00007634 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7635 // Search and mark tokens that are macro argument expansions.
7636 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7637 Tokens, NumTokens);
7638 CursorVisitor MacroArgMarker(TU,
7639 MarkMacroArgTokensVisitorDelegate, &Visitor,
7640 /*VisitPreprocessorLast=*/true,
7641 /*VisitIncludedEntities=*/false,
7642 RegionOfInterest);
7643 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7644 }
7645
7646 // Annotate all of the source locations in the region of interest that map to
7647 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007648 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007649
7650 // FIXME: We use a ridiculous stack size here because the data-recursion
7651 // algorithm uses a large stack frame than the non-data recursive version,
7652 // and AnnotationTokensWorker currently transforms the data-recursion
7653 // algorithm back into a traditional recursion by explicitly calling
7654 // VisitChildren(). We will need to remove this explicit recursive call.
7655 W.AnnotateTokens();
7656
7657 // If we ran into any entities that involve context-sensitive keywords,
7658 // take another pass through the tokens to mark them as such.
7659 if (W.hasContextSensitiveKeywords()) {
7660 for (unsigned I = 0; I != NumTokens; ++I) {
7661 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7662 continue;
7663
7664 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7665 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007666 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007667 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7668 if (Property->getPropertyAttributesAsWritten() != 0 &&
7669 llvm::StringSwitch<bool>(II->getName())
7670 .Case("readonly", true)
7671 .Case("assign", true)
7672 .Case("unsafe_unretained", true)
7673 .Case("readwrite", true)
7674 .Case("retain", true)
7675 .Case("copy", true)
7676 .Case("nonatomic", true)
7677 .Case("atomic", true)
7678 .Case("getter", true)
7679 .Case("setter", true)
7680 .Case("strong", true)
7681 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007682 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007683 .Default(false))
7684 Tokens[I].int_data[0] = CXToken_Keyword;
7685 }
7686 continue;
7687 }
7688
7689 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7690 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7691 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7692 if (llvm::StringSwitch<bool>(II->getName())
7693 .Case("in", true)
7694 .Case("out", true)
7695 .Case("inout", true)
7696 .Case("oneway", true)
7697 .Case("bycopy", true)
7698 .Case("byref", true)
7699 .Default(false))
7700 Tokens[I].int_data[0] = CXToken_Keyword;
7701 continue;
7702 }
7703
7704 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7705 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7706 Tokens[I].int_data[0] = CXToken_Keyword;
7707 continue;
7708 }
7709 }
7710 }
7711}
7712
Guy Benyei11169dd2012-12-18 14:30:41 +00007713void clang_annotateTokens(CXTranslationUnit TU,
7714 CXToken *Tokens, unsigned NumTokens,
7715 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007716 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007717 LOG_BAD_TU(TU);
7718 return;
7719 }
7720 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007721 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007722 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007723 }
7724
7725 LOG_FUNC_SECTION {
7726 *Log << TU << ' ';
7727 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7728 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7729 *Log << clang_getRange(bloc, eloc);
7730 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007731
7732 // Any token we don't specifically annotate will have a NULL cursor.
7733 CXCursor C = clang_getNullCursor();
7734 for (unsigned I = 0; I != NumTokens; ++I)
7735 Cursors[I] = C;
7736
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007737 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007738 if (!CXXUnit)
7739 return;
7740
7741 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007742
7743 auto AnnotateTokensImpl = [=]() {
7744 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7745 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007746 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007747 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007748 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7749 }
7750}
7751
Guy Benyei11169dd2012-12-18 14:30:41 +00007752//===----------------------------------------------------------------------===//
7753// Operations for querying linkage of a cursor.
7754//===----------------------------------------------------------------------===//
7755
Guy Benyei11169dd2012-12-18 14:30:41 +00007756CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7757 if (!clang_isDeclaration(cursor.kind))
7758 return CXLinkage_Invalid;
7759
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007760 const Decl *D = cxcursor::getCursorDecl(cursor);
7761 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007762 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007763 case NoLinkage:
7764 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007765 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007766 case InternalLinkage: return CXLinkage_Internal;
7767 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007768 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007769 case ExternalLinkage: return CXLinkage_External;
7770 };
7771
7772 return CXLinkage_Invalid;
7773}
Guy Benyei11169dd2012-12-18 14:30:41 +00007774
7775//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007776// Operations for querying visibility of a cursor.
7777//===----------------------------------------------------------------------===//
7778
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007779CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7780 if (!clang_isDeclaration(cursor.kind))
7781 return CXVisibility_Invalid;
7782
7783 const Decl *D = cxcursor::getCursorDecl(cursor);
7784 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7785 switch (ND->getVisibility()) {
7786 case HiddenVisibility: return CXVisibility_Hidden;
7787 case ProtectedVisibility: return CXVisibility_Protected;
7788 case DefaultVisibility: return CXVisibility_Default;
7789 };
7790
7791 return CXVisibility_Invalid;
7792}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007793
7794//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007795// Operations for querying language of a cursor.
7796//===----------------------------------------------------------------------===//
7797
7798static CXLanguageKind getDeclLanguage(const Decl *D) {
7799 if (!D)
7800 return CXLanguage_C;
7801
7802 switch (D->getKind()) {
7803 default:
7804 break;
7805 case Decl::ImplicitParam:
7806 case Decl::ObjCAtDefsField:
7807 case Decl::ObjCCategory:
7808 case Decl::ObjCCategoryImpl:
7809 case Decl::ObjCCompatibleAlias:
7810 case Decl::ObjCImplementation:
7811 case Decl::ObjCInterface:
7812 case Decl::ObjCIvar:
7813 case Decl::ObjCMethod:
7814 case Decl::ObjCProperty:
7815 case Decl::ObjCPropertyImpl:
7816 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007817 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007818 return CXLanguage_ObjC;
7819 case Decl::CXXConstructor:
7820 case Decl::CXXConversion:
7821 case Decl::CXXDestructor:
7822 case Decl::CXXMethod:
7823 case Decl::CXXRecord:
7824 case Decl::ClassTemplate:
7825 case Decl::ClassTemplatePartialSpecialization:
7826 case Decl::ClassTemplateSpecialization:
7827 case Decl::Friend:
7828 case Decl::FriendTemplate:
7829 case Decl::FunctionTemplate:
7830 case Decl::LinkageSpec:
7831 case Decl::Namespace:
7832 case Decl::NamespaceAlias:
7833 case Decl::NonTypeTemplateParm:
7834 case Decl::StaticAssert:
7835 case Decl::TemplateTemplateParm:
7836 case Decl::TemplateTypeParm:
7837 case Decl::UnresolvedUsingTypename:
7838 case Decl::UnresolvedUsingValue:
7839 case Decl::Using:
7840 case Decl::UsingDirective:
7841 case Decl::UsingShadow:
7842 return CXLanguage_CPlusPlus;
7843 }
7844
7845 return CXLanguage_C;
7846}
7847
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007848static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7849 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007850 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007851
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007852 switch (D->getAvailability()) {
7853 case AR_Available:
7854 case AR_NotYetIntroduced:
7855 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007856 return getCursorAvailabilityForDecl(
7857 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007858 return CXAvailability_Available;
7859
7860 case AR_Deprecated:
7861 return CXAvailability_Deprecated;
7862
7863 case AR_Unavailable:
7864 return CXAvailability_NotAvailable;
7865 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007866
7867 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007868}
7869
Guy Benyei11169dd2012-12-18 14:30:41 +00007870enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7871 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007872 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7873 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007874
7875 return CXAvailability_Available;
7876}
7877
7878static CXVersion convertVersion(VersionTuple In) {
7879 CXVersion Out = { -1, -1, -1 };
7880 if (In.empty())
7881 return Out;
7882
7883 Out.Major = In.getMajor();
7884
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007885 Optional<unsigned> Minor = In.getMinor();
7886 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007887 Out.Minor = *Minor;
7888 else
7889 return Out;
7890
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007891 Optional<unsigned> Subminor = In.getSubminor();
7892 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007893 Out.Subminor = *Subminor;
7894
7895 return Out;
7896}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007897
Alex Lorenz1345ea22017-06-12 19:06:30 +00007898static void getCursorPlatformAvailabilityForDecl(
7899 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7900 int *always_unavailable, CXString *unavailable_message,
7901 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007902 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007903 for (auto A : D->attrs()) {
7904 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007905 HadAvailAttr = true;
7906 if (always_deprecated)
7907 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007908 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007909 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007910 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007911 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007912 continue;
7913 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007914
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007915 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007916 HadAvailAttr = true;
7917 if (always_unavailable)
7918 *always_unavailable = 1;
7919 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007920 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007921 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7922 }
7923 continue;
7924 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007925
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007926 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007927 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007928 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007929 }
7930 }
7931
7932 if (!HadAvailAttr)
7933 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7934 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007935 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7936 deprecated_message, always_unavailable, unavailable_message,
7937 AvailabilityAttrs);
7938
7939 if (AvailabilityAttrs.empty())
7940 return;
7941
Fangrui Song55fab262018-09-26 22:16:28 +00007942 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007943 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7944 return LHS->getPlatform()->getName() <
7945 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007946 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007947 ASTContext &Ctx = D->getASTContext();
7948 auto It = std::unique(
7949 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7950 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7951 if (LHS->getPlatform() != RHS->getPlatform())
7952 return false;
7953
7954 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7955 LHS->getDeprecated() == RHS->getDeprecated() &&
7956 LHS->getObsoleted() == RHS->getObsoleted() &&
7957 LHS->getMessage() == RHS->getMessage() &&
7958 LHS->getReplacement() == RHS->getReplacement())
7959 return true;
7960
7961 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7962 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7963 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7964 return false;
7965
7966 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7967 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7968
7969 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7970 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7971 if (LHS->getMessage().empty())
7972 LHS->setMessage(Ctx, RHS->getMessage());
7973 if (LHS->getReplacement().empty())
7974 LHS->setReplacement(Ctx, RHS->getReplacement());
7975 }
7976
7977 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7978 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7979 if (LHS->getMessage().empty())
7980 LHS->setMessage(Ctx, RHS->getMessage());
7981 if (LHS->getReplacement().empty())
7982 LHS->setReplacement(Ctx, RHS->getReplacement());
7983 }
7984
7985 return true;
7986 });
7987 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007988}
7989
Alex Lorenz1345ea22017-06-12 19:06:30 +00007990int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007991 CXString *deprecated_message,
7992 int *always_unavailable,
7993 CXString *unavailable_message,
7994 CXPlatformAvailability *availability,
7995 int availability_size) {
7996 if (always_deprecated)
7997 *always_deprecated = 0;
7998 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007999 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008000 if (always_unavailable)
8001 *always_unavailable = 0;
8002 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008003 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00008004
Guy Benyei11169dd2012-12-18 14:30:41 +00008005 if (!clang_isDeclaration(cursor.kind))
8006 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00008007
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008008 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00008009 if (!D)
8010 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00008011
Alex Lorenz1345ea22017-06-12 19:06:30 +00008012 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
8013 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
8014 always_unavailable, unavailable_message,
8015 AvailabilityAttrs);
8016 for (const auto &Avail :
8017 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
8018 .take_front(availability_size))) {
8019 availability[Avail.index()].Platform =
8020 cxstring::createDup(Avail.value()->getPlatform()->getName());
8021 availability[Avail.index()].Introduced =
8022 convertVersion(Avail.value()->getIntroduced());
8023 availability[Avail.index()].Deprecated =
8024 convertVersion(Avail.value()->getDeprecated());
8025 availability[Avail.index()].Obsoleted =
8026 convertVersion(Avail.value()->getObsoleted());
8027 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
8028 availability[Avail.index()].Message =
8029 cxstring::createDup(Avail.value()->getMessage());
8030 }
8031
8032 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008033}
Alex Lorenz1345ea22017-06-12 19:06:30 +00008034
Guy Benyei11169dd2012-12-18 14:30:41 +00008035void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
8036 clang_disposeString(availability->Platform);
8037 clang_disposeString(availability->Message);
8038}
8039
8040CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
8041 if (clang_isDeclaration(cursor.kind))
8042 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
8043
8044 return CXLanguage_Invalid;
8045}
8046
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00008047CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
8048 const Decl *D = cxcursor::getCursorDecl(cursor);
8049 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8050 switch (VD->getTLSKind()) {
8051 case VarDecl::TLS_None:
8052 return CXTLS_None;
8053 case VarDecl::TLS_Dynamic:
8054 return CXTLS_Dynamic;
8055 case VarDecl::TLS_Static:
8056 return CXTLS_Static;
8057 }
8058 }
8059
8060 return CXTLS_None;
8061}
8062
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008063 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00008064 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00008065 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008066static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008067 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00008068 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008069
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008070 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8072 return FunTmpl;
8073
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008074 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008075 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8076 return ClassTmpl;
8077
8078 return D;
8079}
8080
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008081
8082enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8083 StorageClass sc = SC_None;
8084 const Decl *D = getCursorDecl(C);
8085 if (D) {
8086 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8087 sc = FD->getStorageClass();
8088 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8089 sc = VD->getStorageClass();
8090 } else {
8091 return CX_SC_Invalid;
8092 }
8093 } else {
8094 return CX_SC_Invalid;
8095 }
8096 switch (sc) {
8097 case SC_None:
8098 return CX_SC_None;
8099 case SC_Extern:
8100 return CX_SC_Extern;
8101 case SC_Static:
8102 return CX_SC_Static;
8103 case SC_PrivateExtern:
8104 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008105 case SC_Auto:
8106 return CX_SC_Auto;
8107 case SC_Register:
8108 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008109 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008110 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008111}
8112
Guy Benyei11169dd2012-12-18 14:30:41 +00008113CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8114 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008115 if (const Decl *D = getCursorDecl(cursor)) {
8116 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008117 if (!DC)
8118 return clang_getNullCursor();
8119
8120 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8121 getCursorTU(cursor));
8122 }
8123 }
8124
8125 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008126 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008127 return MakeCXCursor(D, getCursorTU(cursor));
8128 }
8129
8130 return clang_getNullCursor();
8131}
8132
8133CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8134 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008135 if (const Decl *D = getCursorDecl(cursor)) {
8136 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008137 if (!DC)
8138 return clang_getNullCursor();
8139
8140 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8141 getCursorTU(cursor));
8142 }
8143 }
8144
8145 // FIXME: Note that we can't easily compute the lexical context of a
8146 // statement or expression, so we return nothing.
8147 return clang_getNullCursor();
8148}
8149
8150CXFile clang_getIncludedFile(CXCursor cursor) {
8151 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008152 return nullptr;
8153
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008154 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008155 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008156}
8157
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008158unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8159 if (C.kind != CXCursor_ObjCPropertyDecl)
8160 return CXObjCPropertyAttr_noattr;
8161
8162 unsigned Result = CXObjCPropertyAttr_noattr;
8163 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8164 ObjCPropertyDecl::PropertyAttributeKind Attr =
8165 PD->getPropertyAttributesAsWritten();
8166
8167#define SET_CXOBJCPROP_ATTR(A) \
8168 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8169 Result |= CXObjCPropertyAttr_##A
8170 SET_CXOBJCPROP_ATTR(readonly);
8171 SET_CXOBJCPROP_ATTR(getter);
8172 SET_CXOBJCPROP_ATTR(assign);
8173 SET_CXOBJCPROP_ATTR(readwrite);
8174 SET_CXOBJCPROP_ATTR(retain);
8175 SET_CXOBJCPROP_ATTR(copy);
8176 SET_CXOBJCPROP_ATTR(nonatomic);
8177 SET_CXOBJCPROP_ATTR(setter);
8178 SET_CXOBJCPROP_ATTR(atomic);
8179 SET_CXOBJCPROP_ATTR(weak);
8180 SET_CXOBJCPROP_ATTR(strong);
8181 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008182 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008183#undef SET_CXOBJCPROP_ATTR
8184
8185 return Result;
8186}
8187
Michael Wu6e88f532018-08-03 05:38:29 +00008188CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8189 if (C.kind != CXCursor_ObjCPropertyDecl)
8190 return cxstring::createNull();
8191
8192 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8193 Selector sel = PD->getGetterName();
8194 if (sel.isNull())
8195 return cxstring::createNull();
8196
8197 return cxstring::createDup(sel.getAsString());
8198}
8199
8200CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8201 if (C.kind != CXCursor_ObjCPropertyDecl)
8202 return cxstring::createNull();
8203
8204 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8205 Selector sel = PD->getSetterName();
8206 if (sel.isNull())
8207 return cxstring::createNull();
8208
8209 return cxstring::createDup(sel.getAsString());
8210}
8211
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008212unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8213 if (!clang_isDeclaration(C.kind))
8214 return CXObjCDeclQualifier_None;
8215
8216 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8217 const Decl *D = getCursorDecl(C);
8218 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8219 QT = MD->getObjCDeclQualifier();
8220 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8221 QT = PD->getObjCDeclQualifier();
8222 if (QT == Decl::OBJC_TQ_None)
8223 return CXObjCDeclQualifier_None;
8224
8225 unsigned Result = CXObjCDeclQualifier_None;
8226 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8227 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8228 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8229 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8230 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8231 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8232
8233 return Result;
8234}
8235
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008236unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8237 if (!clang_isDeclaration(C.kind))
8238 return 0;
8239
8240 const Decl *D = getCursorDecl(C);
8241 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8242 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8243 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8244 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8245
8246 return 0;
8247}
8248
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008249unsigned clang_Cursor_isVariadic(CXCursor C) {
8250 if (!clang_isDeclaration(C.kind))
8251 return 0;
8252
8253 const Decl *D = getCursorDecl(C);
8254 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8255 return FD->isVariadic();
8256 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8257 return MD->isVariadic();
8258
8259 return 0;
8260}
8261
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008262unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8263 CXString *language, CXString *definedIn,
8264 unsigned *isGenerated) {
8265 if (!clang_isDeclaration(C.kind))
8266 return 0;
8267
8268 const Decl *D = getCursorDecl(C);
8269
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008270 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008271 if (language)
8272 *language = cxstring::createDup(attr->getLanguage());
8273 if (definedIn)
8274 *definedIn = cxstring::createDup(attr->getDefinedIn());
8275 if (isGenerated)
8276 *isGenerated = attr->getGeneratedDeclaration();
8277 return 1;
8278 }
8279 return 0;
8280}
8281
Guy Benyei11169dd2012-12-18 14:30:41 +00008282CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8283 if (!clang_isDeclaration(C.kind))
8284 return clang_getNullRange();
8285
8286 const Decl *D = getCursorDecl(C);
8287 ASTContext &Context = getCursorContext(C);
8288 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8289 if (!RC)
8290 return clang_getNullRange();
8291
8292 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8293}
8294
8295CXString clang_Cursor_getRawCommentText(CXCursor C) {
8296 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008297 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008298
8299 const Decl *D = getCursorDecl(C);
8300 ASTContext &Context = getCursorContext(C);
8301 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8302 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8303 StringRef();
8304
8305 // Don't duplicate the string because RawText points directly into source
8306 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008307 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008308}
8309
8310CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8311 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008312 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008313
8314 const Decl *D = getCursorDecl(C);
8315 const ASTContext &Context = getCursorContext(C);
8316 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8317
8318 if (RC) {
8319 StringRef BriefText = RC->getBriefText(Context);
8320
8321 // Don't duplicate the string because RawComment ensures that this memory
8322 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008323 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008324 }
8325
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008326 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008327}
8328
Guy Benyei11169dd2012-12-18 14:30:41 +00008329CXModule clang_Cursor_getModule(CXCursor C) {
8330 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008331 if (const ImportDecl *ImportD =
8332 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008333 return ImportD->getImportedModule();
8334 }
8335
Craig Topper69186e72014-06-08 08:38:04 +00008336 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008337}
8338
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008339CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8340 if (isNotUsableTU(TU)) {
8341 LOG_BAD_TU(TU);
8342 return nullptr;
8343 }
8344 if (!File)
8345 return nullptr;
8346 FileEntry *FE = static_cast<FileEntry *>(File);
8347
8348 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8349 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8350 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8351
Richard Smithfeb54b62014-10-23 02:01:19 +00008352 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008353}
8354
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008355CXFile clang_Module_getASTFile(CXModule CXMod) {
8356 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008357 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008358 Module *Mod = static_cast<Module*>(CXMod);
8359 return const_cast<FileEntry *>(Mod->getASTFile());
8360}
8361
Guy Benyei11169dd2012-12-18 14:30:41 +00008362CXModule clang_Module_getParent(CXModule CXMod) {
8363 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008364 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008365 Module *Mod = static_cast<Module*>(CXMod);
8366 return Mod->Parent;
8367}
8368
8369CXString clang_Module_getName(CXModule CXMod) {
8370 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008371 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008372 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008373 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008374}
8375
8376CXString clang_Module_getFullName(CXModule CXMod) {
8377 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008378 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008379 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008380 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008381}
8382
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008383int clang_Module_isSystem(CXModule CXMod) {
8384 if (!CXMod)
8385 return 0;
8386 Module *Mod = static_cast<Module*>(CXMod);
8387 return Mod->IsSystem;
8388}
8389
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008390unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8391 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008392 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008393 LOG_BAD_TU(TU);
8394 return 0;
8395 }
8396 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008397 return 0;
8398 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008399 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8400 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8401 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008402}
8403
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008404CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8405 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008406 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008407 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008408 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008409 }
8410 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008411 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008412 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008413 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008414
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008415 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8416 if (Index < TopHeaders.size())
8417 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008418
Craig Topper69186e72014-06-08 08:38:04 +00008419 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008420}
8421
Guy Benyei11169dd2012-12-18 14:30:41 +00008422//===----------------------------------------------------------------------===//
8423// C++ AST instrospection.
8424//===----------------------------------------------------------------------===//
8425
Jonathan Coe29565352016-04-27 12:48:25 +00008426unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8427 if (!clang_isDeclaration(C.kind))
8428 return 0;
8429
8430 const Decl *D = cxcursor::getCursorDecl(C);
8431 const CXXConstructorDecl *Constructor =
8432 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8433 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8434}
8435
8436unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8437 if (!clang_isDeclaration(C.kind))
8438 return 0;
8439
8440 const Decl *D = cxcursor::getCursorDecl(C);
8441 const CXXConstructorDecl *Constructor =
8442 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8443 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8444}
8445
8446unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8447 if (!clang_isDeclaration(C.kind))
8448 return 0;
8449
8450 const Decl *D = cxcursor::getCursorDecl(C);
8451 const CXXConstructorDecl *Constructor =
8452 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8453 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8454}
8455
8456unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8457 if (!clang_isDeclaration(C.kind))
8458 return 0;
8459
8460 const Decl *D = cxcursor::getCursorDecl(C);
8461 const CXXConstructorDecl *Constructor =
8462 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8463 // Passing 'false' excludes constructors marked 'explicit'.
8464 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8465}
8466
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008467unsigned clang_CXXField_isMutable(CXCursor C) {
8468 if (!clang_isDeclaration(C.kind))
8469 return 0;
8470
8471 if (const auto D = cxcursor::getCursorDecl(C))
8472 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8473 return FD->isMutable() ? 1 : 0;
8474 return 0;
8475}
8476
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008477unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8478 if (!clang_isDeclaration(C.kind))
8479 return 0;
8480
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008481 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008482 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008483 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008484 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8485}
8486
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008487unsigned clang_CXXMethod_isConst(CXCursor C) {
8488 if (!clang_isDeclaration(C.kind))
8489 return 0;
8490
8491 const Decl *D = cxcursor::getCursorDecl(C);
8492 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008493 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008494 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008495}
8496
Jonathan Coe29565352016-04-27 12:48:25 +00008497unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8498 if (!clang_isDeclaration(C.kind))
8499 return 0;
8500
8501 const Decl *D = cxcursor::getCursorDecl(C);
8502 const CXXMethodDecl *Method =
8503 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8504 return (Method && Method->isDefaulted()) ? 1 : 0;
8505}
8506
Guy Benyei11169dd2012-12-18 14:30:41 +00008507unsigned clang_CXXMethod_isStatic(CXCursor C) {
8508 if (!clang_isDeclaration(C.kind))
8509 return 0;
8510
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008511 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008512 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008513 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008514 return (Method && Method->isStatic()) ? 1 : 0;
8515}
8516
8517unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8518 if (!clang_isDeclaration(C.kind))
8519 return 0;
8520
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008521 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008522 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008523 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008524 return (Method && Method->isVirtual()) ? 1 : 0;
8525}
Guy Benyei11169dd2012-12-18 14:30:41 +00008526
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008527unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8528 if (!clang_isDeclaration(C.kind))
8529 return 0;
8530
8531 const auto *D = cxcursor::getCursorDecl(C);
8532 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8533 if (RD)
8534 RD = RD->getDefinition();
8535 return (RD && RD->isAbstract()) ? 1 : 0;
8536}
8537
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008538unsigned clang_EnumDecl_isScoped(CXCursor C) {
8539 if (!clang_isDeclaration(C.kind))
8540 return 0;
8541
8542 const Decl *D = cxcursor::getCursorDecl(C);
8543 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8544 return (Enum && Enum->isScoped()) ? 1 : 0;
8545}
8546
Guy Benyei11169dd2012-12-18 14:30:41 +00008547//===----------------------------------------------------------------------===//
8548// Attribute introspection.
8549//===----------------------------------------------------------------------===//
8550
Guy Benyei11169dd2012-12-18 14:30:41 +00008551CXType clang_getIBOutletCollectionType(CXCursor C) {
8552 if (C.kind != CXCursor_IBOutletCollectionAttr)
8553 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8554
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008555 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008556 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8557
8558 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8559}
Guy Benyei11169dd2012-12-18 14:30:41 +00008560
8561//===----------------------------------------------------------------------===//
8562// Inspecting memory usage.
8563//===----------------------------------------------------------------------===//
8564
8565typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8566
8567static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8568 enum CXTUResourceUsageKind k,
8569 unsigned long amount) {
8570 CXTUResourceUsageEntry entry = { k, amount };
8571 entries.push_back(entry);
8572}
8573
Guy Benyei11169dd2012-12-18 14:30:41 +00008574const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8575 const char *str = "";
8576 switch (kind) {
8577 case CXTUResourceUsage_AST:
8578 str = "ASTContext: expressions, declarations, and types";
8579 break;
8580 case CXTUResourceUsage_Identifiers:
8581 str = "ASTContext: identifiers";
8582 break;
8583 case CXTUResourceUsage_Selectors:
8584 str = "ASTContext: selectors";
8585 break;
8586 case CXTUResourceUsage_GlobalCompletionResults:
8587 str = "Code completion: cached global results";
8588 break;
8589 case CXTUResourceUsage_SourceManagerContentCache:
8590 str = "SourceManager: content cache allocator";
8591 break;
8592 case CXTUResourceUsage_AST_SideTables:
8593 str = "ASTContext: side tables";
8594 break;
8595 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8596 str = "SourceManager: malloc'ed memory buffers";
8597 break;
8598 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8599 str = "SourceManager: mmap'ed memory buffers";
8600 break;
8601 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8602 str = "ExternalASTSource: malloc'ed memory buffers";
8603 break;
8604 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8605 str = "ExternalASTSource: mmap'ed memory buffers";
8606 break;
8607 case CXTUResourceUsage_Preprocessor:
8608 str = "Preprocessor: malloc'ed memory";
8609 break;
8610 case CXTUResourceUsage_PreprocessingRecord:
8611 str = "Preprocessor: PreprocessingRecord";
8612 break;
8613 case CXTUResourceUsage_SourceManager_DataStructures:
8614 str = "SourceManager: data structures and tables";
8615 break;
8616 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8617 str = "Preprocessor: header search tables";
8618 break;
8619 }
8620 return str;
8621}
8622
8623CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008624 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008625 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008626 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008627 return usage;
8628 }
8629
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008630 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008631 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008632 ASTContext &astContext = astUnit->getASTContext();
8633
8634 // How much memory is used by AST nodes and types?
8635 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8636 (unsigned long) astContext.getASTAllocatedMemory());
8637
8638 // How much memory is used by identifiers?
8639 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8640 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8641
8642 // How much memory is used for selectors?
8643 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8644 (unsigned long) astContext.Selectors.getTotalMemory());
8645
8646 // How much memory is used by ASTContext's side tables?
8647 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8648 (unsigned long) astContext.getSideTableAllocatedMemory());
8649
8650 // How much memory is used for caching global code completion results?
8651 unsigned long completionBytes = 0;
8652 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008653 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008654 completionBytes = completionAllocator->getTotalMemory();
8655 }
8656 createCXTUResourceUsageEntry(*entries,
8657 CXTUResourceUsage_GlobalCompletionResults,
8658 completionBytes);
8659
8660 // How much memory is being used by SourceManager's content cache?
8661 createCXTUResourceUsageEntry(*entries,
8662 CXTUResourceUsage_SourceManagerContentCache,
8663 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8664
8665 // How much memory is being used by the MemoryBuffer's in SourceManager?
8666 const SourceManager::MemoryBufferSizes &srcBufs =
8667 astUnit->getSourceManager().getMemoryBufferSizes();
8668
8669 createCXTUResourceUsageEntry(*entries,
8670 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8671 (unsigned long) srcBufs.malloc_bytes);
8672 createCXTUResourceUsageEntry(*entries,
8673 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8674 (unsigned long) srcBufs.mmap_bytes);
8675 createCXTUResourceUsageEntry(*entries,
8676 CXTUResourceUsage_SourceManager_DataStructures,
8677 (unsigned long) astContext.getSourceManager()
8678 .getDataStructureSizes());
8679
8680 // How much memory is being used by the ExternalASTSource?
8681 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8682 const ExternalASTSource::MemoryBufferSizes &sizes =
8683 esrc->getMemoryBufferSizes();
8684
8685 createCXTUResourceUsageEntry(*entries,
8686 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8687 (unsigned long) sizes.malloc_bytes);
8688 createCXTUResourceUsageEntry(*entries,
8689 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8690 (unsigned long) sizes.mmap_bytes);
8691 }
8692
8693 // How much memory is being used by the Preprocessor?
8694 Preprocessor &pp = astUnit->getPreprocessor();
8695 createCXTUResourceUsageEntry(*entries,
8696 CXTUResourceUsage_Preprocessor,
8697 pp.getTotalMemory());
8698
8699 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8700 createCXTUResourceUsageEntry(*entries,
8701 CXTUResourceUsage_PreprocessingRecord,
8702 pRec->getTotalMemory());
8703 }
8704
8705 createCXTUResourceUsageEntry(*entries,
8706 CXTUResourceUsage_Preprocessor_HeaderSearch,
8707 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008708
Guy Benyei11169dd2012-12-18 14:30:41 +00008709 CXTUResourceUsage usage = { (void*) entries.get(),
8710 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008711 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008712 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008713 return usage;
8714}
8715
8716void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8717 if (usage.data)
8718 delete (MemUsageEntries*) usage.data;
8719}
8720
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008721CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8722 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008723 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008724 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008725
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008726 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008727 LOG_BAD_TU(TU);
8728 return skipped;
8729 }
8730
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008731 if (!file)
8732 return skipped;
8733
8734 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8735 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8736 if (!ppRec)
8737 return skipped;
8738
8739 ASTContext &Ctx = astUnit->getASTContext();
8740 SourceManager &sm = Ctx.getSourceManager();
8741 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8742 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008743 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008744
8745 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8746 std::vector<SourceRange> wantedRanges;
8747 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8748 i != ei; ++i) {
8749 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8750 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008751 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8752 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008753 }
8754
8755 skipped->count = wantedRanges.size();
8756 skipped->ranges = new CXSourceRange[skipped->count];
8757 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8758 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8759
8760 return skipped;
8761}
8762
Cameron Desrochersd8091282016-08-18 15:43:55 +00008763CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8764 CXSourceRangeList *skipped = new CXSourceRangeList;
8765 skipped->count = 0;
8766 skipped->ranges = nullptr;
8767
8768 if (isNotUsableTU(TU)) {
8769 LOG_BAD_TU(TU);
8770 return skipped;
8771 }
8772
8773 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8774 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8775 if (!ppRec)
8776 return skipped;
8777
8778 ASTContext &Ctx = astUnit->getASTContext();
8779
8780 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8781
8782 skipped->count = SkippedRanges.size();
8783 skipped->ranges = new CXSourceRange[skipped->count];
8784 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8785 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8786
8787 return skipped;
8788}
8789
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008790void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8791 if (ranges) {
8792 delete[] ranges->ranges;
8793 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008794 }
8795}
8796
Guy Benyei11169dd2012-12-18 14:30:41 +00008797void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8798 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8799 for (unsigned I = 0; I != Usage.numEntries; ++I)
8800 fprintf(stderr, " %s: %lu\n",
8801 clang_getTUResourceUsageName(Usage.entries[I].kind),
8802 Usage.entries[I].amount);
8803
8804 clang_disposeCXTUResourceUsage(Usage);
8805}
8806
8807//===----------------------------------------------------------------------===//
8808// Misc. utility functions.
8809//===----------------------------------------------------------------------===//
8810
Richard Smith0a7b2972018-07-03 21:34:13 +00008811/// Default to using our desired 8 MB stack size on "safety" threads.
8812static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008813
8814namespace clang {
8815
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008816bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008817 unsigned Size) {
8818 if (!Size)
8819 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008820 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008821 return CRC.RunSafelyOnThread(Fn, Size);
8822 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008823}
8824
8825unsigned GetSafetyThreadStackSize() {
8826 return SafetyStackThreadSize;
8827}
8828
8829void SetSafetyThreadStackSize(unsigned Value) {
8830 SafetyStackThreadSize = Value;
8831}
8832
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008833}
Guy Benyei11169dd2012-12-18 14:30:41 +00008834
8835void clang::setThreadBackgroundPriority() {
8836 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8837 return;
8838
Nico Weber18cfd9f2019-04-21 19:18:41 +00008839#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008840 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008841#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008842}
8843
8844void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8845 if (!Unit)
8846 return;
8847
8848 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8849 DEnd = Unit->stored_diag_end();
8850 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008851 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008852 CXString Msg = clang_formatDiagnostic(&Diag,
8853 clang_defaultDiagnosticDisplayOptions());
8854 fprintf(stderr, "%s\n", clang_getCString(Msg));
8855 clang_disposeString(Msg);
8856 }
Nico Weber1865df42018-04-27 19:11:14 +00008857#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008858 // On Windows, force a flush, since there may be multiple copies of
8859 // stderr and stdout in the file system, all with different buffers
8860 // but writing to the same device.
8861 fflush(stderr);
8862#endif
8863}
8864
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008865MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8866 SourceLocation MacroDefLoc,
8867 CXTranslationUnit TU){
8868 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008869 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008870 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008871 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008872
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008873 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008874 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008875 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008876 if (MD) {
8877 for (MacroDirective::DefInfo
8878 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8879 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8880 return Def.getMacroInfo();
8881 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008882 }
8883
Craig Topper69186e72014-06-08 08:38:04 +00008884 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008885}
8886
Richard Smith66a81862015-05-04 02:25:31 +00008887const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008888 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008889 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008890 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008891 const IdentifierInfo *II = MacroDef->getName();
8892 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008893 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008894
8895 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8896}
8897
Richard Smith66a81862015-05-04 02:25:31 +00008898MacroDefinitionRecord *
8899cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8900 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008901 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008902 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008903 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008904 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008905
8906 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008907 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008908 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8909 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008910 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008911
8912 // Check that the token is inside the definition and not its argument list.
8913 SourceManager &SM = Unit->getSourceManager();
8914 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008915 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008916 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008917 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008918
8919 Preprocessor &PP = Unit->getPreprocessor();
8920 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8921 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008922 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008923
Alp Toker2d57cea2014-05-17 04:53:25 +00008924 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008925 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008926 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008927
8928 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008929 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008930 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008931
Richard Smith20e883e2015-04-29 23:20:19 +00008932 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008933 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008934 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008935
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008936 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008937}
8938
Richard Smith66a81862015-05-04 02:25:31 +00008939MacroDefinitionRecord *
8940cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8941 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008942 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008943 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008944
8945 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008946 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008947 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008948 Preprocessor &PP = Unit->getPreprocessor();
8949 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008950 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008951 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8952 Token Tok;
8953 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008954 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008955
8956 return checkForMacroInMacroDefinition(MI, Tok, TU);
8957}
8958
Guy Benyei11169dd2012-12-18 14:30:41 +00008959CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008960 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008961}
8962
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008963Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8964 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008965 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008966 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008967 if (Unit->isMainFileAST())
8968 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008969 return *this;
8970 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008971 } else {
8972 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008973 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008974 return *this;
8975}
8976
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008977Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8978 *this << FE->getName();
8979 return *this;
8980}
8981
8982Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8983 CXString cursorName = clang_getCursorDisplayName(cursor);
8984 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8985 clang_disposeString(cursorName);
8986 return *this;
8987}
8988
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008989Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8990 CXFile File;
8991 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008992 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008993 CXString FileName = clang_getFileName(File);
8994 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8995 clang_disposeString(FileName);
8996 return *this;
8997}
8998
8999Logger &cxindex::Logger::operator<<(CXSourceRange range) {
9000 CXSourceLocation BLoc = clang_getRangeStart(range);
9001 CXSourceLocation ELoc = clang_getRangeEnd(range);
9002
9003 CXFile BFile;
9004 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00009005 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009006
9007 CXFile EFile;
9008 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00009009 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009010
9011 CXString BFileName = clang_getFileName(BFile);
9012 if (BFile == EFile) {
9013 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
9014 BLine, BColumn, ELine, EColumn);
9015 } else {
9016 CXString EFileName = clang_getFileName(EFile);
9017 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
9018 BLine, BColumn)
9019 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
9020 ELine, EColumn);
9021 clang_disposeString(EFileName);
9022 }
9023 clang_disposeString(BFileName);
9024 return *this;
9025}
9026
9027Logger &cxindex::Logger::operator<<(CXString Str) {
9028 *this << clang_getCString(Str);
9029 return *this;
9030}
9031
9032Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
9033 LogOS << Fmt;
9034 return *this;
9035}
9036
Benjamin Kramer762bc332019-08-07 14:44:40 +00009037static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00009038
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009039cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00009040 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009041
9042 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
9043
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009044 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009045 OS << "[libclang:" << Name << ':';
9046
Alp Toker1a86ad22014-07-06 06:24:00 +00009047#ifdef USE_DARWIN_THREADS
9048 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009049 mach_port_t tid = pthread_mach_thread_np(pthread_self());
9050 OS << tid << ':';
9051#endif
9052
9053 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
9054 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00009055 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009056
9057 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00009058 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00009059 OS << "--------------------------------------------------\n";
9060 }
9061}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00009062
9063#ifdef CLANG_TOOL_EXTRA_BUILD
9064// This anchor is used to force the linker to link the clang-tidy plugin.
9065extern volatile int ClangTidyPluginAnchorSource;
9066static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
9067 ClangTidyPluginAnchorSource;
9068
9069// This anchor is used to force the linker to link the clang-include-fixer
9070// plugin.
9071extern volatile int ClangIncludeFixerPluginAnchorSource;
9072static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
9073 ClangIncludeFixerPluginAnchorSource;
9074#endif