blob: 49a1726ac5a239202535f28eccbbc201aa9585d9 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
Guy Benyei11169dd2012-12-18 14:30:41 +000015#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000017#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "CXCursor.h"
19#include "CXSourceLocation.h"
20#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
23#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000027#include "clang/Basic/DiagnosticCategories.h"
28#include "clang/Basic/DiagnosticIDs.h"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000029#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/Basic/Version.h"
31#include "clang/Frontend/ASTUnit.h"
32#include "clang/Frontend/CompilerInstance.h"
33#include "clang/Frontend/FrontendDiagnostic.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000034#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000035#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Lex/HeaderSearch.h"
37#include "clang/Lex/Lexer.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000040#include "clang/Serialization/SerializationDiagnostic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000041#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"
50#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000051#include "llvm/Support/Program.h"
52#include "llvm/Support/SaveAndRestore.h"
53#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000054#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include "llvm/Support/Threading.h"
56#include "llvm/Support/Timer.h"
57#include "llvm/Support/raw_ostream.h"
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;
Guy Benyei11169dd2012-12-18 14:30:41 +000084 return D;
85}
86
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000087bool cxtu::isASTReadError(ASTUnit *AU) {
88 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
89 DEnd = AU->stored_diag_end();
90 D != DEnd; ++D) {
91 if (D->getLevel() >= DiagnosticsEngine::Error &&
92 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
93 diag::DiagCat_AST_Deserialization_Issue)
94 return true;
95 }
96 return false;
97}
98
Guy Benyei11169dd2012-12-18 14:30:41 +000099cxtu::CXTUOwner::~CXTUOwner() {
100 if (TU)
101 clang_disposeTranslationUnit(TU);
102}
103
104/// \brief Compare two source ranges to determine their relative position in
105/// the translation unit.
106static RangeComparisonResult RangeCompare(SourceManager &SM,
107 SourceRange R1,
108 SourceRange R2) {
109 assert(R1.isValid() && "First range is invalid?");
110 assert(R2.isValid() && "Second range is invalid?");
111 if (R1.getEnd() != R2.getBegin() &&
112 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
113 return RangeBefore;
114 if (R2.getEnd() != R1.getBegin() &&
115 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
116 return RangeAfter;
117 return RangeOverlap;
118}
119
120/// \brief Determine if a source location falls within, before, or after a
121/// a given source range.
122static RangeComparisonResult LocationCompare(SourceManager &SM,
123 SourceLocation L, SourceRange R) {
124 assert(R.isValid() && "First range is invalid?");
125 assert(L.isValid() && "Second range is invalid?");
126 if (L == R.getBegin() || L == R.getEnd())
127 return RangeOverlap;
128 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
129 return RangeBefore;
130 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
131 return RangeAfter;
132 return RangeOverlap;
133}
134
135/// \brief Translate a Clang source range into a CIndex source range.
136///
137/// Clang internally represents ranges where the end location points to the
138/// start of the token at the end. However, for external clients it is more
139/// useful to have a CXSourceRange be a proper half-open interval. This routine
140/// does the appropriate translation.
141CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
142 const LangOptions &LangOpts,
143 const CharSourceRange &R) {
144 // We want the last character in this location, so we will adjust the
145 // location accordingly.
146 SourceLocation EndLoc = R.getEnd();
147 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
148 EndLoc = SM.getExpansionRange(EndLoc).second;
Yaron Keren8b563662015-10-03 10:46:20 +0000149 if (R.isTokenRange() && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000150 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
151 SM, LangOpts);
152 EndLoc = EndLoc.getLocWithOffset(Length);
153 }
154
Bill Wendlingeade3622013-01-23 08:25:41 +0000155 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000156 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000157 R.getBegin().getRawEncoding(),
158 EndLoc.getRawEncoding()
159 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000160 return Result;
161}
162
163//===----------------------------------------------------------------------===//
164// Cursor visitor.
165//===----------------------------------------------------------------------===//
166
167static SourceRange getRawCursorExtent(CXCursor C);
168static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
169
170
171RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
172 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
173}
174
175/// \brief Visit the given cursor and, if requested by the visitor,
176/// its children.
177///
178/// \param Cursor the cursor to visit.
179///
180/// \param CheckedRegionOfInterest if true, then the caller already checked
181/// that this cursor is within the region of interest.
182///
183/// \returns true if the visitation should be aborted, false if it
184/// should continue.
185bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
186 if (clang_isInvalid(Cursor.kind))
187 return false;
188
189 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000190 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000191 if (!D) {
192 assert(0 && "Invalid declaration cursor");
193 return true; // abort.
194 }
195
196 // Ignore implicit declarations, unless it's an objc method because
197 // currently we should report implicit methods for properties when indexing.
198 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
199 return false;
200 }
201
202 // If we have a range of interest, and this cursor doesn't intersect with it,
203 // we're done.
204 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
205 SourceRange Range = getRawCursorExtent(Cursor);
206 if (Range.isInvalid() || CompareRegionOfInterest(Range))
207 return false;
208 }
209
210 switch (Visitor(Cursor, Parent, ClientData)) {
211 case CXChildVisit_Break:
212 return true;
213
214 case CXChildVisit_Continue:
215 return false;
216
217 case CXChildVisit_Recurse: {
218 bool ret = VisitChildren(Cursor);
219 if (PostChildrenVisitor)
220 if (PostChildrenVisitor(Cursor, ClientData))
221 return true;
222 return ret;
223 }
224 }
225
226 llvm_unreachable("Invalid CXChildVisitResult!");
227}
228
229static bool visitPreprocessedEntitiesInRange(SourceRange R,
230 PreprocessingRecord &PPRec,
231 CursorVisitor &Visitor) {
232 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
233 FileID FID;
234
235 if (!Visitor.shouldVisitIncludedEntities()) {
236 // If the begin/end of the range lie in the same FileID, do the optimization
237 // where we skip preprocessed entities that do not come from the same FileID.
238 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
239 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
240 FID = FileID();
241 }
242
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000243 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
244 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000245 PPRec, FID);
246}
247
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000248bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000250 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000251
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000252 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000253 SourceManager &SM = Unit->getSourceManager();
254
255 std::pair<FileID, unsigned>
256 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
257 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
258
259 if (End.first != Begin.first) {
260 // If the end does not reside in the same file, try to recover by
261 // picking the end of the file of begin location.
262 End.first = Begin.first;
263 End.second = SM.getFileIDSize(Begin.first);
264 }
265
266 assert(Begin.first == End.first);
267 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000268 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000269
270 FileID File = Begin.first;
271 unsigned Offset = Begin.second;
272 unsigned Length = End.second - Begin.second;
273
274 if (!VisitDeclsOnly && !VisitPreprocessorLast)
275 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000276 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000277
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000278 if (visitDeclsFromFileRegion(File, Offset, Length))
279 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000280
281 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000282 return visitPreprocessedEntitiesInRegion();
283
284 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000285}
286
287static bool isInLexicalContext(Decl *D, DeclContext *DC) {
288 if (!DC)
289 return false;
290
291 for (DeclContext *DeclDC = D->getLexicalDeclContext();
292 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
293 if (DeclDC == DC)
294 return true;
295 }
296 return false;
297}
298
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000299bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000300 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000301 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000302 SourceManager &SM = Unit->getSourceManager();
303 SourceRange Range = RegionOfInterest;
304
305 SmallVector<Decl *, 16> Decls;
306 Unit->findFileRegionDecls(File, Offset, Length, Decls);
307
308 // If we didn't find any file level decls for the file, try looking at the
309 // file that it was included from.
310 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
311 bool Invalid = false;
312 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
313 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000314 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000315
316 SourceLocation Outer;
317 if (SLEntry.isFile())
318 Outer = SLEntry.getFile().getIncludeLoc();
319 else
320 Outer = SLEntry.getExpansion().getExpansionLocStart();
321 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000322 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000323
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000324 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000325 Length = 0;
326 Unit->findFileRegionDecls(File, Offset, Length, Decls);
327 }
328
329 assert(!Decls.empty());
330
331 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000332 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000333 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
334 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000335 Decl *D = *DIt;
336 if (D->getSourceRange().isInvalid())
337 continue;
338
339 if (isInLexicalContext(D, CurDC))
340 continue;
341
342 CurDC = dyn_cast<DeclContext>(D);
343
344 if (TagDecl *TD = dyn_cast<TagDecl>(D))
345 if (!TD->isFreeStanding())
346 continue;
347
348 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
349 if (CompRes == RangeBefore)
350 continue;
351 if (CompRes == RangeAfter)
352 break;
353
354 assert(CompRes == RangeOverlap);
355 VisitedAtLeastOnce = true;
356
357 if (isa<ObjCContainerDecl>(D)) {
358 FileDI_current = &DIt;
359 FileDE_current = DE;
360 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000361 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000362 }
363
364 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000365 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000366 }
367
368 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000369 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000370
371 // No Decls overlapped with the range. Move up the lexical context until there
372 // is a context that contains the range or we reach the translation unit
373 // level.
374 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
375 : (*(DIt-1))->getLexicalDeclContext();
376
377 while (DC && !DC->isTranslationUnit()) {
378 Decl *D = cast<Decl>(DC);
379 SourceRange CurDeclRange = D->getSourceRange();
380 if (CurDeclRange.isInvalid())
381 break;
382
383 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000384 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
385 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000386 }
387
388 DC = D->getLexicalDeclContext();
389 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000390
391 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000392}
393
394bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
395 if (!AU->getPreprocessor().getPreprocessingRecord())
396 return false;
397
398 PreprocessingRecord &PPRec
399 = *AU->getPreprocessor().getPreprocessingRecord();
400 SourceManager &SM = AU->getSourceManager();
401
402 if (RegionOfInterest.isValid()) {
403 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
404 SourceLocation B = MappedRange.getBegin();
405 SourceLocation E = MappedRange.getEnd();
406
407 if (AU->isInPreambleFileID(B)) {
408 if (SM.isLoadedSourceLocation(E))
409 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
410 PPRec, *this);
411
412 // Beginning of range lies in the preamble but it also extends beyond
413 // it into the main file. Split the range into 2 parts, one covering
414 // the preamble and another covering the main file. This allows subsequent
415 // calls to visitPreprocessedEntitiesInRange to accept a source range that
416 // lies in the same FileID, allowing it to skip preprocessed entities that
417 // do not come from the same FileID.
418 bool breaked =
419 visitPreprocessedEntitiesInRange(
420 SourceRange(B, AU->getEndOfPreambleFileID()),
421 PPRec, *this);
422 if (breaked) return true;
423 return visitPreprocessedEntitiesInRange(
424 SourceRange(AU->getStartOfMainFileID(), E),
425 PPRec, *this);
426 }
427
428 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
429 }
430
431 bool OnlyLocalDecls
432 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
433
434 if (OnlyLocalDecls)
435 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
436 PPRec);
437
438 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
439}
440
441template<typename InputIterator>
442bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
443 InputIterator Last,
444 PreprocessingRecord &PPRec,
445 FileID FID) {
446 for (; First != Last; ++First) {
447 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
448 continue;
449
450 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000451 if (!PPE)
452 continue;
453
Guy Benyei11169dd2012-12-18 14:30:41 +0000454 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
455 if (Visit(MakeMacroExpansionCursor(ME, TU)))
456 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000457
Guy Benyei11169dd2012-12-18 14:30:41 +0000458 continue;
459 }
Richard Smith66a81862015-05-04 02:25:31 +0000460
461 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000462 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
463 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000464
Guy Benyei11169dd2012-12-18 14:30:41 +0000465 continue;
466 }
467
468 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
469 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
470 return true;
471
472 continue;
473 }
474 }
475
476 return false;
477}
478
479/// \brief Visit the children of the given cursor.
480///
481/// \returns true if the visitation should be aborted, false if it
482/// should continue.
483bool CursorVisitor::VisitChildren(CXCursor Cursor) {
484 if (clang_isReference(Cursor.kind) &&
485 Cursor.kind != CXCursor_CXXBaseSpecifier) {
486 // By definition, references have no children.
487 return false;
488 }
489
490 // Set the Parent field to Cursor, then back to its old value once we're
491 // done.
492 SetParentRAII SetParent(Parent, StmtParent, Cursor);
493
494 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000495 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000496 if (!D)
497 return false;
498
499 return VisitAttributes(D) || Visit(D);
500 }
501
502 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000503 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000504 return Visit(S);
505
506 return false;
507 }
508
509 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000510 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000511 return Visit(E);
512
513 return false;
514 }
515
516 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000517 CXTranslationUnit TU = getCursorTU(Cursor);
518 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000519
520 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
521 for (unsigned I = 0; I != 2; ++I) {
522 if (VisitOrder[I]) {
523 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
524 RegionOfInterest.isInvalid()) {
525 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
526 TLEnd = CXXUnit->top_level_end();
527 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000528 const Optional<bool> V = handleDeclForVisitation(*TL);
529 if (!V.hasValue())
530 continue;
531 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000532 }
533 } else if (VisitDeclContext(
534 CXXUnit->getASTContext().getTranslationUnitDecl()))
535 return true;
536 continue;
537 }
538
539 // Walk the preprocessing record.
540 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
541 visitPreprocessedEntitiesInRegion();
542 }
543
544 return false;
545 }
546
547 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000548 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000549 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
550 return Visit(BaseTSInfo->getTypeLoc());
551 }
552 }
553 }
554
555 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000556 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000557 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000558 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000559 return Visit(cxcursor::MakeCursorObjCClassRef(
560 ObjT->getInterface(),
561 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000562 }
563
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000564 // If pointing inside a macro definition, check if the token is an identifier
565 // that was ever defined as a macro. In such a case, create a "pseudo" macro
566 // expansion cursor for that token.
567 SourceLocation BeginLoc = RegionOfInterest.getBegin();
568 if (Cursor.kind == CXCursor_MacroDefinition &&
569 BeginLoc == RegionOfInterest.getEnd()) {
570 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000571 const MacroInfo *MI =
572 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000573 if (MacroDefinitionRecord *MacroDef =
574 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000575 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
576 }
577
Guy Benyei11169dd2012-12-18 14:30:41 +0000578 // Nothing to visit at the moment.
579 return false;
580}
581
582bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
583 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
584 if (Visit(TSInfo->getTypeLoc()))
585 return true;
586
587 if (Stmt *Body = B->getBody())
588 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
589
590 return false;
591}
592
Ted Kremenek03325582013-02-21 01:29:01 +0000593Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000594 if (RegionOfInterest.isValid()) {
595 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
596 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000597 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000598
599 switch (CompareRegionOfInterest(Range)) {
600 case RangeBefore:
601 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000602 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000603
604 case RangeAfter:
605 // This declaration comes after the region of interest; we're done.
606 return false;
607
608 case RangeOverlap:
609 // This declaration overlaps the region of interest; visit it.
610 break;
611 }
612 }
613 return true;
614}
615
616bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
617 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
618
619 // FIXME: Eventually remove. This part of a hack to support proper
620 // iteration over all Decls contained lexically within an ObjC container.
621 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
622 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
623
624 for ( ; I != E; ++I) {
625 Decl *D = *I;
626 if (D->getLexicalDeclContext() != DC)
627 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000628 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000629 if (!V.hasValue())
630 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000631 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000632 }
633 return false;
634}
635
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000636Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
637 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
638
639 // Ignore synthesized ivars here, otherwise if we have something like:
640 // @synthesize prop = _prop;
641 // and '_prop' is not declared, we will encounter a '_prop' ivar before
642 // encountering the 'prop' synthesize declaration and we will think that
643 // we passed the region-of-interest.
644 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
645 if (ivarD->getSynthesize())
646 return None;
647 }
648
649 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
650 // declarations is a mismatch with the compiler semantics.
651 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
652 auto *ID = cast<ObjCInterfaceDecl>(D);
653 if (!ID->isThisDeclarationADefinition())
654 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
655
656 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
657 auto *PD = cast<ObjCProtocolDecl>(D);
658 if (!PD->isThisDeclarationADefinition())
659 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
660 }
661
662 const Optional<bool> V = shouldVisitCursor(Cursor);
663 if (!V.hasValue())
664 return None;
665 if (!V.getValue())
666 return false;
667 if (Visit(Cursor, true))
668 return true;
669 return None;
670}
671
Guy Benyei11169dd2012-12-18 14:30:41 +0000672bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
673 llvm_unreachable("Translation units are visited directly by Visit()");
674}
675
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000676bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
677 if (VisitTemplateParameters(D->getTemplateParameters()))
678 return true;
679
680 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
681}
682
Guy Benyei11169dd2012-12-18 14:30:41 +0000683bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
684 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
685 return Visit(TSInfo->getTypeLoc());
686
687 return false;
688}
689
690bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
691 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
692 return Visit(TSInfo->getTypeLoc());
693
694 return false;
695}
696
697bool CursorVisitor::VisitTagDecl(TagDecl *D) {
698 return VisitDeclContext(D);
699}
700
701bool CursorVisitor::VisitClassTemplateSpecializationDecl(
702 ClassTemplateSpecializationDecl *D) {
703 bool ShouldVisitBody = false;
704 switch (D->getSpecializationKind()) {
705 case TSK_Undeclared:
706 case TSK_ImplicitInstantiation:
707 // Nothing to visit
708 return false;
709
710 case TSK_ExplicitInstantiationDeclaration:
711 case TSK_ExplicitInstantiationDefinition:
712 break;
713
714 case TSK_ExplicitSpecialization:
715 ShouldVisitBody = true;
716 break;
717 }
718
719 // Visit the template arguments used in the specialization.
720 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
721 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000722 if (TemplateSpecializationTypeLoc TSTLoc =
723 TL.getAs<TemplateSpecializationTypeLoc>()) {
724 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
725 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000726 return true;
727 }
728 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000729
730 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000731}
732
733bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
734 ClassTemplatePartialSpecializationDecl *D) {
735 // FIXME: Visit the "outer" template parameter lists on the TagDecl
736 // before visiting these template parameters.
737 if (VisitTemplateParameters(D->getTemplateParameters()))
738 return true;
739
740 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000741 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
742 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
743 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000744 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
745 return true;
746
747 return VisitCXXRecordDecl(D);
748}
749
750bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
751 // Visit the default argument.
752 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
753 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
754 if (Visit(DefArg->getTypeLoc()))
755 return true;
756
757 return false;
758}
759
760bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
761 if (Expr *Init = D->getInitExpr())
762 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
763 return false;
764}
765
766bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000767 unsigned NumParamList = DD->getNumTemplateParameterLists();
768 for (unsigned i = 0; i < NumParamList; i++) {
769 TemplateParameterList* Params = DD->getTemplateParameterList(i);
770 if (VisitTemplateParameters(Params))
771 return true;
772 }
773
Guy Benyei11169dd2012-12-18 14:30:41 +0000774 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
775 if (Visit(TSInfo->getTypeLoc()))
776 return true;
777
778 // Visit the nested-name-specifier, if present.
779 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
780 if (VisitNestedNameSpecifierLoc(QualifierLoc))
781 return true;
782
783 return false;
784}
785
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000786/// \brief Compare two base or member initializers based on their source order.
787static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
788 CXXCtorInitializer *const *Y) {
789 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
790}
791
Guy Benyei11169dd2012-12-18 14:30:41 +0000792bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000793 unsigned NumParamList = ND->getNumTemplateParameterLists();
794 for (unsigned i = 0; i < NumParamList; i++) {
795 TemplateParameterList* Params = ND->getTemplateParameterList(i);
796 if (VisitTemplateParameters(Params))
797 return true;
798 }
799
Guy Benyei11169dd2012-12-18 14:30:41 +0000800 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
801 // Visit the function declaration's syntactic components in the order
802 // written. This requires a bit of work.
803 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +0000804 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Guy Benyei11169dd2012-12-18 14:30:41 +0000805
806 // If we have a function declared directly (without the use of a typedef),
807 // visit just the return type. Otherwise, just visit the function's type
808 // now.
Alp Toker42a16a62014-01-25 23:51:36 +0000809 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
Guy Benyei11169dd2012-12-18 14:30:41 +0000810 (!FTL && Visit(TL)))
811 return true;
812
813 // Visit the nested-name-specifier, if present.
814 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
815 if (VisitNestedNameSpecifierLoc(QualifierLoc))
816 return true;
817
818 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000819 if (!isa<CXXDestructorDecl>(ND))
820 if (VisitDeclarationNameInfo(ND->getNameInfo()))
821 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000822
823 // FIXME: Visit explicitly-specified template arguments!
824
825 // Visit the function parameters, if we have a function type.
David Blaikie6adc78e2013-02-18 22:06:02 +0000826 if (FTL && VisitFunctionTypeLoc(FTL, true))
Guy Benyei11169dd2012-12-18 14:30:41 +0000827 return true;
828
Bill Wendling44426052012-12-20 19:22:21 +0000829 // FIXME: Attributes?
Guy Benyei11169dd2012-12-18 14:30:41 +0000830 }
831
832 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
833 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
834 // Find the initializers that were written in the source.
835 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000836 for (auto *I : Constructor->inits()) {
837 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000838 continue;
839
Aaron Ballman0ad78302014-03-13 17:34:31 +0000840 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000841 }
842
843 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000844 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
845 &CompareCXXCtorInitializers);
846
Guy Benyei11169dd2012-12-18 14:30:41 +0000847 // Visit the initializers in source order
848 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
849 CXXCtorInitializer *Init = WrittenInits[I];
850 if (Init->isAnyMemberInitializer()) {
851 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
852 Init->getMemberLocation(), TU)))
853 return true;
854 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
855 if (Visit(TInfo->getTypeLoc()))
856 return true;
857 }
858
859 // Visit the initializer value.
860 if (Expr *Initializer = Init->getInit())
861 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
862 return true;
863 }
864 }
865
866 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
867 return true;
868 }
869
870 return false;
871}
872
873bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
874 if (VisitDeclaratorDecl(D))
875 return true;
876
877 if (Expr *BitWidth = D->getBitWidth())
878 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
879
Benjamin Kramer99f97592017-11-15 12:20:41 +0000880 if (Expr *Init = D->getInClassInitializer())
881 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
882
Guy Benyei11169dd2012-12-18 14:30:41 +0000883 return false;
884}
885
886bool CursorVisitor::VisitVarDecl(VarDecl *D) {
887 if (VisitDeclaratorDecl(D))
888 return true;
889
890 if (Expr *Init = D->getInit())
891 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
892
893 return false;
894}
895
896bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
897 if (VisitDeclaratorDecl(D))
898 return true;
899
900 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
901 if (Expr *DefArg = D->getDefaultArgument())
902 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
903
904 return false;
905}
906
907bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
908 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
909 // before visiting these template parameters.
910 if (VisitTemplateParameters(D->getTemplateParameters()))
911 return true;
912
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000913 auto* FD = D->getTemplatedDecl();
914 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000915}
916
917bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
918 // FIXME: Visit the "outer" template parameter lists on the TagDecl
919 // before visiting these template parameters.
920 if (VisitTemplateParameters(D->getTemplateParameters()))
921 return true;
922
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000923 auto* CD = D->getTemplatedDecl();
924 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000925}
926
927bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
928 if (VisitTemplateParameters(D->getTemplateParameters()))
929 return true;
930
931 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
932 VisitTemplateArgumentLoc(D->getDefaultArgument()))
933 return true;
934
935 return false;
936}
937
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000938bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
939 // Visit the bound, if it's explicit.
940 if (D->hasExplicitBound()) {
941 if (auto TInfo = D->getTypeSourceInfo()) {
942 if (Visit(TInfo->getTypeLoc()))
943 return true;
944 }
945 }
946
947 return false;
948}
949
Guy Benyei11169dd2012-12-18 14:30:41 +0000950bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000951 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 if (Visit(TSInfo->getTypeLoc()))
953 return true;
954
David Majnemer59f77922016-06-24 04:05:48 +0000955 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000956 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 return true;
958 }
959
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000960 return ND->isThisDeclarationADefinition() &&
961 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000962}
963
964template <typename DeclIt>
965static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
966 SourceManager &SM, SourceLocation EndLoc,
967 SmallVectorImpl<Decl *> &Decls) {
968 DeclIt next = *DI_current;
969 while (++next != DE_current) {
970 Decl *D_next = *next;
971 if (!D_next)
972 break;
973 SourceLocation L = D_next->getLocStart();
974 if (!L.isValid())
975 break;
976 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
977 *DI_current = next;
978 Decls.push_back(D_next);
979 continue;
980 }
981 break;
982 }
983}
984
Guy Benyei11169dd2012-12-18 14:30:41 +0000985bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
986 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
987 // an @implementation can lexically contain Decls that are not properly
988 // nested in the AST. When we identify such cases, we need to retrofit
989 // this nesting here.
990 if (!DI_current && !FileDI_current)
991 return VisitDeclContext(D);
992
993 // Scan the Decls that immediately come after the container
994 // in the current DeclContext. If any fall within the
995 // container's lexical region, stash them into a vector
996 // for later processing.
997 SmallVector<Decl *, 24> DeclsInContainer;
998 SourceLocation EndLoc = D->getSourceRange().getEnd();
999 SourceManager &SM = AU->getSourceManager();
1000 if (EndLoc.isValid()) {
1001 if (DI_current) {
1002 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1003 DeclsInContainer);
1004 } else {
1005 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1006 DeclsInContainer);
1007 }
1008 }
1009
1010 // The common case.
1011 if (DeclsInContainer.empty())
1012 return VisitDeclContext(D);
1013
1014 // Get all the Decls in the DeclContext, and sort them with the
1015 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001016 for (auto *SubDecl : D->decls()) {
1017 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1018 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001019 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001020 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001021 }
1022
1023 // Now sort the Decls so that they appear in lexical order.
1024 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001025 [&SM](Decl *A, Decl *B) {
1026 SourceLocation L_A = A->getLocStart();
1027 SourceLocation L_B = B->getLocStart();
Mandeep Singh Grangfa51e1d2017-11-29 20:55:13 +00001028 return L_A != L_B ?
1029 SM.isBeforeInTranslationUnit(L_A, L_B) :
1030 SM.isBeforeInTranslationUnit(A->getLocEnd(), B->getLocEnd());
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001031 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001032
1033 // Now visit the decls.
1034 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1035 E = DeclsInContainer.end(); I != E; ++I) {
1036 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001037 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001038 if (!V.hasValue())
1039 continue;
1040 if (!V.getValue())
1041 return false;
1042 if (Visit(Cursor, true))
1043 return true;
1044 }
1045 return false;
1046}
1047
1048bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1049 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1050 TU)))
1051 return true;
1052
Douglas Gregore9d95f12015-07-07 03:57:35 +00001053 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1054 return true;
1055
Guy Benyei11169dd2012-12-18 14:30:41 +00001056 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1057 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1058 E = ND->protocol_end(); I != E; ++I, ++PL)
1059 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1060 return true;
1061
1062 return VisitObjCContainerDecl(ND);
1063}
1064
1065bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1066 if (!PID->isThisDeclarationADefinition())
1067 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1068
1069 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1070 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1071 E = PID->protocol_end(); I != E; ++I, ++PL)
1072 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1073 return true;
1074
1075 return VisitObjCContainerDecl(PID);
1076}
1077
1078bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1079 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1080 return true;
1081
1082 // FIXME: This implements a workaround with @property declarations also being
1083 // installed in the DeclContext for the @interface. Eventually this code
1084 // should be removed.
1085 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1086 if (!CDecl || !CDecl->IsClassExtension())
1087 return false;
1088
1089 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1090 if (!ID)
1091 return false;
1092
1093 IdentifierInfo *PropertyId = PD->getIdentifier();
1094 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001095 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1096 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001097
1098 if (!prevDecl)
1099 return false;
1100
1101 // Visit synthesized methods since they will be skipped when visiting
1102 // the @interface.
1103 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1104 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1105 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1106 return true;
1107
1108 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1109 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1110 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1111 return true;
1112
1113 return false;
1114}
1115
Douglas Gregore9d95f12015-07-07 03:57:35 +00001116bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1117 if (!typeParamList)
1118 return false;
1119
1120 for (auto *typeParam : *typeParamList) {
1121 // Visit the type parameter.
1122 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1123 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001124 }
1125
1126 return false;
1127}
1128
Guy Benyei11169dd2012-12-18 14:30:41 +00001129bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1130 if (!D->isThisDeclarationADefinition()) {
1131 // Forward declaration is treated like a reference.
1132 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1133 }
1134
Douglas Gregore9d95f12015-07-07 03:57:35 +00001135 // Objective-C type parameters.
1136 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1137 return true;
1138
Guy Benyei11169dd2012-12-18 14:30:41 +00001139 // Issue callbacks for super class.
1140 if (D->getSuperClass() &&
1141 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1142 D->getSuperClassLoc(),
1143 TU)))
1144 return true;
1145
Douglas Gregore9d95f12015-07-07 03:57:35 +00001146 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1147 if (Visit(SuperClassTInfo->getTypeLoc()))
1148 return true;
1149
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1151 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1152 E = D->protocol_end(); I != E; ++I, ++PL)
1153 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1154 return true;
1155
1156 return VisitObjCContainerDecl(D);
1157}
1158
1159bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1160 return VisitObjCContainerDecl(D);
1161}
1162
1163bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1164 // 'ID' could be null when dealing with invalid code.
1165 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1166 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1167 return true;
1168
1169 return VisitObjCImplDecl(D);
1170}
1171
1172bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1173#if 0
1174 // Issue callbacks for super class.
1175 // FIXME: No source location information!
1176 if (D->getSuperClass() &&
1177 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1178 D->getSuperClassLoc(),
1179 TU)))
1180 return true;
1181#endif
1182
1183 return VisitObjCImplDecl(D);
1184}
1185
1186bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1187 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1188 if (PD->isIvarNameSpecified())
1189 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1190
1191 return false;
1192}
1193
1194bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1195 return VisitDeclContext(D);
1196}
1197
1198bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1199 // Visit nested-name-specifier.
1200 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1201 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1202 return true;
1203
1204 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1205 D->getTargetNameLoc(), TU));
1206}
1207
1208bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1209 // Visit nested-name-specifier.
1210 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1211 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1212 return true;
1213 }
1214
1215 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1216 return true;
1217
1218 return VisitDeclarationNameInfo(D->getNameInfo());
1219}
1220
1221bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1222 // Visit nested-name-specifier.
1223 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1224 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1225 return true;
1226
1227 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1228 D->getIdentLocation(), TU));
1229}
1230
1231bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1232 // Visit nested-name-specifier.
1233 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1234 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1235 return true;
1236 }
1237
1238 return VisitDeclarationNameInfo(D->getNameInfo());
1239}
1240
1241bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1242 UnresolvedUsingTypenameDecl *D) {
1243 // Visit nested-name-specifier.
1244 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1245 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1246 return true;
1247
1248 return false;
1249}
1250
Olivier Goffart81978012016-06-09 16:15:55 +00001251bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1252 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1253 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001254 if (StringLiteral *Message = D->getMessage())
1255 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1256 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001257 return false;
1258}
1259
Olivier Goffartd211c642016-11-04 06:29:27 +00001260bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1261 if (NamedDecl *FriendD = D->getFriendDecl()) {
1262 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1263 return true;
1264 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1265 if (Visit(TI->getTypeLoc()))
1266 return true;
1267 }
1268 return false;
1269}
1270
Guy Benyei11169dd2012-12-18 14:30:41 +00001271bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1272 switch (Name.getName().getNameKind()) {
1273 case clang::DeclarationName::Identifier:
1274 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001275 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001276 case clang::DeclarationName::CXXOperatorName:
1277 case clang::DeclarationName::CXXUsingDirective:
1278 return false;
Richard Smith35845152017-02-07 01:37:30 +00001279
Guy Benyei11169dd2012-12-18 14:30:41 +00001280 case clang::DeclarationName::CXXConstructorName:
1281 case clang::DeclarationName::CXXDestructorName:
1282 case clang::DeclarationName::CXXConversionFunctionName:
1283 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1284 return Visit(TSInfo->getTypeLoc());
1285 return false;
1286
1287 case clang::DeclarationName::ObjCZeroArgSelector:
1288 case clang::DeclarationName::ObjCOneArgSelector:
1289 case clang::DeclarationName::ObjCMultiArgSelector:
1290 // FIXME: Per-identifier location info?
1291 return false;
1292 }
1293
1294 llvm_unreachable("Invalid DeclarationName::Kind!");
1295}
1296
1297bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1298 SourceRange Range) {
1299 // FIXME: This whole routine is a hack to work around the lack of proper
1300 // source information in nested-name-specifiers (PR5791). Since we do have
1301 // a beginning source location, we can visit the first component of the
1302 // nested-name-specifier, if it's a single-token component.
1303 if (!NNS)
1304 return false;
1305
1306 // Get the first component in the nested-name-specifier.
1307 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1308 NNS = Prefix;
1309
1310 switch (NNS->getKind()) {
1311 case NestedNameSpecifier::Namespace:
1312 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1313 TU));
1314
1315 case NestedNameSpecifier::NamespaceAlias:
1316 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1317 Range.getBegin(), TU));
1318
1319 case NestedNameSpecifier::TypeSpec: {
1320 // If the type has a form where we know that the beginning of the source
1321 // range matches up with a reference cursor. Visit the appropriate reference
1322 // cursor.
1323 const Type *T = NNS->getAsType();
1324 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1325 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1326 if (const TagType *Tag = dyn_cast<TagType>(T))
1327 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1328 if (const TemplateSpecializationType *TST
1329 = dyn_cast<TemplateSpecializationType>(T))
1330 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1331 break;
1332 }
1333
1334 case NestedNameSpecifier::TypeSpecWithTemplate:
1335 case NestedNameSpecifier::Global:
1336 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001337 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001338 break;
1339 }
1340
1341 return false;
1342}
1343
1344bool
1345CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1346 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1347 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1348 Qualifiers.push_back(Qualifier);
1349
1350 while (!Qualifiers.empty()) {
1351 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1352 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1353 switch (NNS->getKind()) {
1354 case NestedNameSpecifier::Namespace:
1355 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1356 Q.getLocalBeginLoc(),
1357 TU)))
1358 return true;
1359
1360 break;
1361
1362 case NestedNameSpecifier::NamespaceAlias:
1363 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1364 Q.getLocalBeginLoc(),
1365 TU)))
1366 return true;
1367
1368 break;
1369
1370 case NestedNameSpecifier::TypeSpec:
1371 case NestedNameSpecifier::TypeSpecWithTemplate:
1372 if (Visit(Q.getTypeLoc()))
1373 return true;
1374
1375 break;
1376
1377 case NestedNameSpecifier::Global:
1378 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001379 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 break;
1381 }
1382 }
1383
1384 return false;
1385}
1386
1387bool CursorVisitor::VisitTemplateParameters(
1388 const TemplateParameterList *Params) {
1389 if (!Params)
1390 return false;
1391
1392 for (TemplateParameterList::const_iterator P = Params->begin(),
1393 PEnd = Params->end();
1394 P != PEnd; ++P) {
1395 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1396 return true;
1397 }
1398
1399 return false;
1400}
1401
1402bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1403 switch (Name.getKind()) {
1404 case TemplateName::Template:
1405 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1406
1407 case TemplateName::OverloadedTemplate:
1408 // Visit the overloaded template set.
1409 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1410 return true;
1411
1412 return false;
1413
1414 case TemplateName::DependentTemplate:
1415 // FIXME: Visit nested-name-specifier.
1416 return false;
1417
1418 case TemplateName::QualifiedTemplate:
1419 // FIXME: Visit nested-name-specifier.
1420 return Visit(MakeCursorTemplateRef(
1421 Name.getAsQualifiedTemplateName()->getDecl(),
1422 Loc, TU));
1423
1424 case TemplateName::SubstTemplateTemplateParm:
1425 return Visit(MakeCursorTemplateRef(
1426 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1427 Loc, TU));
1428
1429 case TemplateName::SubstTemplateTemplateParmPack:
1430 return Visit(MakeCursorTemplateRef(
1431 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1432 Loc, TU));
1433 }
1434
1435 llvm_unreachable("Invalid TemplateName::Kind!");
1436}
1437
1438bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1439 switch (TAL.getArgument().getKind()) {
1440 case TemplateArgument::Null:
1441 case TemplateArgument::Integral:
1442 case TemplateArgument::Pack:
1443 return false;
1444
1445 case TemplateArgument::Type:
1446 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1447 return Visit(TSInfo->getTypeLoc());
1448 return false;
1449
1450 case TemplateArgument::Declaration:
1451 if (Expr *E = TAL.getSourceDeclExpression())
1452 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1453 return false;
1454
1455 case TemplateArgument::NullPtr:
1456 if (Expr *E = TAL.getSourceNullPtrExpression())
1457 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1458 return false;
1459
1460 case TemplateArgument::Expression:
1461 if (Expr *E = TAL.getSourceExpression())
1462 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1463 return false;
1464
1465 case TemplateArgument::Template:
1466 case TemplateArgument::TemplateExpansion:
1467 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1468 return true;
1469
1470 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1471 TAL.getTemplateNameLoc());
1472 }
1473
1474 llvm_unreachable("Invalid TemplateArgument::Kind!");
1475}
1476
1477bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1478 return VisitDeclContext(D);
1479}
1480
1481bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1482 return Visit(TL.getUnqualifiedLoc());
1483}
1484
1485bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1486 ASTContext &Context = AU->getASTContext();
1487
1488 // Some builtin types (such as Objective-C's "id", "sel", and
1489 // "Class") have associated declarations. Create cursors for those.
1490 QualType VisitType;
1491 switch (TL.getTypePtr()->getKind()) {
1492
1493 case BuiltinType::Void:
1494 case BuiltinType::NullPtr:
1495 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001496#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1497 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001498#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001499 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001500 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001501 case BuiltinType::OCLClkEvent:
1502 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001503 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001504#define BUILTIN_TYPE(Id, SingletonId)
1505#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1506#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1507#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1508#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1509#include "clang/AST/BuiltinTypes.def"
1510 break;
1511
1512 case BuiltinType::ObjCId:
1513 VisitType = Context.getObjCIdType();
1514 break;
1515
1516 case BuiltinType::ObjCClass:
1517 VisitType = Context.getObjCClassType();
1518 break;
1519
1520 case BuiltinType::ObjCSel:
1521 VisitType = Context.getObjCSelType();
1522 break;
1523 }
1524
1525 if (!VisitType.isNull()) {
1526 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1527 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1528 TU));
1529 }
1530
1531 return false;
1532}
1533
1534bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1535 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1536}
1537
1538bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1539 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1540}
1541
1542bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1543 if (TL.isDefinition())
1544 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1545
1546 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1547}
1548
1549bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1550 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1551}
1552
1553bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001554 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001555}
1556
Manman Rene6be26c2016-09-13 17:25:08 +00001557bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1558 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getLocStart(), TU)))
1559 return true;
1560 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1561 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1562 TU)))
1563 return true;
1564 }
1565
1566 return false;
1567}
1568
Guy Benyei11169dd2012-12-18 14:30:41 +00001569bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1570 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1571 return true;
1572
Douglas Gregore9d95f12015-07-07 03:57:35 +00001573 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1574 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1575 return true;
1576 }
1577
Guy Benyei11169dd2012-12-18 14:30:41 +00001578 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1579 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1580 TU)))
1581 return true;
1582 }
1583
1584 return false;
1585}
1586
1587bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1588 return Visit(TL.getPointeeLoc());
1589}
1590
1591bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1592 return Visit(TL.getInnerLoc());
1593}
1594
1595bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1596 return Visit(TL.getPointeeLoc());
1597}
1598
1599bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1600 return Visit(TL.getPointeeLoc());
1601}
1602
1603bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1604 return Visit(TL.getPointeeLoc());
1605}
1606
1607bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1608 return Visit(TL.getPointeeLoc());
1609}
1610
1611bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1612 return Visit(TL.getPointeeLoc());
1613}
1614
1615bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1616 return Visit(TL.getModifiedLoc());
1617}
1618
1619bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1620 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001621 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001622 return true;
1623
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001624 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1625 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1627 return true;
1628
1629 return false;
1630}
1631
1632bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1633 if (Visit(TL.getElementLoc()))
1634 return true;
1635
1636 if (Expr *Size = TL.getSizeExpr())
1637 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1638
1639 return false;
1640}
1641
Reid Kleckner8a365022013-06-24 17:51:48 +00001642bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1643 return Visit(TL.getOriginalLoc());
1644}
1645
Reid Kleckner0503a872013-12-05 01:23:43 +00001646bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1647 return Visit(TL.getOriginalLoc());
1648}
1649
Richard Smith600b5262017-01-26 20:40:47 +00001650bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1651 DeducedTemplateSpecializationTypeLoc TL) {
1652 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1653 TL.getTemplateNameLoc()))
1654 return true;
1655
1656 return false;
1657}
1658
Guy Benyei11169dd2012-12-18 14:30:41 +00001659bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1660 TemplateSpecializationTypeLoc TL) {
1661 // Visit the template name.
1662 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1663 TL.getTemplateNameLoc()))
1664 return true;
1665
1666 // Visit the template arguments.
1667 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1668 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1669 return true;
1670
1671 return false;
1672}
1673
1674bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1675 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1676}
1677
1678bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1679 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1680 return Visit(TSInfo->getTypeLoc());
1681
1682 return false;
1683}
1684
1685bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1686 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1687 return Visit(TSInfo->getTypeLoc());
1688
1689 return false;
1690}
1691
1692bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001693 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001694}
1695
1696bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1697 DependentTemplateSpecializationTypeLoc TL) {
1698 // Visit the nested-name-specifier, if there is one.
1699 if (TL.getQualifierLoc() &&
1700 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1701 return true;
1702
1703 // Visit the template arguments.
1704 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1705 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1706 return true;
1707
1708 return false;
1709}
1710
1711bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1712 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1713 return true;
1714
1715 return Visit(TL.getNamedTypeLoc());
1716}
1717
1718bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1719 return Visit(TL.getPatternLoc());
1720}
1721
1722bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1723 if (Expr *E = TL.getUnderlyingExpr())
1724 return Visit(MakeCXCursor(E, StmtParent, TU));
1725
1726 return false;
1727}
1728
1729bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1730 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1731}
1732
1733bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1734 return Visit(TL.getValueLoc());
1735}
1736
Xiuli Pan9c14e282016-01-09 12:53:17 +00001737bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1738 return Visit(TL.getValueLoc());
1739}
1740
Guy Benyei11169dd2012-12-18 14:30:41 +00001741#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1742bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1743 return Visit##PARENT##Loc(TL); \
1744}
1745
1746DEFAULT_TYPELOC_IMPL(Complex, Type)
1747DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1748DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1749DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1750DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001751DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001752DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1753DEFAULT_TYPELOC_IMPL(Vector, Type)
1754DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1755DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1756DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1757DEFAULT_TYPELOC_IMPL(Record, TagType)
1758DEFAULT_TYPELOC_IMPL(Enum, TagType)
1759DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1760DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1761DEFAULT_TYPELOC_IMPL(Auto, Type)
1762
1763bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1764 // Visit the nested-name-specifier, if present.
1765 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1766 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1767 return true;
1768
1769 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001770 for (const auto &I : D->bases()) {
1771 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001772 return true;
1773 }
1774 }
1775
1776 return VisitTagDecl(D);
1777}
1778
1779bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001780 for (const auto *I : D->attrs())
1781 if (Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001782 return true;
1783
1784 return false;
1785}
1786
1787//===----------------------------------------------------------------------===//
1788// Data-recursive visitor methods.
1789//===----------------------------------------------------------------------===//
1790
1791namespace {
1792#define DEF_JOB(NAME, DATA, KIND)\
1793class NAME : public VisitorJob {\
1794public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001795 NAME(const DATA *d, CXCursor parent) : \
1796 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001797 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001798 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001799};
1800
1801DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1802DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1803DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1804DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001805DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1806DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1807DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1808#undef DEF_JOB
1809
James Y Knight04ec5bf2015-12-24 02:59:37 +00001810class ExplicitTemplateArgsVisit : public VisitorJob {
1811public:
1812 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1813 const TemplateArgumentLoc *End, CXCursor parent)
1814 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1815 End) {}
1816 static bool classof(const VisitorJob *VJ) {
1817 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1818 }
1819 const TemplateArgumentLoc *begin() const {
1820 return static_cast<const TemplateArgumentLoc *>(data[0]);
1821 }
1822 const TemplateArgumentLoc *end() {
1823 return static_cast<const TemplateArgumentLoc *>(data[1]);
1824 }
1825};
Guy Benyei11169dd2012-12-18 14:30:41 +00001826class DeclVisit : public VisitorJob {
1827public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001828 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001829 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001830 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001831 static bool classof(const VisitorJob *VJ) {
1832 return VJ->getKind() == DeclVisitKind;
1833 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001834 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001835 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001836};
1837class TypeLocVisit : public VisitorJob {
1838public:
1839 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1840 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1841 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1842
1843 static bool classof(const VisitorJob *VJ) {
1844 return VJ->getKind() == TypeLocVisitKind;
1845 }
1846
1847 TypeLoc get() const {
1848 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001849 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001850 }
1851};
1852
1853class LabelRefVisit : public VisitorJob {
1854public:
1855 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1856 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1857 labelLoc.getPtrEncoding()) {}
1858
1859 static bool classof(const VisitorJob *VJ) {
1860 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1861 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001862 const LabelDecl *get() const {
1863 return static_cast<const LabelDecl *>(data[0]);
1864 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001865 SourceLocation getLoc() const {
1866 return SourceLocation::getFromPtrEncoding(data[1]); }
1867};
1868
1869class NestedNameSpecifierLocVisit : public VisitorJob {
1870public:
1871 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1872 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1873 Qualifier.getNestedNameSpecifier(),
1874 Qualifier.getOpaqueData()) { }
1875
1876 static bool classof(const VisitorJob *VJ) {
1877 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1878 }
1879
1880 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001881 return NestedNameSpecifierLoc(
1882 const_cast<NestedNameSpecifier *>(
1883 static_cast<const NestedNameSpecifier *>(data[0])),
1884 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001885 }
1886};
1887
1888class DeclarationNameInfoVisit : public VisitorJob {
1889public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001890 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001891 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001892 static bool classof(const VisitorJob *VJ) {
1893 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1894 }
1895 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001896 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001897 switch (S->getStmtClass()) {
1898 default:
1899 llvm_unreachable("Unhandled Stmt");
1900 case clang::Stmt::MSDependentExistsStmtClass:
1901 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1902 case Stmt::CXXDependentScopeMemberExprClass:
1903 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1904 case Stmt::DependentScopeDeclRefExprClass:
1905 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001906 case Stmt::OMPCriticalDirectiveClass:
1907 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001908 }
1909 }
1910};
1911class MemberRefVisit : public VisitorJob {
1912public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001913 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001914 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1915 L.getPtrEncoding()) {}
1916 static bool classof(const VisitorJob *VJ) {
1917 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1918 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001919 const FieldDecl *get() const {
1920 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 }
1922 SourceLocation getLoc() const {
1923 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1924 }
1925};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001926class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001927 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001928 VisitorWorkList &WL;
1929 CXCursor Parent;
1930public:
1931 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1932 : WL(wl), Parent(parent) {}
1933
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001934 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1935 void VisitBlockExpr(const BlockExpr *B);
1936 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1937 void VisitCompoundStmt(const CompoundStmt *S);
1938 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1939 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1940 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1941 void VisitCXXNewExpr(const CXXNewExpr *E);
1942 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1943 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1944 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1945 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1946 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1947 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1948 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1949 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001950 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001951 void VisitDeclRefExpr(const DeclRefExpr *D);
1952 void VisitDeclStmt(const DeclStmt *S);
1953 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1954 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1955 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1956 void VisitForStmt(const ForStmt *FS);
1957 void VisitGotoStmt(const GotoStmt *GS);
1958 void VisitIfStmt(const IfStmt *If);
1959 void VisitInitListExpr(const InitListExpr *IE);
1960 void VisitMemberExpr(const MemberExpr *M);
1961 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1962 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1963 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1964 void VisitOverloadExpr(const OverloadExpr *E);
1965 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1966 void VisitStmt(const Stmt *S);
1967 void VisitSwitchStmt(const SwitchStmt *S);
1968 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001969 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1970 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1971 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1972 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1973 void VisitVAArgExpr(const VAArgExpr *E);
1974 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1975 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1976 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1977 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001978 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00001979 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001980 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001981 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001982 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00001983 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001984 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001985 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001986 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00001987 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001988 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001989 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001990 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001991 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001992 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00001993 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001994 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00001995 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001996 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001997 void
1998 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00001999 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002000 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002001 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002002 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002003 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002004 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002005 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002006 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002007 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002008 void
2009 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002010 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002011 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002012 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002013 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002014 void VisitOMPDistributeParallelForDirective(
2015 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002016 void VisitOMPDistributeParallelForSimdDirective(
2017 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002018 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002019 void VisitOMPTargetParallelForSimdDirective(
2020 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002021 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002022 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002023 void VisitOMPTeamsDistributeSimdDirective(
2024 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002025 void VisitOMPTeamsDistributeParallelForSimdDirective(
2026 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002027 void VisitOMPTeamsDistributeParallelForDirective(
2028 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002029 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002030 void VisitOMPTargetTeamsDistributeDirective(
2031 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002032 void VisitOMPTargetTeamsDistributeParallelForDirective(
2033 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002034 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2035 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002036 void VisitOMPTargetTeamsDistributeSimdDirective(
2037 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002038
Guy Benyei11169dd2012-12-18 14:30:41 +00002039private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002040 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002041 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002042 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2043 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002044 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2045 void AddStmt(const Stmt *S);
2046 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002047 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002048 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002049 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002050};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002051} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002052
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002053void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002054 // 'S' should always be non-null, since it comes from the
2055 // statement we are visiting.
2056 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2057}
2058
2059void
2060EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2061 if (Qualifier)
2062 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2063}
2064
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002065void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002066 if (S)
2067 WL.push_back(StmtVisit(S, Parent));
2068}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002069void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002070 if (D)
2071 WL.push_back(DeclVisit(D, Parent, isFirst));
2072}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002073void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2074 unsigned NumTemplateArgs) {
2075 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002076}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002077void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002078 if (D)
2079 WL.push_back(MemberRefVisit(D, L, Parent));
2080}
2081void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2082 if (TI)
2083 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2084 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002085void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002086 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002087 for (const Stmt *SubStmt : S->children()) {
2088 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002089 }
2090 if (size == WL.size())
2091 return;
2092 // Now reverse the entries we just added. This will match the DFS
2093 // ordering performed by the worklist.
2094 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2095 std::reverse(I, E);
2096}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002097namespace {
2098class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2099 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002100 /// \brief Process clauses with list of variables.
2101 template <typename T>
2102 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002103public:
2104 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2105#define OPENMP_CLAUSE(Name, Class) \
2106 void Visit##Class(const Class *C);
2107#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002108 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002109 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002110};
2111
Alexey Bataev3392d762016-02-16 11:18:12 +00002112void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2113 const OMPClauseWithPreInit *C) {
2114 Visitor->AddStmt(C->getPreInitStmt());
2115}
2116
Alexey Bataev005248a2016-02-25 05:25:57 +00002117void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2118 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002119 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002120 Visitor->AddStmt(C->getPostUpdateExpr());
2121}
2122
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002123void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002124 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002125 Visitor->AddStmt(C->getCondition());
2126}
2127
Alexey Bataev3778b602014-07-17 07:32:53 +00002128void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2129 Visitor->AddStmt(C->getCondition());
2130}
2131
Alexey Bataev568a8332014-03-06 06:15:19 +00002132void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002133 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002134 Visitor->AddStmt(C->getNumThreads());
2135}
2136
Alexey Bataev62c87d22014-03-21 04:51:18 +00002137void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2138 Visitor->AddStmt(C->getSafelen());
2139}
2140
Alexey Bataev66b15b52015-08-21 11:14:16 +00002141void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2142 Visitor->AddStmt(C->getSimdlen());
2143}
2144
Alexander Musman8bd31e62014-05-27 15:12:19 +00002145void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2146 Visitor->AddStmt(C->getNumForLoops());
2147}
2148
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002149void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002150
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002151void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2152
Alexey Bataev56dafe82014-06-20 07:16:17 +00002153void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002154 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002155 Visitor->AddStmt(C->getChunkSize());
2156}
2157
Alexey Bataev10e775f2015-07-30 11:36:16 +00002158void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2159 Visitor->AddStmt(C->getNumForLoops());
2160}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002161
Alexey Bataev236070f2014-06-20 11:19:47 +00002162void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2163
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002164void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2165
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002166void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2167
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002168void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2169
Alexey Bataevdea47612014-07-23 07:46:59 +00002170void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2171
Alexey Bataev67a4f222014-07-23 10:25:33 +00002172void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2173
Alexey Bataev459dec02014-07-24 06:46:57 +00002174void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2175
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002176void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2177
Alexey Bataev346265e2015-09-25 10:37:12 +00002178void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2179
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002180void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2181
Alexey Bataevb825de12015-12-07 10:51:44 +00002182void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2183
Michael Wonge710d542015-08-07 16:16:36 +00002184void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2185 Visitor->AddStmt(C->getDevice());
2186}
2187
Kelvin Li099bb8c2015-11-24 20:50:12 +00002188void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002189 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002190 Visitor->AddStmt(C->getNumTeams());
2191}
2192
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002193void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002194 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002195 Visitor->AddStmt(C->getThreadLimit());
2196}
2197
Alexey Bataeva0569352015-12-01 10:17:31 +00002198void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2199 Visitor->AddStmt(C->getPriority());
2200}
2201
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002202void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2203 Visitor->AddStmt(C->getGrainsize());
2204}
2205
Alexey Bataev382967a2015-12-08 12:06:20 +00002206void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2207 Visitor->AddStmt(C->getNumTasks());
2208}
2209
Alexey Bataev28c75412015-12-15 08:19:24 +00002210void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2211 Visitor->AddStmt(C->getHint());
2212}
2213
Alexey Bataev756c1962013-09-24 03:17:45 +00002214template<typename T>
2215void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002216 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002217 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002218 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002219}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002220
2221void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002222 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002223 for (const auto *E : C->private_copies()) {
2224 Visitor->AddStmt(E);
2225 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002226}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002227void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2228 const OMPFirstprivateClause *C) {
2229 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002230 VisitOMPClauseWithPreInit(C);
2231 for (const auto *E : C->private_copies()) {
2232 Visitor->AddStmt(E);
2233 }
2234 for (const auto *E : C->inits()) {
2235 Visitor->AddStmt(E);
2236 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002237}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002238void OMPClauseEnqueue::VisitOMPLastprivateClause(
2239 const OMPLastprivateClause *C) {
2240 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002241 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002242 for (auto *E : C->private_copies()) {
2243 Visitor->AddStmt(E);
2244 }
2245 for (auto *E : C->source_exprs()) {
2246 Visitor->AddStmt(E);
2247 }
2248 for (auto *E : C->destination_exprs()) {
2249 Visitor->AddStmt(E);
2250 }
2251 for (auto *E : C->assignment_ops()) {
2252 Visitor->AddStmt(E);
2253 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002254}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002255void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002256 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002257}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002258void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2259 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002260 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002261 for (auto *E : C->privates()) {
2262 Visitor->AddStmt(E);
2263 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002264 for (auto *E : C->lhs_exprs()) {
2265 Visitor->AddStmt(E);
2266 }
2267 for (auto *E : C->rhs_exprs()) {
2268 Visitor->AddStmt(E);
2269 }
2270 for (auto *E : C->reduction_ops()) {
2271 Visitor->AddStmt(E);
2272 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002273}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002274void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2275 const OMPTaskReductionClause *C) {
2276 VisitOMPClauseList(C);
2277 VisitOMPClauseWithPostUpdate(C);
2278 for (auto *E : C->privates()) {
2279 Visitor->AddStmt(E);
2280 }
2281 for (auto *E : C->lhs_exprs()) {
2282 Visitor->AddStmt(E);
2283 }
2284 for (auto *E : C->rhs_exprs()) {
2285 Visitor->AddStmt(E);
2286 }
2287 for (auto *E : C->reduction_ops()) {
2288 Visitor->AddStmt(E);
2289 }
2290}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002291void OMPClauseEnqueue::VisitOMPInReductionClause(
2292 const OMPInReductionClause *C) {
2293 VisitOMPClauseList(C);
2294 VisitOMPClauseWithPostUpdate(C);
2295 for (auto *E : C->privates()) {
2296 Visitor->AddStmt(E);
2297 }
2298 for (auto *E : C->lhs_exprs()) {
2299 Visitor->AddStmt(E);
2300 }
2301 for (auto *E : C->rhs_exprs()) {
2302 Visitor->AddStmt(E);
2303 }
2304 for (auto *E : C->reduction_ops()) {
2305 Visitor->AddStmt(E);
2306 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002307 for (auto *E : C->taskgroup_descriptors())
2308 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002309}
Alexander Musman8dba6642014-04-22 13:09:42 +00002310void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2311 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002312 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002313 for (const auto *E : C->privates()) {
2314 Visitor->AddStmt(E);
2315 }
Alexander Musman3276a272015-03-21 10:12:56 +00002316 for (const auto *E : C->inits()) {
2317 Visitor->AddStmt(E);
2318 }
2319 for (const auto *E : C->updates()) {
2320 Visitor->AddStmt(E);
2321 }
2322 for (const auto *E : C->finals()) {
2323 Visitor->AddStmt(E);
2324 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002325 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002326 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002327}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002328void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2329 VisitOMPClauseList(C);
2330 Visitor->AddStmt(C->getAlignment());
2331}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002332void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2333 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002334 for (auto *E : C->source_exprs()) {
2335 Visitor->AddStmt(E);
2336 }
2337 for (auto *E : C->destination_exprs()) {
2338 Visitor->AddStmt(E);
2339 }
2340 for (auto *E : C->assignment_ops()) {
2341 Visitor->AddStmt(E);
2342 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002343}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002344void
2345OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2346 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002347 for (auto *E : C->source_exprs()) {
2348 Visitor->AddStmt(E);
2349 }
2350 for (auto *E : C->destination_exprs()) {
2351 Visitor->AddStmt(E);
2352 }
2353 for (auto *E : C->assignment_ops()) {
2354 Visitor->AddStmt(E);
2355 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002356}
Alexey Bataev6125da92014-07-21 11:26:11 +00002357void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2358 VisitOMPClauseList(C);
2359}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002360void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2361 VisitOMPClauseList(C);
2362}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002363void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2364 VisitOMPClauseList(C);
2365}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002366void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2367 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002368 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002369 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002370}
Alexey Bataev3392d762016-02-16 11:18:12 +00002371void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2372 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002373void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2374 VisitOMPClauseList(C);
2375}
Samuel Antaoec172c62016-05-26 17:49:04 +00002376void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2377 VisitOMPClauseList(C);
2378}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002379void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2380 VisitOMPClauseList(C);
2381}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002382void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2383 VisitOMPClauseList(C);
2384}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002385}
Alexey Bataev756c1962013-09-24 03:17:45 +00002386
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002387void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2388 unsigned size = WL.size();
2389 OMPClauseEnqueue Visitor(this);
2390 Visitor.Visit(S);
2391 if (size == WL.size())
2392 return;
2393 // Now reverse the entries we just added. This will match the DFS
2394 // ordering performed by the worklist.
2395 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2396 std::reverse(I, E);
2397}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002398void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002399 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2400}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002401void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 AddDecl(B->getBlockDecl());
2403}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002404void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 EnqueueChildren(E);
2406 AddTypeLoc(E->getTypeSourceInfo());
2407}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002408void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002409 for (auto &I : llvm::reverse(S->body()))
2410 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002411}
2412void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002413VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 AddStmt(S->getSubStmt());
2415 AddDeclarationNameInfo(S);
2416 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2417 AddNestedNameSpecifierLoc(QualifierLoc);
2418}
2419
2420void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002421VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002422 if (E->hasExplicitTemplateArgs())
2423 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 AddDeclarationNameInfo(E);
2425 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2426 AddNestedNameSpecifierLoc(QualifierLoc);
2427 if (!E->isImplicitAccess())
2428 AddStmt(E->getBase());
2429}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002430void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 // Enqueue the initializer , if any.
2432 AddStmt(E->getInitializer());
2433 // Enqueue the array size, if any.
2434 AddStmt(E->getArraySize());
2435 // Enqueue the allocated type.
2436 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2437 // Enqueue the placement arguments.
2438 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2439 AddStmt(E->getPlacementArg(I-1));
2440}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002441void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2443 AddStmt(CE->getArg(I-1));
2444 AddStmt(CE->getCallee());
2445 AddStmt(CE->getArg(0));
2446}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002447void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2448 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 // Visit the name of the type being destroyed.
2450 AddTypeLoc(E->getDestroyedTypeInfo());
2451 // Visit the scope type that looks disturbingly like the nested-name-specifier
2452 // but isn't.
2453 AddTypeLoc(E->getScopeTypeInfo());
2454 // Visit the nested-name-specifier.
2455 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2456 AddNestedNameSpecifierLoc(QualifierLoc);
2457 // Visit base expression.
2458 AddStmt(E->getBase());
2459}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002460void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2461 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 AddTypeLoc(E->getTypeSourceInfo());
2463}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002464void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2465 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 EnqueueChildren(E);
2467 AddTypeLoc(E->getTypeSourceInfo());
2468}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002469void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 EnqueueChildren(E);
2471 if (E->isTypeOperand())
2472 AddTypeLoc(E->getTypeOperandSourceInfo());
2473}
2474
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002475void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2476 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 EnqueueChildren(E);
2478 AddTypeLoc(E->getTypeSourceInfo());
2479}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002480void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 EnqueueChildren(E);
2482 if (E->isTypeOperand())
2483 AddTypeLoc(E->getTypeOperandSourceInfo());
2484}
2485
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002486void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 EnqueueChildren(S);
2488 AddDecl(S->getExceptionDecl());
2489}
2490
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002491void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002492 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002493 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002494 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002495}
2496
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002497void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002498 if (DR->hasExplicitTemplateArgs())
2499 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 WL.push_back(DeclRefExprParts(DR, Parent));
2501}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2503 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002504 if (E->hasExplicitTemplateArgs())
2505 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 AddDeclarationNameInfo(E);
2507 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2508}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002509void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 unsigned size = WL.size();
2511 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002512 for (const auto *D : S->decls()) {
2513 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 isFirst = false;
2515 }
2516 if (size == WL.size())
2517 return;
2518 // Now reverse the entries we just added. This will match the DFS
2519 // ordering performed by the worklist.
2520 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2521 std::reverse(I, E);
2522}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002523void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002525 for (const DesignatedInitExpr::Designator &D :
2526 llvm::reverse(E->designators())) {
2527 if (D.isFieldDesignator()) {
2528 if (FieldDecl *Field = D.getField())
2529 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 continue;
2531 }
David Majnemerf7e36092016-06-23 00:15:04 +00002532 if (D.isArrayDesignator()) {
2533 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 continue;
2535 }
David Majnemerf7e36092016-06-23 00:15:04 +00002536 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2537 AddStmt(E->getArrayRangeEnd(D));
2538 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 }
2540}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002541void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 EnqueueChildren(E);
2543 AddTypeLoc(E->getTypeInfoAsWritten());
2544}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002545void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 AddStmt(FS->getBody());
2547 AddStmt(FS->getInc());
2548 AddStmt(FS->getCond());
2549 AddDecl(FS->getConditionVariable());
2550 AddStmt(FS->getInit());
2551}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002552void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2554}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002555void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 AddStmt(If->getElse());
2557 AddStmt(If->getThen());
2558 AddStmt(If->getCond());
2559 AddDecl(If->getConditionVariable());
2560}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002561void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 // We care about the syntactic form of the initializer list, only.
2563 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2564 IE = Syntactic;
2565 EnqueueChildren(IE);
2566}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002567void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 WL.push_back(MemberExprParts(M, Parent));
2569
2570 // If the base of the member access expression is an implicit 'this', don't
2571 // visit it.
2572 // FIXME: If we ever want to show these implicit accesses, this will be
2573 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002574 if (M->isImplicitAccess())
2575 return;
2576
2577 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2578 // real field that that we are interested in.
2579 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2580 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2581 if (FD->isAnonymousStructOrUnion()) {
2582 AddStmt(SubME->getBase());
2583 return;
2584 }
2585 }
2586 }
2587
2588 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002589}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002590void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 AddTypeLoc(E->getEncodedTypeSourceInfo());
2592}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002593void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 EnqueueChildren(M);
2595 AddTypeLoc(M->getClassReceiverTypeInfo());
2596}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002597void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 // Visit the components of the offsetof expression.
2599 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 const OffsetOfNode &Node = E->getComponent(I-1);
2601 switch (Node.getKind()) {
2602 case OffsetOfNode::Array:
2603 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2604 break;
2605 case OffsetOfNode::Field:
2606 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2607 break;
2608 case OffsetOfNode::Identifier:
2609 case OffsetOfNode::Base:
2610 continue;
2611 }
2612 }
2613 // Visit the type into which we're computing the offset.
2614 AddTypeLoc(E->getTypeSourceInfo());
2615}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002616void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002617 if (E->hasExplicitTemplateArgs())
2618 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 WL.push_back(OverloadExprParts(E, Parent));
2620}
2621void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002622 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 EnqueueChildren(E);
2624 if (E->isArgumentType())
2625 AddTypeLoc(E->getArgumentTypeInfo());
2626}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002627void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 EnqueueChildren(S);
2629}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002630void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 AddStmt(S->getBody());
2632 AddStmt(S->getCond());
2633 AddDecl(S->getConditionVariable());
2634}
2635
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002636void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 AddStmt(W->getBody());
2638 AddStmt(W->getCond());
2639 AddDecl(W->getConditionVariable());
2640}
2641
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002642void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 for (unsigned I = E->getNumArgs(); I > 0; --I)
2644 AddTypeLoc(E->getArg(I-1));
2645}
2646
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002647void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002648 AddTypeLoc(E->getQueriedTypeSourceInfo());
2649}
2650
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002651void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 EnqueueChildren(E);
2653}
2654
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002655void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 VisitOverloadExpr(U);
2657 if (!U->isImplicitAccess())
2658 AddStmt(U->getBase());
2659}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002660void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 AddStmt(E->getSubExpr());
2662 AddTypeLoc(E->getWrittenTypeInfo());
2663}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002664void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 WL.push_back(SizeOfPackExprParts(E, Parent));
2666}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002667void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 // If the opaque value has a source expression, just transparently
2669 // visit that. This is useful for (e.g.) pseudo-object expressions.
2670 if (Expr *SourceExpr = E->getSourceExpr())
2671 return Visit(SourceExpr);
2672}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002673void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 AddStmt(E->getBody());
2675 WL.push_back(LambdaExprParts(E, Parent));
2676}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002677void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 // Treat the expression like its syntactic form.
2679 Visit(E->getSyntacticForm());
2680}
2681
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002682void EnqueueVisitor::VisitOMPExecutableDirective(
2683 const OMPExecutableDirective *D) {
2684 EnqueueChildren(D);
2685 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2686 E = D->clauses().end();
2687 I != E; ++I)
2688 EnqueueChildren(*I);
2689}
2690
Alexander Musman3aaab662014-08-19 11:27:13 +00002691void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2692 VisitOMPExecutableDirective(D);
2693}
2694
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002695void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2696 VisitOMPExecutableDirective(D);
2697}
2698
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002699void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002700 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002701}
2702
Alexey Bataevf29276e2014-06-18 04:14:57 +00002703void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002704 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002705}
2706
Alexander Musmanf82886e2014-09-18 05:12:34 +00002707void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2708 VisitOMPLoopDirective(D);
2709}
2710
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002711void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2712 VisitOMPExecutableDirective(D);
2713}
2714
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002715void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2716 VisitOMPExecutableDirective(D);
2717}
2718
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002719void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2720 VisitOMPExecutableDirective(D);
2721}
2722
Alexander Musman80c22892014-07-17 08:54:58 +00002723void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2724 VisitOMPExecutableDirective(D);
2725}
2726
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002727void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2728 VisitOMPExecutableDirective(D);
2729 AddDeclarationNameInfo(D);
2730}
2731
Alexey Bataev4acb8592014-07-07 13:01:15 +00002732void
2733EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002734 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002735}
2736
Alexander Musmane4e893b2014-09-23 09:33:00 +00002737void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2738 const OMPParallelForSimdDirective *D) {
2739 VisitOMPLoopDirective(D);
2740}
2741
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002742void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2743 const OMPParallelSectionsDirective *D) {
2744 VisitOMPExecutableDirective(D);
2745}
2746
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002747void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2748 VisitOMPExecutableDirective(D);
2749}
2750
Alexey Bataev68446b72014-07-18 07:47:19 +00002751void
2752EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2753 VisitOMPExecutableDirective(D);
2754}
2755
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002756void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2757 VisitOMPExecutableDirective(D);
2758}
2759
Alexey Bataev2df347a2014-07-18 10:17:07 +00002760void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2761 VisitOMPExecutableDirective(D);
2762}
2763
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002764void EnqueueVisitor::VisitOMPTaskgroupDirective(
2765 const OMPTaskgroupDirective *D) {
2766 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002767 if (const Expr *E = D->getReductionRef())
2768 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002769}
2770
Alexey Bataev6125da92014-07-21 11:26:11 +00002771void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2772 VisitOMPExecutableDirective(D);
2773}
2774
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002775void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2776 VisitOMPExecutableDirective(D);
2777}
2778
Alexey Bataev0162e452014-07-22 10:10:35 +00002779void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2780 VisitOMPExecutableDirective(D);
2781}
2782
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002783void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2784 VisitOMPExecutableDirective(D);
2785}
2786
Michael Wong65f367f2015-07-21 13:44:28 +00002787void EnqueueVisitor::VisitOMPTargetDataDirective(const
2788 OMPTargetDataDirective *D) {
2789 VisitOMPExecutableDirective(D);
2790}
2791
Samuel Antaodf67fc42016-01-19 19:15:56 +00002792void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2793 const OMPTargetEnterDataDirective *D) {
2794 VisitOMPExecutableDirective(D);
2795}
2796
Samuel Antao72590762016-01-19 20:04:50 +00002797void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2798 const OMPTargetExitDataDirective *D) {
2799 VisitOMPExecutableDirective(D);
2800}
2801
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002802void EnqueueVisitor::VisitOMPTargetParallelDirective(
2803 const OMPTargetParallelDirective *D) {
2804 VisitOMPExecutableDirective(D);
2805}
2806
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002807void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2808 const OMPTargetParallelForDirective *D) {
2809 VisitOMPLoopDirective(D);
2810}
2811
Alexey Bataev13314bf2014-10-09 04:18:56 +00002812void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2813 VisitOMPExecutableDirective(D);
2814}
2815
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002816void EnqueueVisitor::VisitOMPCancellationPointDirective(
2817 const OMPCancellationPointDirective *D) {
2818 VisitOMPExecutableDirective(D);
2819}
2820
Alexey Bataev80909872015-07-02 11:25:17 +00002821void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2822 VisitOMPExecutableDirective(D);
2823}
2824
Alexey Bataev49f6e782015-12-01 04:18:41 +00002825void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2826 VisitOMPLoopDirective(D);
2827}
2828
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002829void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2830 const OMPTaskLoopSimdDirective *D) {
2831 VisitOMPLoopDirective(D);
2832}
2833
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002834void EnqueueVisitor::VisitOMPDistributeDirective(
2835 const OMPDistributeDirective *D) {
2836 VisitOMPLoopDirective(D);
2837}
2838
Carlo Bertolli9925f152016-06-27 14:55:37 +00002839void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2840 const OMPDistributeParallelForDirective *D) {
2841 VisitOMPLoopDirective(D);
2842}
2843
Kelvin Li4a39add2016-07-05 05:00:15 +00002844void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2845 const OMPDistributeParallelForSimdDirective *D) {
2846 VisitOMPLoopDirective(D);
2847}
2848
Kelvin Li787f3fc2016-07-06 04:45:38 +00002849void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2850 const OMPDistributeSimdDirective *D) {
2851 VisitOMPLoopDirective(D);
2852}
2853
Kelvin Lia579b912016-07-14 02:54:56 +00002854void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2855 const OMPTargetParallelForSimdDirective *D) {
2856 VisitOMPLoopDirective(D);
2857}
2858
Kelvin Li986330c2016-07-20 22:57:10 +00002859void EnqueueVisitor::VisitOMPTargetSimdDirective(
2860 const OMPTargetSimdDirective *D) {
2861 VisitOMPLoopDirective(D);
2862}
2863
Kelvin Li02532872016-08-05 14:37:37 +00002864void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2865 const OMPTeamsDistributeDirective *D) {
2866 VisitOMPLoopDirective(D);
2867}
2868
Kelvin Li4e325f72016-10-25 12:50:55 +00002869void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2870 const OMPTeamsDistributeSimdDirective *D) {
2871 VisitOMPLoopDirective(D);
2872}
2873
Kelvin Li579e41c2016-11-30 23:51:03 +00002874void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2875 const OMPTeamsDistributeParallelForSimdDirective *D) {
2876 VisitOMPLoopDirective(D);
2877}
2878
Kelvin Li7ade93f2016-12-09 03:24:30 +00002879void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2880 const OMPTeamsDistributeParallelForDirective *D) {
2881 VisitOMPLoopDirective(D);
2882}
2883
Kelvin Libf594a52016-12-17 05:48:59 +00002884void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2885 const OMPTargetTeamsDirective *D) {
2886 VisitOMPExecutableDirective(D);
2887}
2888
Kelvin Li83c451e2016-12-25 04:52:54 +00002889void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2890 const OMPTargetTeamsDistributeDirective *D) {
2891 VisitOMPLoopDirective(D);
2892}
2893
Kelvin Li80e8f562016-12-29 22:16:30 +00002894void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2895 const OMPTargetTeamsDistributeParallelForDirective *D) {
2896 VisitOMPLoopDirective(D);
2897}
2898
Kelvin Li1851df52017-01-03 05:23:48 +00002899void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2900 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2901 VisitOMPLoopDirective(D);
2902}
2903
Kelvin Lida681182017-01-10 18:08:18 +00002904void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2905 const OMPTargetTeamsDistributeSimdDirective *D) {
2906 VisitOMPLoopDirective(D);
2907}
2908
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002909void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2911}
2912
2913bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2914 if (RegionOfInterest.isValid()) {
2915 SourceRange Range = getRawCursorExtent(C);
2916 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2917 return false;
2918 }
2919 return true;
2920}
2921
2922bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2923 while (!WL.empty()) {
2924 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002925 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002926
2927 // Set the Parent field, then back to its old value once we're done.
2928 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2929
2930 switch (LI.getKind()) {
2931 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002932 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 if (!D)
2934 continue;
2935
2936 // For now, perform default visitation for Decls.
2937 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2938 cast<DeclVisit>(&LI)->isFirst())))
2939 return true;
2940
2941 continue;
2942 }
2943 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002944 for (const TemplateArgumentLoc &Arg :
2945 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2946 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002947 return true;
2948 }
2949 continue;
2950 }
2951 case VisitorJob::TypeLocVisitKind: {
2952 // Perform default visitation for TypeLocs.
2953 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2954 return true;
2955 continue;
2956 }
2957 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002958 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 if (LabelStmt *stmt = LS->getStmt()) {
2960 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2961 TU))) {
2962 return true;
2963 }
2964 }
2965 continue;
2966 }
2967
2968 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2969 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2970 if (VisitNestedNameSpecifierLoc(V->get()))
2971 return true;
2972 continue;
2973 }
2974
2975 case VisitorJob::DeclarationNameInfoVisitKind: {
2976 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2977 ->get()))
2978 return true;
2979 continue;
2980 }
2981 case VisitorJob::MemberRefVisitKind: {
2982 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2983 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2984 return true;
2985 continue;
2986 }
2987 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002988 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 if (!S)
2990 continue;
2991
2992 // Update the current cursor.
2993 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2994 if (!IsInRegionOfInterest(Cursor))
2995 continue;
2996 switch (Visitor(Cursor, Parent, ClientData)) {
2997 case CXChildVisit_Break: return true;
2998 case CXChildVisit_Continue: break;
2999 case CXChildVisit_Recurse:
3000 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003001 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 EnqueueWorkList(WL, S);
3003 break;
3004 }
3005 continue;
3006 }
3007 case VisitorJob::MemberExprPartsKind: {
3008 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003009 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003010
3011 // Visit the nested-name-specifier
3012 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3013 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3014 return true;
3015
3016 // Visit the declaration name.
3017 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3018 return true;
3019
3020 // Visit the explicitly-specified template arguments, if any.
3021 if (M->hasExplicitTemplateArgs()) {
3022 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3023 *ArgEnd = Arg + M->getNumTemplateArgs();
3024 Arg != ArgEnd; ++Arg) {
3025 if (VisitTemplateArgumentLoc(*Arg))
3026 return true;
3027 }
3028 }
3029 continue;
3030 }
3031 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003032 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 // Visit nested-name-specifier, if present.
3034 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3035 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3036 return true;
3037 // Visit declaration name.
3038 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3039 return true;
3040 continue;
3041 }
3042 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003043 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003044 // Visit the nested-name-specifier.
3045 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3046 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3047 return true;
3048 // Visit the declaration name.
3049 if (VisitDeclarationNameInfo(O->getNameInfo()))
3050 return true;
3051 // Visit the overloaded declaration reference.
3052 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3053 return true;
3054 continue;
3055 }
3056 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003057 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 NamedDecl *Pack = E->getPack();
3059 if (isa<TemplateTypeParmDecl>(Pack)) {
3060 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3061 E->getPackLoc(), TU)))
3062 return true;
3063
3064 continue;
3065 }
3066
3067 if (isa<TemplateTemplateParmDecl>(Pack)) {
3068 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3069 E->getPackLoc(), TU)))
3070 return true;
3071
3072 continue;
3073 }
3074
3075 // Non-type template parameter packs and function parameter packs are
3076 // treated like DeclRefExpr cursors.
3077 continue;
3078 }
3079
3080 case VisitorJob::LambdaExprPartsKind: {
3081 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003082 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3084 CEnd = E->explicit_capture_end();
3085 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003086 // FIXME: Lambda init-captures.
3087 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003089
Guy Benyei11169dd2012-12-18 14:30:41 +00003090 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3091 C->getLocation(),
3092 TU)))
3093 return true;
3094 }
3095
3096 // Visit parameters and return type, if present.
3097 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3098 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3099 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3100 // Visit the whole type.
3101 if (Visit(TL))
3102 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003103 } else if (FunctionProtoTypeLoc Proto =
3104 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003105 if (E->hasExplicitParameters()) {
3106 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003107 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3108 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 return true;
3110 } else {
3111 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003112 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 return true;
3114 }
3115 }
3116 }
3117 break;
3118 }
3119
3120 case VisitorJob::PostChildrenVisitKind:
3121 if (PostChildrenVisitor(Parent, ClientData))
3122 return true;
3123 break;
3124 }
3125 }
3126 return false;
3127}
3128
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003129bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003130 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 if (!WorkListFreeList.empty()) {
3132 WL = WorkListFreeList.back();
3133 WL->clear();
3134 WorkListFreeList.pop_back();
3135 }
3136 else {
3137 WL = new VisitorWorkList();
3138 WorkListCache.push_back(WL);
3139 }
3140 EnqueueWorkList(*WL, S);
3141 bool result = RunVisitorWorkList(*WL);
3142 WorkListFreeList.push_back(WL);
3143 return result;
3144}
3145
3146namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003147typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003148RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3149 const DeclarationNameInfo &NI, SourceRange QLoc,
3150 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3152 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3153 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3154
3155 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3156
3157 RefNamePieces Pieces;
3158
3159 if (WantQualifier && QLoc.isValid())
3160 Pieces.push_back(QLoc);
3161
3162 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3163 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003164
3165 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3166 Pieces.push_back(*TemplateArgsLoc);
3167
Guy Benyei11169dd2012-12-18 14:30:41 +00003168 if (Kind == DeclarationName::CXXOperatorName) {
3169 Pieces.push_back(SourceLocation::getFromRawEncoding(
3170 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3171 Pieces.push_back(SourceLocation::getFromRawEncoding(
3172 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3173 }
3174
3175 if (WantSinglePiece) {
3176 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3177 Pieces.clear();
3178 Pieces.push_back(R);
3179 }
3180
3181 return Pieces;
3182}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003183}
Guy Benyei11169dd2012-12-18 14:30:41 +00003184
3185//===----------------------------------------------------------------------===//
3186// Misc. API hooks.
3187//===----------------------------------------------------------------------===//
3188
Chad Rosier05c71aa2013-03-27 18:28:23 +00003189static void fatal_error_handler(void *user_data, const std::string& reason,
3190 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003191 // Write the result out to stderr avoiding errs() because raw_ostreams can
3192 // call report_fatal_error.
3193 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3194 ::abort();
3195}
3196
Chandler Carruth66660742014-06-27 16:37:27 +00003197namespace {
3198struct RegisterFatalErrorHandler {
3199 RegisterFatalErrorHandler() {
3200 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3201 }
3202};
3203}
3204
3205static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3206
Guy Benyei11169dd2012-12-18 14:30:41 +00003207CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3208 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003209 // We use crash recovery to make some of our APIs more reliable, implicitly
3210 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003211 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3212 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003213
Chandler Carruth66660742014-06-27 16:37:27 +00003214 // Look through the managed static to trigger construction of the managed
3215 // static which registers our fatal error handler. This ensures it is only
3216 // registered once.
3217 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003218
Adrian Prantlbc068582015-07-08 01:00:30 +00003219 // Initialize targets for clang module support.
3220 llvm::InitializeAllTargets();
3221 llvm::InitializeAllTargetMCs();
3222 llvm::InitializeAllAsmPrinters();
3223 llvm::InitializeAllAsmParsers();
3224
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003225 CIndexer *CIdxr = new CIndexer();
3226
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 if (excludeDeclarationsFromPCH)
3228 CIdxr->setOnlyLocalDecls();
3229 if (displayDiagnostics)
3230 CIdxr->setDisplayDiagnostics();
3231
3232 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3233 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3234 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3235 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3236 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3237 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3238
3239 return CIdxr;
3240}
3241
3242void clang_disposeIndex(CXIndex CIdx) {
3243 if (CIdx)
3244 delete static_cast<CIndexer *>(CIdx);
3245}
3246
3247void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3248 if (CIdx)
3249 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3250}
3251
3252unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3253 if (CIdx)
3254 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3255 return 0;
3256}
3257
Alex Lorenz08615792017-12-04 21:56:36 +00003258void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3259 const char *Path) {
3260 if (CIdx)
3261 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3262}
3263
Guy Benyei11169dd2012-12-18 14:30:41 +00003264void clang_toggleCrashRecovery(unsigned isEnabled) {
3265 if (isEnabled)
3266 llvm::CrashRecoveryContext::Enable();
3267 else
3268 llvm::CrashRecoveryContext::Disable();
3269}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003270
Guy Benyei11169dd2012-12-18 14:30:41 +00003271CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3272 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003273 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003274 enum CXErrorCode Result =
3275 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003276 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003277 assert((TU && Result == CXError_Success) ||
3278 (!TU && Result != CXError_Success));
3279 return TU;
3280}
3281
3282enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3283 const char *ast_filename,
3284 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003285 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003286 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003287
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003288 if (!CIdx || !ast_filename || !out_TU)
3289 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003290
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003291 LOG_FUNC_SECTION {
3292 *Log << ast_filename;
3293 }
3294
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3296 FileSystemOptions FileSystemOpts;
3297
Justin Bognerd512c1e2014-10-15 00:33:06 +00003298 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3299 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003300 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003301 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3302 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003303 FileSystemOpts, /*UseDebugInfo=*/false,
3304 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003305 /*CaptureDiagnostics=*/true,
3306 /*AllowPCHWithCompilerErrors=*/true,
3307 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003308 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003309 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003310}
3311
3312unsigned clang_defaultEditingTranslationUnitOptions() {
3313 return CXTranslationUnit_PrecompiledPreamble |
3314 CXTranslationUnit_CacheCompletionResults;
3315}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003316
Guy Benyei11169dd2012-12-18 14:30:41 +00003317CXTranslationUnit
3318clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3319 const char *source_filename,
3320 int num_command_line_args,
3321 const char * const *command_line_args,
3322 unsigned num_unsaved_files,
3323 struct CXUnsavedFile *unsaved_files) {
3324 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3325 return clang_parseTranslationUnit(CIdx, source_filename,
3326 command_line_args, num_command_line_args,
3327 unsaved_files, num_unsaved_files,
3328 Options);
3329}
3330
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003331static CXErrorCode
3332clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3333 const char *const *command_line_args,
3334 int num_command_line_args,
3335 ArrayRef<CXUnsavedFile> unsaved_files,
3336 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003337 // Set up the initial return values.
3338 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003339 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003340
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003341 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003342 if (!CIdx || !out_TU)
3343 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003344
Guy Benyei11169dd2012-12-18 14:30:41 +00003345 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3346
3347 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3348 setThreadBackgroundPriority();
3349
3350 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003351 bool CreatePreambleOnFirstParse =
3352 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003353 // FIXME: Add a flag for modules.
3354 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003355 = (options & (CXTranslationUnit_Incomplete |
3356 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003357 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003358 = options & CXTranslationUnit_CacheCompletionResults;
3359 bool IncludeBriefCommentsInCodeCompletion
3360 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3361 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003362 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3364
3365 // Configure the diagnostics.
3366 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003367 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003368
Manuel Klimek016c0242016-03-01 10:56:19 +00003369 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003370 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003371
Guy Benyei11169dd2012-12-18 14:30:41 +00003372 // Recover resources if we crash before exiting this function.
3373 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3374 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003375 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003376
Ahmed Charlesb8984322014-03-07 20:03:18 +00003377 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3378 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003379
3380 // Recover resources if we crash before exiting this function.
3381 llvm::CrashRecoveryContextCleanupRegistrar<
3382 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3383
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003384 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003385 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003386 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003387 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003388 }
3389
Ahmed Charlesb8984322014-03-07 20:03:18 +00003390 std::unique_ptr<std::vector<const char *>> Args(
3391 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003392
3393 // Recover resources if we crash before exiting this method.
3394 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3395 ArgsCleanup(Args.get());
3396
3397 // Since the Clang C library is primarily used by batch tools dealing with
3398 // (often very broken) source code, where spell-checking can have a
3399 // significant negative impact on performance (particularly when
3400 // precompiled headers are involved), we disable it by default.
3401 // Only do this if we haven't found a spell-checking-related argument.
3402 bool FoundSpellCheckingArgument = false;
3403 for (int I = 0; I != num_command_line_args; ++I) {
3404 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3405 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3406 FoundSpellCheckingArgument = true;
3407 break;
3408 }
3409 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003410 Args->insert(Args->end(), command_line_args,
3411 command_line_args + num_command_line_args);
3412
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003413 if (!FoundSpellCheckingArgument)
3414 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3415
Guy Benyei11169dd2012-12-18 14:30:41 +00003416 // The 'source_filename' argument is optional. If the caller does not
3417 // specify it then it is assumed that the source file is specified
3418 // in the actual argument list.
3419 // Put the source file after command_line_args otherwise if '-x' flag is
3420 // present it will be unused.
3421 if (source_filename)
3422 Args->push_back(source_filename);
3423
3424 // Do we need the detailed preprocessing record?
3425 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3426 Args->push_back("-Xclang");
3427 Args->push_back("-detailed-preprocessing-record");
3428 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003429
3430 // Suppress any editor placeholder diagnostics.
3431 Args->push_back("-fallow-editor-placeholders");
3432
Guy Benyei11169dd2012-12-18 14:30:41 +00003433 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003434 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003435 // Unless the user specified that they want the preamble on the first parse
3436 // set it up to be created on the first reparse. This makes the first parse
3437 // faster, trading for a slower (first) reparse.
3438 unsigned PrecompilePreambleAfterNParses =
3439 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003440
Alex Lorenz08615792017-12-04 21:56:36 +00003441 LibclangInvocationReporter InvocationReporter(
3442 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz80b55ee2017-12-05 02:30:43 +00003443 options, llvm::makeArrayRef(*Args), unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003444 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003445 Args->data(), Args->data() + Args->size(),
3446 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003447 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3448 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003449 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3450 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003451 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003452 /*UserFilesAreVolatile=*/true, ForSerialization,
3453 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3454 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003455
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003456 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003457 if (!Unit && !ErrUnit)
3458 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003459
Guy Benyei11169dd2012-12-18 14:30:41 +00003460 if (NumErrors != Diags->getClient()->getNumErrors()) {
3461 // Make sure to check that 'Unit' is non-NULL.
3462 if (CXXIdx->getDisplayDiagnostics())
3463 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3464 }
3465
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003466 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3467 return CXError_ASTReadError;
3468
David Blaikieea4395e2017-01-06 19:49:01 +00003469 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003470 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003471}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003472
3473CXTranslationUnit
3474clang_parseTranslationUnit(CXIndex CIdx,
3475 const char *source_filename,
3476 const char *const *command_line_args,
3477 int num_command_line_args,
3478 struct CXUnsavedFile *unsaved_files,
3479 unsigned num_unsaved_files,
3480 unsigned options) {
3481 CXTranslationUnit TU;
3482 enum CXErrorCode Result = clang_parseTranslationUnit2(
3483 CIdx, source_filename, command_line_args, num_command_line_args,
3484 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003485 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003486 assert((TU && Result == CXError_Success) ||
3487 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003488 return TU;
3489}
3490
3491enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003492 CXIndex CIdx, const char *source_filename,
3493 const char *const *command_line_args, int num_command_line_args,
3494 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3495 unsigned options, CXTranslationUnit *out_TU) {
3496 SmallVector<const char *, 4> Args;
3497 Args.push_back("clang");
3498 Args.append(command_line_args, command_line_args + num_command_line_args);
3499 return clang_parseTranslationUnit2FullArgv(
3500 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3501 num_unsaved_files, options, out_TU);
3502}
3503
3504enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3505 CXIndex CIdx, const char *source_filename,
3506 const char *const *command_line_args, int num_command_line_args,
3507 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3508 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003509 LOG_FUNC_SECTION {
3510 *Log << source_filename << ": ";
3511 for (int i = 0; i != num_command_line_args; ++i)
3512 *Log << command_line_args[i] << " ";
3513 }
3514
Alp Toker9d85b182014-07-07 01:23:14 +00003515 if (num_unsaved_files && !unsaved_files)
3516 return CXError_InvalidArguments;
3517
Alp Toker5c532982014-07-07 22:42:03 +00003518 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003519 auto ParseTranslationUnitImpl = [=, &result] {
3520 result = clang_parseTranslationUnit_Impl(
3521 CIdx, source_filename, command_line_args, num_command_line_args,
3522 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3523 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003524
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 llvm::CrashRecoveryContext CRC;
3526
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003527 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003528 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3529 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3530 fprintf(stderr, " 'command_line_args' : [");
3531 for (int i = 0; i != num_command_line_args; ++i) {
3532 if (i)
3533 fprintf(stderr, ", ");
3534 fprintf(stderr, "'%s'", command_line_args[i]);
3535 }
3536 fprintf(stderr, "],\n");
3537 fprintf(stderr, " 'unsaved_files' : [");
3538 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3539 if (i)
3540 fprintf(stderr, ", ");
3541 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3542 unsaved_files[i].Length);
3543 }
3544 fprintf(stderr, "],\n");
3545 fprintf(stderr, " 'options' : %d,\n", options);
3546 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003547
3548 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003549 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003550 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003551 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003552 }
Alp Toker5c532982014-07-07 22:42:03 +00003553
3554 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003555}
3556
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003557CXString clang_Type_getObjCEncoding(CXType CT) {
3558 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3559 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3560 std::string encoding;
3561 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3562 encoding);
3563
3564 return cxstring::createDup(encoding);
3565}
3566
3567static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3568 if (C.kind == CXCursor_MacroDefinition) {
3569 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3570 return MDR->getName();
3571 } else if (C.kind == CXCursor_MacroExpansion) {
3572 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3573 return ME.getName();
3574 }
3575 return nullptr;
3576}
3577
3578unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3579 const IdentifierInfo *II = getMacroIdentifier(C);
3580 if (!II) {
3581 return false;
3582 }
3583 ASTUnit *ASTU = getCursorASTUnit(C);
3584 Preprocessor &PP = ASTU->getPreprocessor();
3585 if (const MacroInfo *MI = PP.getMacroInfo(II))
3586 return MI->isFunctionLike();
3587 return false;
3588}
3589
3590unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3591 const IdentifierInfo *II = getMacroIdentifier(C);
3592 if (!II) {
3593 return false;
3594 }
3595 ASTUnit *ASTU = getCursorASTUnit(C);
3596 Preprocessor &PP = ASTU->getPreprocessor();
3597 if (const MacroInfo *MI = PP.getMacroInfo(II))
3598 return MI->isBuiltinMacro();
3599 return false;
3600}
3601
3602unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3603 const Decl *D = getCursorDecl(C);
3604 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3605 if (!FD) {
3606 return false;
3607 }
3608 return FD->isInlined();
3609}
3610
3611static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3612 if (callExpr->getNumArgs() != 1) {
3613 return nullptr;
3614 }
3615
3616 StringLiteral *S = nullptr;
3617 auto *arg = callExpr->getArg(0);
3618 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3619 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3620 auto *subExpr = I->getSubExprAsWritten();
3621
3622 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3623 return nullptr;
3624 }
3625
3626 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3627 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3628 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3629 } else {
3630 return nullptr;
3631 }
3632 return S;
3633}
3634
David Blaikie59272572016-04-13 18:23:33 +00003635struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003636 CXEvalResultKind EvalType;
3637 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003638 unsigned long long unsignedVal;
3639 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003640 double floatVal;
3641 char *stringVal;
3642 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003643 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003644 ~ExprEvalResult() {
3645 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3646 EvalType != CXEval_Int) {
3647 delete EvalData.stringVal;
3648 }
3649 }
3650};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003651
3652void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003653 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003654}
3655
3656CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3657 if (!E) {
3658 return CXEval_UnExposed;
3659 }
3660 return ((ExprEvalResult *)E)->EvalType;
3661}
3662
3663int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003664 return clang_EvalResult_getAsLongLong(E);
3665}
3666
3667long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003668 if (!E) {
3669 return 0;
3670 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003671 ExprEvalResult *Result = (ExprEvalResult*)E;
3672 if (Result->IsUnsignedInt)
3673 return Result->EvalData.unsignedVal;
3674 return Result->EvalData.intVal;
3675}
3676
3677unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3678 return ((ExprEvalResult *)E)->IsUnsignedInt;
3679}
3680
3681unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3682 if (!E) {
3683 return 0;
3684 }
3685
3686 ExprEvalResult *Result = (ExprEvalResult*)E;
3687 if (Result->IsUnsignedInt)
3688 return Result->EvalData.unsignedVal;
3689 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003690}
3691
3692double clang_EvalResult_getAsDouble(CXEvalResult E) {
3693 if (!E) {
3694 return 0;
3695 }
3696 return ((ExprEvalResult *)E)->EvalData.floatVal;
3697}
3698
3699const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3700 if (!E) {
3701 return nullptr;
3702 }
3703 return ((ExprEvalResult *)E)->EvalData.stringVal;
3704}
3705
3706static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3707 Expr::EvalResult ER;
3708 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003709 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003710 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003711
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003712 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003713 if (!expr->EvaluateAsRValue(ER, ctx))
3714 return nullptr;
3715
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003716 QualType rettype;
3717 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003718 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003719 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003720 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003721
David Blaikiebbc00882016-04-13 18:36:19 +00003722 if (ER.Val.isInt()) {
3723 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003724
3725 auto& val = ER.Val.getInt();
3726 if (val.isUnsigned()) {
3727 result->IsUnsignedInt = true;
3728 result->EvalData.unsignedVal = val.getZExtValue();
3729 } else {
3730 result->EvalData.intVal = val.getExtValue();
3731 }
3732
David Blaikiebbc00882016-04-13 18:36:19 +00003733 return result.release();
3734 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003735
David Blaikiebbc00882016-04-13 18:36:19 +00003736 if (ER.Val.isFloat()) {
3737 llvm::SmallVector<char, 100> Buffer;
3738 ER.Val.getFloat().toString(Buffer);
3739 std::string floatStr(Buffer.data(), Buffer.size());
3740 result->EvalType = CXEval_Float;
3741 bool ignored;
3742 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003743 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003744 llvm::APFloat::rmNearestTiesToEven, &ignored);
3745 result->EvalData.floatVal = apFloat.convertToDouble();
3746 return result.release();
3747 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003748
David Blaikiebbc00882016-04-13 18:36:19 +00003749 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3750 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3751 auto *subExpr = I->getSubExprAsWritten();
3752 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3753 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003754 const StringLiteral *StrE = nullptr;
3755 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003756 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003757
3758 if (ObjCExpr) {
3759 StrE = ObjCExpr->getString();
3760 result->EvalType = CXEval_ObjCStrLiteral;
3761 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003762 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003763 result->EvalType = CXEval_StrLiteral;
3764 }
3765
3766 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003767 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003768 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3769 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003770 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003771 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003772 }
3773 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3774 expr->getStmtClass() == Stmt::StringLiteralClass) {
3775 const StringLiteral *StrE = nullptr;
3776 const ObjCStringLiteral *ObjCExpr;
3777 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003778
David Blaikiebbc00882016-04-13 18:36:19 +00003779 if (ObjCExpr) {
3780 StrE = ObjCExpr->getString();
3781 result->EvalType = CXEval_ObjCStrLiteral;
3782 } else {
3783 StrE = cast<StringLiteral>(expr);
3784 result->EvalType = CXEval_StrLiteral;
3785 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003786
David Blaikiebbc00882016-04-13 18:36:19 +00003787 std::string strRef(StrE->getString().str());
3788 result->EvalData.stringVal = new char[strRef.size() + 1];
3789 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3790 result->EvalData.stringVal[strRef.size()] = '\0';
3791 return result.release();
3792 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003793
David Blaikiebbc00882016-04-13 18:36:19 +00003794 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3795 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003796
David Blaikiebbc00882016-04-13 18:36:19 +00003797 rettype = CC->getType();
3798 if (rettype.getAsString() == "CFStringRef" &&
3799 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003800
David Blaikiebbc00882016-04-13 18:36:19 +00003801 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3802 StringLiteral *S = getCFSTR_value(callExpr);
3803 if (S) {
3804 std::string strLiteral(S->getString().str());
3805 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003806
David Blaikiebbc00882016-04-13 18:36:19 +00003807 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3808 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3809 strLiteral.size());
3810 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003811 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003812 }
3813 }
3814
David Blaikiebbc00882016-04-13 18:36:19 +00003815 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3816 callExpr = static_cast<CallExpr *>(expr);
3817 rettype = callExpr->getCallReturnType(ctx);
3818
3819 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3820 return nullptr;
3821
3822 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3823 if (callExpr->getNumArgs() == 1 &&
3824 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3825 return nullptr;
3826 } else if (rettype.getAsString() == "CFStringRef") {
3827
3828 StringLiteral *S = getCFSTR_value(callExpr);
3829 if (S) {
3830 std::string strLiteral(S->getString().str());
3831 result->EvalType = CXEval_CFStr;
3832 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3833 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3834 strLiteral.size());
3835 result->EvalData.stringVal[strLiteral.size()] = '\0';
3836 return result.release();
3837 }
3838 }
3839 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3840 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3841 ValueDecl *V = D->getDecl();
3842 if (V->getKind() == Decl::Function) {
3843 std::string strName = V->getNameAsString();
3844 result->EvalType = CXEval_Other;
3845 result->EvalData.stringVal = new char[strName.size() + 1];
3846 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3847 result->EvalData.stringVal[strName.size()] = '\0';
3848 return result.release();
3849 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003850 }
3851
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003852 return nullptr;
3853}
3854
3855CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3856 const Decl *D = getCursorDecl(C);
3857 if (D) {
3858 const Expr *expr = nullptr;
3859 if (auto *Var = dyn_cast<VarDecl>(D)) {
3860 expr = Var->getInit();
3861 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3862 expr = Field->getInClassInitializer();
3863 }
3864 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003865 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3866 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003867 return nullptr;
3868 }
3869
3870 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3871 if (compoundStmt) {
3872 Expr *expr = nullptr;
3873 for (auto *bodyIterator : compoundStmt->body()) {
3874 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3875 break;
3876 }
3877 }
3878 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003879 return const_cast<CXEvalResult>(
3880 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003881 }
3882 return nullptr;
3883}
3884
3885unsigned clang_Cursor_hasAttrs(CXCursor C) {
3886 const Decl *D = getCursorDecl(C);
3887 if (!D) {
3888 return 0;
3889 }
3890
3891 if (D->hasAttrs()) {
3892 return 1;
3893 }
3894
3895 return 0;
3896}
Guy Benyei11169dd2012-12-18 14:30:41 +00003897unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3898 return CXSaveTranslationUnit_None;
3899}
3900
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003901static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3902 const char *FileName,
3903 unsigned options) {
3904 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003905 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3906 setThreadBackgroundPriority();
3907
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003908 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3909 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003910}
3911
3912int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3913 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003914 LOG_FUNC_SECTION {
3915 *Log << TU << ' ' << FileName;
3916 }
3917
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003918 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003919 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003920 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003921 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003922
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003923 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003924 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3925 if (!CXXUnit->hasSema())
3926 return CXSaveError_InvalidTU;
3927
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003928 CXSaveError result;
3929 auto SaveTranslationUnitImpl = [=, &result]() {
3930 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3931 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003932
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003933 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003934 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003935
3936 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3937 PrintLibclangResourceUsage(TU);
3938
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003939 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003940 }
3941
3942 // We have an AST that has invalid nodes due to compiler errors.
3943 // Use a crash recovery thread for protection.
3944
3945 llvm::CrashRecoveryContext CRC;
3946
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003947 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003948 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3949 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3950 fprintf(stderr, " 'options' : %d,\n", options);
3951 fprintf(stderr, "}\n");
3952
3953 return CXSaveError_Unknown;
3954
3955 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3956 PrintLibclangResourceUsage(TU);
3957 }
3958
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003959 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003960}
3961
3962void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3963 if (CTUnit) {
3964 // If the translation unit has been marked as unsafe to free, just discard
3965 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003966 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3967 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 return;
3969
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003970 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003971 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003972 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3973 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003974 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003975 delete CTUnit;
3976 }
3977}
3978
Erik Verbruggen346066b2017-05-30 14:25:54 +00003979unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
3980 if (CTUnit) {
3981 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3982
3983 if (Unit && Unit->isUnsafeToFree())
3984 return false;
3985
3986 Unit->ResetForParse();
3987 return true;
3988 }
3989
3990 return false;
3991}
3992
Guy Benyei11169dd2012-12-18 14:30:41 +00003993unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3994 return CXReparse_None;
3995}
3996
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003997static CXErrorCode
3998clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3999 ArrayRef<CXUnsavedFile> unsaved_files,
4000 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004001 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004002 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004003 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004004 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004005 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004006
4007 // Reset the associated diagnostics.
4008 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004009 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004010
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004011 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004012 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4013 setThreadBackgroundPriority();
4014
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004015 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004017
4018 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4019 new std::vector<ASTUnit::RemappedFile>());
4020
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 // Recover resources if we crash before exiting this function.
4022 llvm::CrashRecoveryContextCleanupRegistrar<
4023 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004024
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004025 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004026 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004027 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004028 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004029 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004030
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004031 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4032 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004033 return CXError_Success;
4034 if (isASTReadError(CXXUnit))
4035 return CXError_ASTReadError;
4036 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004037}
4038
4039int clang_reparseTranslationUnit(CXTranslationUnit TU,
4040 unsigned num_unsaved_files,
4041 struct CXUnsavedFile *unsaved_files,
4042 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004043 LOG_FUNC_SECTION {
4044 *Log << TU;
4045 }
4046
Alp Toker9d85b182014-07-07 01:23:14 +00004047 if (num_unsaved_files && !unsaved_files)
4048 return CXError_InvalidArguments;
4049
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004050 CXErrorCode result;
4051 auto ReparseTranslationUnitImpl = [=, &result]() {
4052 result = clang_reparseTranslationUnit_Impl(
4053 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4054 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004055
Guy Benyei11169dd2012-12-18 14:30:41 +00004056 llvm::CrashRecoveryContext CRC;
4057
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004058 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004060 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004061 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004062 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4063 PrintLibclangResourceUsage(TU);
4064
Alp Toker5c532982014-07-07 22:42:03 +00004065 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004066}
4067
4068
4069CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004070 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004071 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004072 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004073 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004074
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004075 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004076 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004077}
4078
4079CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004080 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004081 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004082 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004083 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004084
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004085 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004086 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4087}
4088
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004089CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4090 if (isNotUsableTU(CTUnit)) {
4091 LOG_BAD_TU(CTUnit);
4092 return nullptr;
4093 }
4094
4095 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4096 impl->TranslationUnit = CTUnit;
4097 return impl;
4098}
4099
4100CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4101 if (!TargetInfo)
4102 return cxstring::createEmpty();
4103
4104 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4105 assert(!isNotUsableTU(CTUnit) &&
4106 "Unexpected unusable translation unit in TargetInfo");
4107
4108 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4109 std::string Triple =
4110 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4111 return cxstring::createDup(Triple);
4112}
4113
4114int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4115 if (!TargetInfo)
4116 return -1;
4117
4118 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4119 assert(!isNotUsableTU(CTUnit) &&
4120 "Unexpected unusable translation unit in TargetInfo");
4121
4122 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4123 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4124}
4125
4126void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4127 if (!TargetInfo)
4128 return;
4129
4130 delete TargetInfo;
4131}
4132
Guy Benyei11169dd2012-12-18 14:30:41 +00004133//===----------------------------------------------------------------------===//
4134// CXFile Operations.
4135//===----------------------------------------------------------------------===//
4136
Guy Benyei11169dd2012-12-18 14:30:41 +00004137CXString clang_getFileName(CXFile SFile) {
4138 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004139 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004140
4141 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004142 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004143}
4144
4145time_t clang_getFileTime(CXFile SFile) {
4146 if (!SFile)
4147 return 0;
4148
4149 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4150 return FEnt->getModificationTime();
4151}
4152
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004153CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004154 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004155 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004156 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004157 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004158
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004159 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004160
4161 FileManager &FMgr = CXXUnit->getFileManager();
4162 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4163}
4164
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004165const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4166 size_t *size) {
4167 if (isNotUsableTU(TU)) {
4168 LOG_BAD_TU(TU);
4169 return nullptr;
4170 }
4171
4172 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4173 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4174 bool Invalid = true;
4175 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4176 if (Invalid) {
4177 if (size)
4178 *size = 0;
4179 return nullptr;
4180 }
4181 if (size)
4182 *size = buf->getBufferSize();
4183 return buf->getBufferStart();
4184}
4185
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004186unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4187 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004188 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004189 LOG_BAD_TU(TU);
4190 return 0;
4191 }
4192
4193 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 return 0;
4195
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004196 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 FileEntry *FEnt = static_cast<FileEntry *>(file);
4198 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4199 .isFileMultipleIncludeGuarded(FEnt);
4200}
4201
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004202int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4203 if (!file || !outID)
4204 return 1;
4205
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004206 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004207 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4208 outID->data[0] = ID.getDevice();
4209 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004210 outID->data[2] = FEnt->getModificationTime();
4211 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004212}
4213
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004214int clang_File_isEqual(CXFile file1, CXFile file2) {
4215 if (file1 == file2)
4216 return true;
4217
4218 if (!file1 || !file2)
4219 return false;
4220
4221 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4222 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4223 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4224}
4225
Guy Benyei11169dd2012-12-18 14:30:41 +00004226//===----------------------------------------------------------------------===//
4227// CXCursor Operations.
4228//===----------------------------------------------------------------------===//
4229
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004230static const Decl *getDeclFromExpr(const Stmt *E) {
4231 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 return getDeclFromExpr(CE->getSubExpr());
4233
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004234 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004236 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004237 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004238 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004240 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 if (PRE->isExplicitProperty())
4242 return PRE->getExplicitProperty();
4243 // It could be messaging both getter and setter as in:
4244 // ++myobj.myprop;
4245 // in which case prefer to associate the setter since it is less obvious
4246 // from inspecting the source that the setter is going to get called.
4247 if (PRE->isMessagingSetter())
4248 return PRE->getImplicitPropertySetter();
4249 return PRE->getImplicitPropertyGetter();
4250 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004251 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004253 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004254 if (Expr *Src = OVE->getSourceExpr())
4255 return getDeclFromExpr(Src);
4256
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004257 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004259 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004260 if (!CE->isElidable())
4261 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004262 if (const CXXInheritedCtorInitExpr *CE =
4263 dyn_cast<CXXInheritedCtorInitExpr>(E))
4264 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004265 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 return OME->getMethodDecl();
4267
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004268 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004270 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4272 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004273 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4275 isa<ParmVarDecl>(SizeOfPack->getPack()))
4276 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004277
4278 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004279}
4280
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004281static SourceLocation getLocationFromExpr(const Expr *E) {
4282 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004283 return getLocationFromExpr(CE->getSubExpr());
4284
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004285 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004287 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004289 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004291 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004293 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004295 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 return PropRef->getLocation();
4297
4298 return E->getLocStart();
4299}
4300
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004301extern "C" {
4302
Guy Benyei11169dd2012-12-18 14:30:41 +00004303unsigned clang_visitChildren(CXCursor parent,
4304 CXCursorVisitor visitor,
4305 CXClientData client_data) {
4306 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4307 /*VisitPreprocessorLast=*/false);
4308 return CursorVis.VisitChildren(parent);
4309}
4310
4311#ifndef __has_feature
4312#define __has_feature(x) 0
4313#endif
4314#if __has_feature(blocks)
4315typedef enum CXChildVisitResult
4316 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4317
4318static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4319 CXClientData client_data) {
4320 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4321 return block(cursor, parent);
4322}
4323#else
4324// If we are compiled with a compiler that doesn't have native blocks support,
4325// define and call the block manually, so the
4326typedef struct _CXChildVisitResult
4327{
4328 void *isa;
4329 int flags;
4330 int reserved;
4331 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4332 CXCursor);
4333} *CXCursorVisitorBlock;
4334
4335static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4336 CXClientData client_data) {
4337 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4338 return block->invoke(block, cursor, parent);
4339}
4340#endif
4341
4342
4343unsigned clang_visitChildrenWithBlock(CXCursor parent,
4344 CXCursorVisitorBlock block) {
4345 return clang_visitChildren(parent, visitWithBlock, block);
4346}
4347
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004348static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004350 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004351
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004352 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004354 if (const ObjCPropertyImplDecl *PropImpl =
4355 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004357 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004358
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004359 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004361 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004362
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004363 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004364 }
4365
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004366 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004367 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004368
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004369 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4371 // and returns different names. NamedDecl returns the class name and
4372 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004373 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004374
4375 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004376 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004377
4378 SmallString<1024> S;
4379 llvm::raw_svector_ostream os(S);
4380 ND->printName(os);
4381
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004382 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004383}
4384
4385CXString clang_getCursorSpelling(CXCursor C) {
4386 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004387 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004388
4389 if (clang_isReference(C.kind)) {
4390 switch (C.kind) {
4391 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004392 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004393 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 }
4395 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004396 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004397 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 }
4399 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004400 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004402 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004403 }
4404 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004405 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004406 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 }
4408 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004409 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 assert(Type && "Missing type decl");
4411
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004412 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004413 getAsString());
4414 }
4415 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004416 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 assert(Template && "Missing template decl");
4418
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004419 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 }
4421
4422 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004423 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 assert(NS && "Missing namespace decl");
4425
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004426 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 }
4428
4429 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004430 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 assert(Field && "Missing member decl");
4432
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004433 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 }
4435
4436 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004437 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 assert(Label && "Missing label");
4439
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004440 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 }
4442
4443 case CXCursor_OverloadedDeclRef: {
4444 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004445 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4446 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004447 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004448 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004450 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004451 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 OverloadedTemplateStorage *Ovl
4453 = Storage.get<OverloadedTemplateStorage*>();
4454 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004455 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004456 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 }
4458
4459 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004460 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 assert(Var && "Missing variable decl");
4462
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004463 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 }
4465
4466 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004467 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004468 }
4469 }
4470
4471 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004472 const Expr *E = getCursorExpr(C);
4473
4474 if (C.kind == CXCursor_ObjCStringLiteral ||
4475 C.kind == CXCursor_StringLiteral) {
4476 const StringLiteral *SLit;
4477 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4478 SLit = OSL->getString();
4479 } else {
4480 SLit = cast<StringLiteral>(E);
4481 }
4482 SmallString<256> Buf;
4483 llvm::raw_svector_ostream OS(Buf);
4484 SLit->outputString(OS);
4485 return cxstring::createDup(OS.str());
4486 }
4487
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004488 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 if (D)
4490 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004491 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 }
4493
4494 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004495 const Stmt *S = getCursorStmt(C);
4496 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004497 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004498
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004499 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 }
4501
4502 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004503 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 ->getNameStart());
4505
4506 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004507 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004508 ->getNameStart());
4509
4510 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004511 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004512
4513 if (clang_isDeclaration(C.kind))
4514 return getDeclSpelling(getCursorDecl(C));
4515
4516 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004517 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004518 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004519 }
4520
4521 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004522 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004523 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 }
4525
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004526 if (C.kind == CXCursor_PackedAttr) {
4527 return cxstring::createRef("packed");
4528 }
4529
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004530 if (C.kind == CXCursor_VisibilityAttr) {
4531 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4532 switch (AA->getVisibility()) {
4533 case VisibilityAttr::VisibilityType::Default:
4534 return cxstring::createRef("default");
4535 case VisibilityAttr::VisibilityType::Hidden:
4536 return cxstring::createRef("hidden");
4537 case VisibilityAttr::VisibilityType::Protected:
4538 return cxstring::createRef("protected");
4539 }
4540 llvm_unreachable("unknown visibility type");
4541 }
4542
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004543 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004544}
4545
4546CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4547 unsigned pieceIndex,
4548 unsigned options) {
4549 if (clang_Cursor_isNull(C))
4550 return clang_getNullRange();
4551
4552 ASTContext &Ctx = getCursorContext(C);
4553
4554 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004555 const Stmt *S = getCursorStmt(C);
4556 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 if (pieceIndex > 0)
4558 return clang_getNullRange();
4559 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4560 }
4561
4562 return clang_getNullRange();
4563 }
4564
4565 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004566 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4568 if (pieceIndex >= ME->getNumSelectorLocs())
4569 return clang_getNullRange();
4570 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4571 }
4572 }
4573
4574 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4575 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004576 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4578 if (pieceIndex >= MD->getNumSelectorLocs())
4579 return clang_getNullRange();
4580 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4581 }
4582 }
4583
4584 if (C.kind == CXCursor_ObjCCategoryDecl ||
4585 C.kind == CXCursor_ObjCCategoryImplDecl) {
4586 if (pieceIndex > 0)
4587 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004588 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4590 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004591 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004592 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4593 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4594 }
4595
4596 if (C.kind == CXCursor_ModuleImportDecl) {
4597 if (pieceIndex > 0)
4598 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004599 if (const ImportDecl *ImportD =
4600 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4602 if (!Locs.empty())
4603 return cxloc::translateSourceRange(Ctx,
4604 SourceRange(Locs.front(), Locs.back()));
4605 }
4606 return clang_getNullRange();
4607 }
4608
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004609 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004610 C.kind == CXCursor_ConversionFunction ||
4611 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004612 if (pieceIndex > 0)
4613 return clang_getNullRange();
4614 if (const FunctionDecl *FD =
4615 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4616 DeclarationNameInfo FunctionName = FD->getNameInfo();
4617 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4618 }
4619 return clang_getNullRange();
4620 }
4621
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 // FIXME: A CXCursor_InclusionDirective should give the location of the
4623 // filename, but we don't keep track of this.
4624
4625 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4626 // but we don't keep track of this.
4627
4628 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4629 // but we don't keep track of this.
4630
4631 // Default handling, give the location of the cursor.
4632
4633 if (pieceIndex > 0)
4634 return clang_getNullRange();
4635
4636 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4637 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4638 return cxloc::translateSourceRange(Ctx, Loc);
4639}
4640
Eli Bendersky44a206f2014-07-31 18:04:56 +00004641CXString clang_Cursor_getMangling(CXCursor C) {
4642 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4643 return cxstring::createEmpty();
4644
Eli Bendersky44a206f2014-07-31 18:04:56 +00004645 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004646 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004647 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4648 return cxstring::createEmpty();
4649
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004650 ASTContext &Ctx = D->getASTContext();
4651 index::CodegenNameGenerator CGNameGen(Ctx);
4652 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004653}
4654
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004655CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4656 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4657 return nullptr;
4658
4659 const Decl *D = getCursorDecl(C);
4660 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4661 return nullptr;
4662
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004663 ASTContext &Ctx = D->getASTContext();
4664 index::CodegenNameGenerator CGNameGen(Ctx);
4665 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004666 return cxstring::createSet(Manglings);
4667}
4668
Dave Lee1a532c92017-09-22 16:58:57 +00004669CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4670 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4671 return nullptr;
4672
4673 const Decl *D = getCursorDecl(C);
4674 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4675 return nullptr;
4676
4677 ASTContext &Ctx = D->getASTContext();
4678 index::CodegenNameGenerator CGNameGen(Ctx);
4679 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4680 return cxstring::createSet(Manglings);
4681}
4682
Guy Benyei11169dd2012-12-18 14:30:41 +00004683CXString clang_getCursorDisplayName(CXCursor C) {
4684 if (!clang_isDeclaration(C.kind))
4685 return clang_getCursorSpelling(C);
4686
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004687 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004689 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004690
4691 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004692 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004693 D = FunTmpl->getTemplatedDecl();
4694
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004695 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004696 SmallString<64> Str;
4697 llvm::raw_svector_ostream OS(Str);
4698 OS << *Function;
4699 if (Function->getPrimaryTemplate())
4700 OS << "<>";
4701 OS << "(";
4702 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4703 if (I)
4704 OS << ", ";
4705 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4706 }
4707
4708 if (Function->isVariadic()) {
4709 if (Function->getNumParams())
4710 OS << ", ";
4711 OS << "...";
4712 }
4713 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004714 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 }
4716
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004717 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 SmallString<64> Str;
4719 llvm::raw_svector_ostream OS(Str);
4720 OS << *ClassTemplate;
4721 OS << "<";
4722 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4723 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4724 if (I)
4725 OS << ", ";
4726
4727 NamedDecl *Param = Params->getParam(I);
4728 if (Param->getIdentifier()) {
4729 OS << Param->getIdentifier()->getName();
4730 continue;
4731 }
4732
4733 // There is no parameter name, which makes this tricky. Try to come up
4734 // with something useful that isn't too long.
4735 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4736 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4737 else if (NonTypeTemplateParmDecl *NTTP
4738 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4739 OS << NTTP->getType().getAsString(Policy);
4740 else
4741 OS << "template<...> class";
4742 }
4743
4744 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004745 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004746 }
4747
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004748 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004749 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4750 // If the type was explicitly written, use that.
4751 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004752 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00004753
Benjamin Kramer9170e912013-02-22 15:46:01 +00004754 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 llvm::raw_svector_ostream OS(Str);
4756 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00004757 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
4758 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004759 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 }
4761
4762 return clang_getCursorSpelling(C);
4763}
4764
4765CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4766 switch (Kind) {
4767 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004768 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004770 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004772 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004773 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004774 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004776 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004778 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004780 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004782 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004784 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004786 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004788 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004789 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004790 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004791 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004792 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004794 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004795 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004796 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004797 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004798 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004800 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004802 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004803 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004804 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004806 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004808 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004810 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004812 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004814 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004816 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004818 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004820 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004822 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004824 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004826 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004827 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004828 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004829 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004830 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004832 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004833 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004834 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004836 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004838 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004839 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004840 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004841 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004842 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004843 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004844 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004845 case CXCursor_OMPArraySectionExpr:
4846 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004848 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004849 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004850 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004851 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004852 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004853 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004854 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004855 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004856 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004857 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004858 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004860 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004861 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004862 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004863 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004864 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004866 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004868 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004869 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004870 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004871 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004872 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004874 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004876 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004877 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004878 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004880 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004881 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004882 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004884 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004886 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004888 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004890 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004891 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004892 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004894 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004895 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004896 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00004897 case CXCursor_ObjCAvailabilityCheckExpr:
4898 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004899 case CXCursor_ObjCSelfExpr:
4900 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004901 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004902 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004904 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004905 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004906 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004907 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004908 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004909 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004910 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004912 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004914 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004916 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004917 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004918 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004920 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004921 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004922 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004924 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004925 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004926 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004927 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004928 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004929 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004930 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004931 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004932 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004933 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004934 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004936 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004937 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004938 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004939 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004940 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004941 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004942 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004943 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004944 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004946 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004947 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004948 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004950 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004952 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004953 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004954 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004955 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004956 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004958 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004960 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004962 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004963 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004964 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004965 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004966 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004968 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004969 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004970 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004971 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004972 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004974 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004975 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004976 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004977 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004978 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004979 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004980 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004982 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004983 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004984 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004985 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004986 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004987 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004988 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004989 case CXCursor_SEHLeaveStmt:
4990 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004992 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004993 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004994 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004996 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00004997 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004998 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00004999 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005000 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005002 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005004 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005005 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005006 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005007 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005008 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005010 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005011 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005012 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005014 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005016 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005018 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005019 case CXCursor_PackedAttr:
5020 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005021 case CXCursor_PureAttr:
5022 return cxstring::createRef("attribute(pure)");
5023 case CXCursor_ConstAttr:
5024 return cxstring::createRef("attribute(const)");
5025 case CXCursor_NoDuplicateAttr:
5026 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005027 case CXCursor_CUDAConstantAttr:
5028 return cxstring::createRef("attribute(constant)");
5029 case CXCursor_CUDADeviceAttr:
5030 return cxstring::createRef("attribute(device)");
5031 case CXCursor_CUDAGlobalAttr:
5032 return cxstring::createRef("attribute(global)");
5033 case CXCursor_CUDAHostAttr:
5034 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005035 case CXCursor_CUDASharedAttr:
5036 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005037 case CXCursor_VisibilityAttr:
5038 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005039 case CXCursor_DLLExport:
5040 return cxstring::createRef("attribute(dllexport)");
5041 case CXCursor_DLLImport:
5042 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005044 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005046 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005048 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005050 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005052 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005066 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005072 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005078 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005082 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005084 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005088 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005091 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005092 return cxstring::createRef("OMPParallelDirective");
5093 case CXCursor_OMPSimdDirective:
5094 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005095 case CXCursor_OMPForDirective:
5096 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005097 case CXCursor_OMPForSimdDirective:
5098 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005099 case CXCursor_OMPSectionsDirective:
5100 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005101 case CXCursor_OMPSectionDirective:
5102 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005103 case CXCursor_OMPSingleDirective:
5104 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005105 case CXCursor_OMPMasterDirective:
5106 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005107 case CXCursor_OMPCriticalDirective:
5108 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005109 case CXCursor_OMPParallelForDirective:
5110 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005111 case CXCursor_OMPParallelForSimdDirective:
5112 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005113 case CXCursor_OMPParallelSectionsDirective:
5114 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005115 case CXCursor_OMPTaskDirective:
5116 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005117 case CXCursor_OMPTaskyieldDirective:
5118 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005119 case CXCursor_OMPBarrierDirective:
5120 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005121 case CXCursor_OMPTaskwaitDirective:
5122 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005123 case CXCursor_OMPTaskgroupDirective:
5124 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005125 case CXCursor_OMPFlushDirective:
5126 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005127 case CXCursor_OMPOrderedDirective:
5128 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005129 case CXCursor_OMPAtomicDirective:
5130 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005131 case CXCursor_OMPTargetDirective:
5132 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005133 case CXCursor_OMPTargetDataDirective:
5134 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005135 case CXCursor_OMPTargetEnterDataDirective:
5136 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005137 case CXCursor_OMPTargetExitDataDirective:
5138 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005139 case CXCursor_OMPTargetParallelDirective:
5140 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005141 case CXCursor_OMPTargetParallelForDirective:
5142 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005143 case CXCursor_OMPTargetUpdateDirective:
5144 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005145 case CXCursor_OMPTeamsDirective:
5146 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005147 case CXCursor_OMPCancellationPointDirective:
5148 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005149 case CXCursor_OMPCancelDirective:
5150 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005151 case CXCursor_OMPTaskLoopDirective:
5152 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005153 case CXCursor_OMPTaskLoopSimdDirective:
5154 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005155 case CXCursor_OMPDistributeDirective:
5156 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005157 case CXCursor_OMPDistributeParallelForDirective:
5158 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005159 case CXCursor_OMPDistributeParallelForSimdDirective:
5160 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005161 case CXCursor_OMPDistributeSimdDirective:
5162 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005163 case CXCursor_OMPTargetParallelForSimdDirective:
5164 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005165 case CXCursor_OMPTargetSimdDirective:
5166 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005167 case CXCursor_OMPTeamsDistributeDirective:
5168 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005169 case CXCursor_OMPTeamsDistributeSimdDirective:
5170 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005171 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5172 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005173 case CXCursor_OMPTeamsDistributeParallelForDirective:
5174 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005175 case CXCursor_OMPTargetTeamsDirective:
5176 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005177 case CXCursor_OMPTargetTeamsDistributeDirective:
5178 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005179 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5180 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005181 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5182 return cxstring::createRef(
5183 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005184 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5185 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005186 case CXCursor_OverloadCandidate:
5187 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005188 case CXCursor_TypeAliasTemplateDecl:
5189 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005190 case CXCursor_StaticAssert:
5191 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005192 case CXCursor_FriendDecl:
5193 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 }
5195
5196 llvm_unreachable("Unhandled CXCursorKind");
5197}
5198
5199struct GetCursorData {
5200 SourceLocation TokenBeginLoc;
5201 bool PointsAtMacroArgExpansion;
5202 bool VisitedObjCPropertyImplDecl;
5203 SourceLocation VisitedDeclaratorDeclStartLoc;
5204 CXCursor &BestCursor;
5205
5206 GetCursorData(SourceManager &SM,
5207 SourceLocation tokenBegin, CXCursor &outputCursor)
5208 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5209 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5210 VisitedObjCPropertyImplDecl = false;
5211 }
5212};
5213
5214static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5215 CXCursor parent,
5216 CXClientData client_data) {
5217 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5218 CXCursor *BestCursor = &Data->BestCursor;
5219
5220 // If we point inside a macro argument we should provide info of what the
5221 // token is so use the actual cursor, don't replace it with a macro expansion
5222 // cursor.
5223 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5224 return CXChildVisit_Recurse;
5225
5226 if (clang_isDeclaration(cursor.kind)) {
5227 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005228 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5230 if (MD->isImplicit())
5231 return CXChildVisit_Break;
5232
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005233 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5235 // Check that when we have multiple @class references in the same line,
5236 // that later ones do not override the previous ones.
5237 // If we have:
5238 // @class Foo, Bar;
5239 // source ranges for both start at '@', so 'Bar' will end up overriding
5240 // 'Foo' even though the cursor location was at 'Foo'.
5241 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5242 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005243 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5245 if (PrevID != ID &&
5246 !PrevID->isThisDeclarationADefinition() &&
5247 !ID->isThisDeclarationADefinition())
5248 return CXChildVisit_Break;
5249 }
5250
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005251 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5253 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5254 // Check that when we have multiple declarators in the same line,
5255 // that later ones do not override the previous ones.
5256 // If we have:
5257 // int Foo, Bar;
5258 // source ranges for both start at 'int', so 'Bar' will end up overriding
5259 // 'Foo' even though the cursor location was at 'Foo'.
5260 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5261 return CXChildVisit_Break;
5262 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5263
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005264 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5266 (void)PropImp;
5267 // Check that when we have multiple @synthesize in the same line,
5268 // that later ones do not override the previous ones.
5269 // If we have:
5270 // @synthesize Foo, Bar;
5271 // source ranges for both start at '@', so 'Bar' will end up overriding
5272 // 'Foo' even though the cursor location was at 'Foo'.
5273 if (Data->VisitedObjCPropertyImplDecl)
5274 return CXChildVisit_Break;
5275 Data->VisitedObjCPropertyImplDecl = true;
5276 }
5277 }
5278
5279 if (clang_isExpression(cursor.kind) &&
5280 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005281 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 // Avoid having the cursor of an expression replace the declaration cursor
5283 // when the expression source range overlaps the declaration range.
5284 // This can happen for C++ constructor expressions whose range generally
5285 // include the variable declaration, e.g.:
5286 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5287 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5288 D->getLocation() == Data->TokenBeginLoc)
5289 return CXChildVisit_Break;
5290 }
5291 }
5292
5293 // If our current best cursor is the construction of a temporary object,
5294 // don't replace that cursor with a type reference, because we want
5295 // clang_getCursor() to point at the constructor.
5296 if (clang_isExpression(BestCursor->kind) &&
5297 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5298 cursor.kind == CXCursor_TypeRef) {
5299 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5300 // as having the actual point on the type reference.
5301 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5302 return CXChildVisit_Recurse;
5303 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005304
5305 // If we already have an Objective-C superclass reference, don't
5306 // update it further.
5307 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5308 return CXChildVisit_Break;
5309
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 *BestCursor = cursor;
5311 return CXChildVisit_Recurse;
5312}
5313
5314CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005315 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005316 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005317 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005318 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005319
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005320 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005321 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5322
5323 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5324 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5325
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005326 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005327 CXFile SearchFile;
5328 unsigned SearchLine, SearchColumn;
5329 CXFile ResultFile;
5330 unsigned ResultLine, ResultColumn;
5331 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5332 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5333 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005334
5335 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5336 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005337 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005338 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 SearchFileName = clang_getFileName(SearchFile);
5340 ResultFileName = clang_getFileName(ResultFile);
5341 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5342 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005343 *Log << llvm::format("(%s:%d:%d) = %s",
5344 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5345 clang_getCString(KindSpelling))
5346 << llvm::format("(%s:%d:%d):%s%s",
5347 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5348 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 clang_disposeString(SearchFileName);
5350 clang_disposeString(ResultFileName);
5351 clang_disposeString(KindSpelling);
5352 clang_disposeString(USR);
5353
5354 CXCursor Definition = clang_getCursorDefinition(Result);
5355 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5356 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5357 CXString DefinitionKindSpelling
5358 = clang_getCursorKindSpelling(Definition.kind);
5359 CXFile DefinitionFile;
5360 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005361 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005362 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005364 *Log << llvm::format(" -> %s(%s:%d:%d)",
5365 clang_getCString(DefinitionKindSpelling),
5366 clang_getCString(DefinitionFileName),
5367 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005368 clang_disposeString(DefinitionFileName);
5369 clang_disposeString(DefinitionKindSpelling);
5370 }
5371 }
5372
5373 return Result;
5374}
5375
5376CXCursor clang_getNullCursor(void) {
5377 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5378}
5379
5380unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005381 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5382 // can't set consistently. For example, when visiting a DeclStmt we will set
5383 // it but we don't set it on the result of clang_getCursorDefinition for
5384 // a reference of the same declaration.
5385 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5386 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5387 // to provide that kind of info.
5388 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005389 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005390 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005391 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005392
Guy Benyei11169dd2012-12-18 14:30:41 +00005393 return X == Y;
5394}
5395
5396unsigned clang_hashCursor(CXCursor C) {
5397 unsigned Index = 0;
5398 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5399 Index = 1;
5400
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005401 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005402 std::make_pair(C.kind, C.data[Index]));
5403}
5404
5405unsigned clang_isInvalid(enum CXCursorKind K) {
5406 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5407}
5408
5409unsigned clang_isDeclaration(enum CXCursorKind K) {
5410 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5411 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5412}
5413
5414unsigned clang_isReference(enum CXCursorKind K) {
5415 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5416}
5417
5418unsigned clang_isExpression(enum CXCursorKind K) {
5419 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5420}
5421
5422unsigned clang_isStatement(enum CXCursorKind K) {
5423 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5424}
5425
5426unsigned clang_isAttribute(enum CXCursorKind K) {
5427 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5428}
5429
5430unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5431 return K == CXCursor_TranslationUnit;
5432}
5433
5434unsigned clang_isPreprocessing(enum CXCursorKind K) {
5435 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5436}
5437
5438unsigned clang_isUnexposed(enum CXCursorKind K) {
5439 switch (K) {
5440 case CXCursor_UnexposedDecl:
5441 case CXCursor_UnexposedExpr:
5442 case CXCursor_UnexposedStmt:
5443 case CXCursor_UnexposedAttr:
5444 return true;
5445 default:
5446 return false;
5447 }
5448}
5449
5450CXCursorKind clang_getCursorKind(CXCursor C) {
5451 return C.kind;
5452}
5453
5454CXSourceLocation clang_getCursorLocation(CXCursor C) {
5455 if (clang_isReference(C.kind)) {
5456 switch (C.kind) {
5457 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005458 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005459 = getCursorObjCSuperClassRef(C);
5460 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5461 }
5462
5463 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005464 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005465 = getCursorObjCProtocolRef(C);
5466 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5467 }
5468
5469 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005470 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005471 = getCursorObjCClassRef(C);
5472 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5473 }
5474
5475 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005476 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005477 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5478 }
5479
5480 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005481 std::pair<const TemplateDecl *, SourceLocation> P =
5482 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005483 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5484 }
5485
5486 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005487 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005488 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5489 }
5490
5491 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005492 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005493 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5494 }
5495
5496 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005497 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005498 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5499 }
5500
5501 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005502 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005503 if (!BaseSpec)
5504 return clang_getNullLocation();
5505
5506 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5507 return cxloc::translateSourceLocation(getCursorContext(C),
5508 TSInfo->getTypeLoc().getBeginLoc());
5509
5510 return cxloc::translateSourceLocation(getCursorContext(C),
5511 BaseSpec->getLocStart());
5512 }
5513
5514 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005515 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005516 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5517 }
5518
5519 case CXCursor_OverloadedDeclRef:
5520 return cxloc::translateSourceLocation(getCursorContext(C),
5521 getCursorOverloadedDeclRef(C).second);
5522
5523 default:
5524 // FIXME: Need a way to enumerate all non-reference cases.
5525 llvm_unreachable("Missed a reference kind");
5526 }
5527 }
5528
5529 if (clang_isExpression(C.kind))
5530 return cxloc::translateSourceLocation(getCursorContext(C),
5531 getLocationFromExpr(getCursorExpr(C)));
5532
5533 if (clang_isStatement(C.kind))
5534 return cxloc::translateSourceLocation(getCursorContext(C),
5535 getCursorStmt(C)->getLocStart());
5536
5537 if (C.kind == CXCursor_PreprocessingDirective) {
5538 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5539 return cxloc::translateSourceLocation(getCursorContext(C), L);
5540 }
5541
5542 if (C.kind == CXCursor_MacroExpansion) {
5543 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005544 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005545 return cxloc::translateSourceLocation(getCursorContext(C), L);
5546 }
5547
5548 if (C.kind == CXCursor_MacroDefinition) {
5549 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5550 return cxloc::translateSourceLocation(getCursorContext(C), L);
5551 }
5552
5553 if (C.kind == CXCursor_InclusionDirective) {
5554 SourceLocation L
5555 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5556 return cxloc::translateSourceLocation(getCursorContext(C), L);
5557 }
5558
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005559 if (clang_isAttribute(C.kind)) {
5560 SourceLocation L
5561 = cxcursor::getCursorAttr(C)->getLocation();
5562 return cxloc::translateSourceLocation(getCursorContext(C), L);
5563 }
5564
Guy Benyei11169dd2012-12-18 14:30:41 +00005565 if (!clang_isDeclaration(C.kind))
5566 return clang_getNullLocation();
5567
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005568 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005569 if (!D)
5570 return clang_getNullLocation();
5571
5572 SourceLocation Loc = D->getLocation();
5573 // FIXME: Multiple variables declared in a single declaration
5574 // currently lack the information needed to correctly determine their
5575 // ranges when accounting for the type-specifier. We use context
5576 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5577 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005578 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005579 if (!cxcursor::isFirstInDeclGroup(C))
5580 Loc = VD->getLocation();
5581 }
5582
5583 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005584 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005585 Loc = MD->getSelectorStartLoc();
5586
5587 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5588}
5589
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005590} // end extern "C"
5591
Guy Benyei11169dd2012-12-18 14:30:41 +00005592CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5593 assert(TU);
5594
5595 // Guard against an invalid SourceLocation, or we may assert in one
5596 // of the following calls.
5597 if (SLoc.isInvalid())
5598 return clang_getNullCursor();
5599
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005600 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005601
5602 // Translate the given source location to make it point at the beginning of
5603 // the token under the cursor.
5604 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5605 CXXUnit->getASTContext().getLangOpts());
5606
5607 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5608 if (SLoc.isValid()) {
5609 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5610 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5611 /*VisitPreprocessorLast=*/true,
5612 /*VisitIncludedEntities=*/false,
5613 SourceLocation(SLoc));
5614 CursorVis.visitFileRegion();
5615 }
5616
5617 return Result;
5618}
5619
5620static SourceRange getRawCursorExtent(CXCursor C) {
5621 if (clang_isReference(C.kind)) {
5622 switch (C.kind) {
5623 case CXCursor_ObjCSuperClassRef:
5624 return getCursorObjCSuperClassRef(C).second;
5625
5626 case CXCursor_ObjCProtocolRef:
5627 return getCursorObjCProtocolRef(C).second;
5628
5629 case CXCursor_ObjCClassRef:
5630 return getCursorObjCClassRef(C).second;
5631
5632 case CXCursor_TypeRef:
5633 return getCursorTypeRef(C).second;
5634
5635 case CXCursor_TemplateRef:
5636 return getCursorTemplateRef(C).second;
5637
5638 case CXCursor_NamespaceRef:
5639 return getCursorNamespaceRef(C).second;
5640
5641 case CXCursor_MemberRef:
5642 return getCursorMemberRef(C).second;
5643
5644 case CXCursor_CXXBaseSpecifier:
5645 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5646
5647 case CXCursor_LabelRef:
5648 return getCursorLabelRef(C).second;
5649
5650 case CXCursor_OverloadedDeclRef:
5651 return getCursorOverloadedDeclRef(C).second;
5652
5653 case CXCursor_VariableRef:
5654 return getCursorVariableRef(C).second;
5655
5656 default:
5657 // FIXME: Need a way to enumerate all non-reference cases.
5658 llvm_unreachable("Missed a reference kind");
5659 }
5660 }
5661
5662 if (clang_isExpression(C.kind))
5663 return getCursorExpr(C)->getSourceRange();
5664
5665 if (clang_isStatement(C.kind))
5666 return getCursorStmt(C)->getSourceRange();
5667
5668 if (clang_isAttribute(C.kind))
5669 return getCursorAttr(C)->getRange();
5670
5671 if (C.kind == CXCursor_PreprocessingDirective)
5672 return cxcursor::getCursorPreprocessingDirective(C);
5673
5674 if (C.kind == CXCursor_MacroExpansion) {
5675 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005676 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005677 return TU->mapRangeFromPreamble(Range);
5678 }
5679
5680 if (C.kind == CXCursor_MacroDefinition) {
5681 ASTUnit *TU = getCursorASTUnit(C);
5682 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5683 return TU->mapRangeFromPreamble(Range);
5684 }
5685
5686 if (C.kind == CXCursor_InclusionDirective) {
5687 ASTUnit *TU = getCursorASTUnit(C);
5688 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5689 return TU->mapRangeFromPreamble(Range);
5690 }
5691
5692 if (C.kind == CXCursor_TranslationUnit) {
5693 ASTUnit *TU = getCursorASTUnit(C);
5694 FileID MainID = TU->getSourceManager().getMainFileID();
5695 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5696 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5697 return SourceRange(Start, End);
5698 }
5699
5700 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005701 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005702 if (!D)
5703 return SourceRange();
5704
5705 SourceRange R = D->getSourceRange();
5706 // FIXME: Multiple variables declared in a single declaration
5707 // currently lack the information needed to correctly determine their
5708 // ranges when accounting for the type-specifier. We use context
5709 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5710 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005711 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005712 if (!cxcursor::isFirstInDeclGroup(C))
5713 R.setBegin(VD->getLocation());
5714 }
5715 return R;
5716 }
5717 return SourceRange();
5718}
5719
5720/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5721/// the decl-specifier-seq for declarations.
5722static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5723 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005724 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005725 if (!D)
5726 return SourceRange();
5727
5728 SourceRange R = D->getSourceRange();
5729
5730 // Adjust the start of the location for declarations preceded by
5731 // declaration specifiers.
5732 SourceLocation StartLoc;
5733 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5734 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5735 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005736 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005737 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5738 StartLoc = TI->getTypeLoc().getLocStart();
5739 }
5740
5741 if (StartLoc.isValid() && R.getBegin().isValid() &&
5742 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5743 R.setBegin(StartLoc);
5744
5745 // FIXME: Multiple variables declared in a single declaration
5746 // currently lack the information needed to correctly determine their
5747 // ranges when accounting for the type-specifier. We use context
5748 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5749 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005750 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005751 if (!cxcursor::isFirstInDeclGroup(C))
5752 R.setBegin(VD->getLocation());
5753 }
5754
5755 return R;
5756 }
5757
5758 return getRawCursorExtent(C);
5759}
5760
Guy Benyei11169dd2012-12-18 14:30:41 +00005761CXSourceRange clang_getCursorExtent(CXCursor C) {
5762 SourceRange R = getRawCursorExtent(C);
5763 if (R.isInvalid())
5764 return clang_getNullRange();
5765
5766 return cxloc::translateSourceRange(getCursorContext(C), R);
5767}
5768
5769CXCursor clang_getCursorReferenced(CXCursor C) {
5770 if (clang_isInvalid(C.kind))
5771 return clang_getNullCursor();
5772
5773 CXTranslationUnit tu = getCursorTU(C);
5774 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005775 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005776 if (!D)
5777 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005778 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005779 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005780 if (const ObjCPropertyImplDecl *PropImpl =
5781 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005782 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5783 return MakeCXCursor(Property, tu);
5784
5785 return C;
5786 }
5787
5788 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005789 const Expr *E = getCursorExpr(C);
5790 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005791 if (D) {
5792 CXCursor declCursor = MakeCXCursor(D, tu);
5793 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5794 declCursor);
5795 return declCursor;
5796 }
5797
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005798 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005799 return MakeCursorOverloadedDeclRef(Ovl, tu);
5800
5801 return clang_getNullCursor();
5802 }
5803
5804 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005805 const Stmt *S = getCursorStmt(C);
5806 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005807 if (LabelDecl *label = Goto->getLabel())
5808 if (LabelStmt *labelS = label->getStmt())
5809 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5810
5811 return clang_getNullCursor();
5812 }
Richard Smith66a81862015-05-04 02:25:31 +00005813
Guy Benyei11169dd2012-12-18 14:30:41 +00005814 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005815 if (const MacroDefinitionRecord *Def =
5816 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005817 return MakeMacroDefinitionCursor(Def, tu);
5818 }
5819
5820 if (!clang_isReference(C.kind))
5821 return clang_getNullCursor();
5822
5823 switch (C.kind) {
5824 case CXCursor_ObjCSuperClassRef:
5825 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5826
5827 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005828 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5829 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005830 return MakeCXCursor(Def, tu);
5831
5832 return MakeCXCursor(Prot, tu);
5833 }
5834
5835 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005836 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5837 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005838 return MakeCXCursor(Def, tu);
5839
5840 return MakeCXCursor(Class, tu);
5841 }
5842
5843 case CXCursor_TypeRef:
5844 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5845
5846 case CXCursor_TemplateRef:
5847 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5848
5849 case CXCursor_NamespaceRef:
5850 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5851
5852 case CXCursor_MemberRef:
5853 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5854
5855 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005856 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005857 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5858 tu ));
5859 }
5860
5861 case CXCursor_LabelRef:
5862 // FIXME: We end up faking the "parent" declaration here because we
5863 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005864 return MakeCXCursor(getCursorLabelRef(C).first,
5865 cxtu::getASTUnit(tu)->getASTContext()
5866 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005867 tu);
5868
5869 case CXCursor_OverloadedDeclRef:
5870 return C;
5871
5872 case CXCursor_VariableRef:
5873 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5874
5875 default:
5876 // We would prefer to enumerate all non-reference cursor kinds here.
5877 llvm_unreachable("Unhandled reference cursor kind");
5878 }
5879}
5880
5881CXCursor clang_getCursorDefinition(CXCursor C) {
5882 if (clang_isInvalid(C.kind))
5883 return clang_getNullCursor();
5884
5885 CXTranslationUnit TU = getCursorTU(C);
5886
5887 bool WasReference = false;
5888 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5889 C = clang_getCursorReferenced(C);
5890 WasReference = true;
5891 }
5892
5893 if (C.kind == CXCursor_MacroExpansion)
5894 return clang_getCursorReferenced(C);
5895
5896 if (!clang_isDeclaration(C.kind))
5897 return clang_getNullCursor();
5898
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005899 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005900 if (!D)
5901 return clang_getNullCursor();
5902
5903 switch (D->getKind()) {
5904 // Declaration kinds that don't really separate the notions of
5905 // declaration and definition.
5906 case Decl::Namespace:
5907 case Decl::Typedef:
5908 case Decl::TypeAlias:
5909 case Decl::TypeAliasTemplate:
5910 case Decl::TemplateTypeParm:
5911 case Decl::EnumConstant:
5912 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00005913 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00005914 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005915 case Decl::IndirectField:
5916 case Decl::ObjCIvar:
5917 case Decl::ObjCAtDefsField:
5918 case Decl::ImplicitParam:
5919 case Decl::ParmVar:
5920 case Decl::NonTypeTemplateParm:
5921 case Decl::TemplateTemplateParm:
5922 case Decl::ObjCCategoryImpl:
5923 case Decl::ObjCImplementation:
5924 case Decl::AccessSpec:
5925 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00005926 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00005927 case Decl::ObjCPropertyImpl:
5928 case Decl::FileScopeAsm:
5929 case Decl::StaticAssert:
5930 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005931 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005932 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005933 case Decl::Label: // FIXME: Is this right??
5934 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00005935 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00005936 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005937 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005938 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005939 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005940 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005941 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005942 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00005943 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00005944 return C;
5945
5946 // Declaration kinds that don't make any sense here, but are
5947 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005948 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005949 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005950 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005951 break;
5952
5953 // Declaration kinds for which the definition is not resolvable.
5954 case Decl::UnresolvedUsingTypename:
5955 case Decl::UnresolvedUsingValue:
5956 break;
5957
5958 case Decl::UsingDirective:
5959 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5960 TU);
5961
5962 case Decl::NamespaceAlias:
5963 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5964
5965 case Decl::Enum:
5966 case Decl::Record:
5967 case Decl::CXXRecord:
5968 case Decl::ClassTemplateSpecialization:
5969 case Decl::ClassTemplatePartialSpecialization:
5970 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5971 return MakeCXCursor(Def, TU);
5972 return clang_getNullCursor();
5973
5974 case Decl::Function:
5975 case Decl::CXXMethod:
5976 case Decl::CXXConstructor:
5977 case Decl::CXXDestructor:
5978 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005979 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005980 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005981 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005982 return clang_getNullCursor();
5983 }
5984
Larisse Voufo39a1e502013-08-06 01:03:05 +00005985 case Decl::Var:
5986 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00005987 case Decl::VarTemplatePartialSpecialization:
5988 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005989 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005990 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005991 return MakeCXCursor(Def, TU);
5992 return clang_getNullCursor();
5993 }
5994
5995 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00005996 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005997 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5998 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5999 return clang_getNullCursor();
6000 }
6001
6002 case Decl::ClassTemplate: {
6003 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6004 ->getDefinition())
6005 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6006 TU);
6007 return clang_getNullCursor();
6008 }
6009
Larisse Voufo39a1e502013-08-06 01:03:05 +00006010 case Decl::VarTemplate: {
6011 if (VarDecl *Def =
6012 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6013 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6014 return clang_getNullCursor();
6015 }
6016
Guy Benyei11169dd2012-12-18 14:30:41 +00006017 case Decl::Using:
6018 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6019 D->getLocation(), TU);
6020
6021 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006022 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006023 return clang_getCursorDefinition(
6024 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6025 TU));
6026
6027 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006028 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006029 if (Method->isThisDeclarationADefinition())
6030 return C;
6031
6032 // Dig out the method definition in the associated
6033 // @implementation, if we have it.
6034 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006035 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006036 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6037 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6038 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6039 Method->isInstanceMethod()))
6040 if (Def->isThisDeclarationADefinition())
6041 return MakeCXCursor(Def, TU);
6042
6043 return clang_getNullCursor();
6044 }
6045
6046 case Decl::ObjCCategory:
6047 if (ObjCCategoryImplDecl *Impl
6048 = cast<ObjCCategoryDecl>(D)->getImplementation())
6049 return MakeCXCursor(Impl, TU);
6050 return clang_getNullCursor();
6051
6052 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006053 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006054 return MakeCXCursor(Def, TU);
6055 return clang_getNullCursor();
6056
6057 case Decl::ObjCInterface: {
6058 // There are two notions of a "definition" for an Objective-C
6059 // class: the interface and its implementation. When we resolved a
6060 // reference to an Objective-C class, produce the @interface as
6061 // the definition; when we were provided with the interface,
6062 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006063 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006064 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006065 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006066 return MakeCXCursor(Def, TU);
6067 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6068 return MakeCXCursor(Impl, TU);
6069 return clang_getNullCursor();
6070 }
6071
6072 case Decl::ObjCProperty:
6073 // FIXME: We don't really know where to find the
6074 // ObjCPropertyImplDecls that implement this property.
6075 return clang_getNullCursor();
6076
6077 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006078 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006079 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006080 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006081 return MakeCXCursor(Def, TU);
6082
6083 return clang_getNullCursor();
6084
6085 case Decl::Friend:
6086 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6087 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6088 return clang_getNullCursor();
6089
6090 case Decl::FriendTemplate:
6091 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6092 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6093 return clang_getNullCursor();
6094 }
6095
6096 return clang_getNullCursor();
6097}
6098
6099unsigned clang_isCursorDefinition(CXCursor C) {
6100 if (!clang_isDeclaration(C.kind))
6101 return 0;
6102
6103 return clang_getCursorDefinition(C) == C;
6104}
6105
6106CXCursor clang_getCanonicalCursor(CXCursor C) {
6107 if (!clang_isDeclaration(C.kind))
6108 return C;
6109
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006110 if (const Decl *D = getCursorDecl(C)) {
6111 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006112 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6113 return MakeCXCursor(CatD, getCursorTU(C));
6114
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006115 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6116 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006117 return MakeCXCursor(IFD, getCursorTU(C));
6118
6119 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6120 }
6121
6122 return C;
6123}
6124
6125int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6126 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6127}
6128
6129unsigned clang_getNumOverloadedDecls(CXCursor C) {
6130 if (C.kind != CXCursor_OverloadedDeclRef)
6131 return 0;
6132
6133 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006134 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 return E->getNumDecls();
6136
6137 if (OverloadedTemplateStorage *S
6138 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6139 return S->size();
6140
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006141 const Decl *D = Storage.get<const Decl *>();
6142 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006143 return Using->shadow_size();
6144
6145 return 0;
6146}
6147
6148CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6149 if (cursor.kind != CXCursor_OverloadedDeclRef)
6150 return clang_getNullCursor();
6151
6152 if (index >= clang_getNumOverloadedDecls(cursor))
6153 return clang_getNullCursor();
6154
6155 CXTranslationUnit TU = getCursorTU(cursor);
6156 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006157 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 return MakeCXCursor(E->decls_begin()[index], TU);
6159
6160 if (OverloadedTemplateStorage *S
6161 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6162 return MakeCXCursor(S->begin()[index], TU);
6163
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006164 const Decl *D = Storage.get<const Decl *>();
6165 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006166 // FIXME: This is, unfortunately, linear time.
6167 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6168 std::advance(Pos, index);
6169 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6170 }
6171
6172 return clang_getNullCursor();
6173}
6174
6175void clang_getDefinitionSpellingAndExtent(CXCursor C,
6176 const char **startBuf,
6177 const char **endBuf,
6178 unsigned *startLine,
6179 unsigned *startColumn,
6180 unsigned *endLine,
6181 unsigned *endColumn) {
6182 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006183 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006184 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6185
6186 SourceManager &SM = FD->getASTContext().getSourceManager();
6187 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6188 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6189 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6190 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6191 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6192 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6193}
6194
6195
6196CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6197 unsigned PieceIndex) {
6198 RefNamePieces Pieces;
6199
6200 switch (C.kind) {
6201 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006202 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006203 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6204 E->getQualifierLoc().getSourceRange());
6205 break;
6206
6207 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006208 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6209 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6210 Pieces =
6211 buildPieces(NameFlags, false, E->getNameInfo(),
6212 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6213 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006214 break;
6215
6216 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006217 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006218 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006219 const Expr *Callee = OCE->getCallee();
6220 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006221 Callee = ICE->getSubExpr();
6222
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006223 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6225 DRE->getQualifierLoc().getSourceRange());
6226 }
6227 break;
6228
6229 default:
6230 break;
6231 }
6232
6233 if (Pieces.empty()) {
6234 if (PieceIndex == 0)
6235 return clang_getCursorExtent(C);
6236 } else if (PieceIndex < Pieces.size()) {
6237 SourceRange R = Pieces[PieceIndex];
6238 if (R.isValid())
6239 return cxloc::translateSourceRange(getCursorContext(C), R);
6240 }
6241
6242 return clang_getNullRange();
6243}
6244
6245void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006246 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6247 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006248}
6249
6250void clang_executeOnThread(void (*fn)(void*), void *user_data,
6251 unsigned stack_size) {
6252 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6253}
6254
Guy Benyei11169dd2012-12-18 14:30:41 +00006255//===----------------------------------------------------------------------===//
6256// Token-based Operations.
6257//===----------------------------------------------------------------------===//
6258
6259/* CXToken layout:
6260 * int_data[0]: a CXTokenKind
6261 * int_data[1]: starting token location
6262 * int_data[2]: token length
6263 * int_data[3]: reserved
6264 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6265 * otherwise unused.
6266 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006267CXTokenKind clang_getTokenKind(CXToken CXTok) {
6268 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6269}
6270
6271CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6272 switch (clang_getTokenKind(CXTok)) {
6273 case CXToken_Identifier:
6274 case CXToken_Keyword:
6275 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006276 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006277 ->getNameStart());
6278
6279 case CXToken_Literal: {
6280 // We have stashed the starting pointer in the ptr_data field. Use it.
6281 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006282 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 }
6284
6285 case CXToken_Punctuation:
6286 case CXToken_Comment:
6287 break;
6288 }
6289
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006290 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006291 LOG_BAD_TU(TU);
6292 return cxstring::createEmpty();
6293 }
6294
Guy Benyei11169dd2012-12-18 14:30:41 +00006295 // We have to find the starting buffer pointer the hard way, by
6296 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006297 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006298 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006299 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006300
6301 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6302 std::pair<FileID, unsigned> LocInfo
6303 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6304 bool Invalid = false;
6305 StringRef Buffer
6306 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6307 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006308 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006309
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006310 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006311}
6312
6313CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006314 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006315 LOG_BAD_TU(TU);
6316 return clang_getNullLocation();
6317 }
6318
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006319 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006320 if (!CXXUnit)
6321 return clang_getNullLocation();
6322
6323 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6324 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6325}
6326
6327CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006328 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006329 LOG_BAD_TU(TU);
6330 return clang_getNullRange();
6331 }
6332
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006333 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006334 if (!CXXUnit)
6335 return clang_getNullRange();
6336
6337 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6338 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6339}
6340
6341static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6342 SmallVectorImpl<CXToken> &CXTokens) {
6343 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6344 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006345 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006346 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006347 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006348
6349 // Cannot tokenize across files.
6350 if (BeginLocInfo.first != EndLocInfo.first)
6351 return;
6352
6353 // Create a lexer
6354 bool Invalid = false;
6355 StringRef Buffer
6356 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6357 if (Invalid)
6358 return;
6359
6360 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6361 CXXUnit->getASTContext().getLangOpts(),
6362 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6363 Lex.SetCommentRetentionState(true);
6364
6365 // Lex tokens until we hit the end of the range.
6366 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6367 Token Tok;
6368 bool previousWasAt = false;
6369 do {
6370 // Lex the next token
6371 Lex.LexFromRawLexer(Tok);
6372 if (Tok.is(tok::eof))
6373 break;
6374
6375 // Initialize the CXToken.
6376 CXToken CXTok;
6377
6378 // - Common fields
6379 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6380 CXTok.int_data[2] = Tok.getLength();
6381 CXTok.int_data[3] = 0;
6382
6383 // - Kind-specific fields
6384 if (Tok.isLiteral()) {
6385 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006386 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006387 } else if (Tok.is(tok::raw_identifier)) {
6388 // Lookup the identifier to determine whether we have a keyword.
6389 IdentifierInfo *II
6390 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6391
6392 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6393 CXTok.int_data[0] = CXToken_Keyword;
6394 }
6395 else {
6396 CXTok.int_data[0] = Tok.is(tok::identifier)
6397 ? CXToken_Identifier
6398 : CXToken_Keyword;
6399 }
6400 CXTok.ptr_data = II;
6401 } else if (Tok.is(tok::comment)) {
6402 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006403 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006404 } else {
6405 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006406 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006407 }
6408 CXTokens.push_back(CXTok);
6409 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006410 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006411}
6412
6413void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6414 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006415 LOG_FUNC_SECTION {
6416 *Log << TU << ' ' << Range;
6417 }
6418
Guy Benyei11169dd2012-12-18 14:30:41 +00006419 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006420 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006421 if (NumTokens)
6422 *NumTokens = 0;
6423
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006424 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006425 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006426 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006427 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006428
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006429 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006430 if (!CXXUnit || !Tokens || !NumTokens)
6431 return;
6432
6433 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6434
6435 SourceRange R = cxloc::translateCXSourceRange(Range);
6436 if (R.isInvalid())
6437 return;
6438
6439 SmallVector<CXToken, 32> CXTokens;
6440 getTokens(CXXUnit, R, CXTokens);
6441
6442 if (CXTokens.empty())
6443 return;
6444
6445 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6446 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6447 *NumTokens = CXTokens.size();
6448}
6449
6450void clang_disposeTokens(CXTranslationUnit TU,
6451 CXToken *Tokens, unsigned NumTokens) {
6452 free(Tokens);
6453}
6454
Guy Benyei11169dd2012-12-18 14:30:41 +00006455//===----------------------------------------------------------------------===//
6456// Token annotation APIs.
6457//===----------------------------------------------------------------------===//
6458
Guy Benyei11169dd2012-12-18 14:30:41 +00006459static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6460 CXCursor parent,
6461 CXClientData client_data);
6462static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6463 CXClientData client_data);
6464
6465namespace {
6466class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006467 CXToken *Tokens;
6468 CXCursor *Cursors;
6469 unsigned NumTokens;
6470 unsigned TokIdx;
6471 unsigned PreprocessingTokIdx;
6472 CursorVisitor AnnotateVis;
6473 SourceManager &SrcMgr;
6474 bool HasContextSensitiveKeywords;
6475
6476 struct PostChildrenInfo {
6477 CXCursor Cursor;
6478 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006479 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006480 unsigned BeforeChildrenTokenIdx;
6481 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006482 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006483
6484 CXToken &getTok(unsigned Idx) {
6485 assert(Idx < NumTokens);
6486 return Tokens[Idx];
6487 }
6488 const CXToken &getTok(unsigned Idx) const {
6489 assert(Idx < NumTokens);
6490 return Tokens[Idx];
6491 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006492 bool MoreTokens() const { return TokIdx < NumTokens; }
6493 unsigned NextToken() const { return TokIdx; }
6494 void AdvanceToken() { ++TokIdx; }
6495 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006496 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006497 }
6498 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006499 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006500 }
6501 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006502 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006503 }
6504
6505 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006506 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006507 SourceRange);
6508
6509public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006510 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006511 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006512 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006513 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006514 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006515 AnnotateTokensVisitor, this,
6516 /*VisitPreprocessorLast=*/true,
6517 /*VisitIncludedEntities=*/false,
6518 RegionOfInterest,
6519 /*VisitDeclsOnly=*/false,
6520 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006521 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006522 HasContextSensitiveKeywords(false) { }
6523
6524 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6525 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6526 bool postVisitChildren(CXCursor cursor);
6527 void AnnotateTokens();
6528
6529 /// \brief Determine whether the annotator saw any cursors that have
6530 /// context-sensitive keywords.
6531 bool hasContextSensitiveKeywords() const {
6532 return HasContextSensitiveKeywords;
6533 }
6534
6535 ~AnnotateTokensWorker() {
6536 assert(PostChildrenInfos.empty());
6537 }
6538};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006539}
Guy Benyei11169dd2012-12-18 14:30:41 +00006540
6541void AnnotateTokensWorker::AnnotateTokens() {
6542 // Walk the AST within the region of interest, annotating tokens
6543 // along the way.
6544 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006545}
Guy Benyei11169dd2012-12-18 14:30:41 +00006546
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006547static inline void updateCursorAnnotation(CXCursor &Cursor,
6548 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006549 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006550 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006551 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006552}
6553
6554/// \brief It annotates and advances tokens with a cursor until the comparison
6555//// between the cursor location and the source range is the same as
6556/// \arg compResult.
6557///
6558/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6559/// Pass RangeOverlap to annotate tokens inside a range.
6560void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6561 RangeComparisonResult compResult,
6562 SourceRange range) {
6563 while (MoreTokens()) {
6564 const unsigned I = NextToken();
6565 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006566 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6567 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006568
6569 SourceLocation TokLoc = GetTokenLoc(I);
6570 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006571 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006572 AdvanceToken();
6573 continue;
6574 }
6575 break;
6576 }
6577}
6578
6579/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006580/// \returns true if it advanced beyond all macro tokens, false otherwise.
6581bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006582 CXCursor updateC,
6583 RangeComparisonResult compResult,
6584 SourceRange range) {
6585 assert(MoreTokens());
6586 assert(isFunctionMacroToken(NextToken()) &&
6587 "Should be called only for macro arg tokens");
6588
6589 // This works differently than annotateAndAdvanceTokens; because expanded
6590 // macro arguments can have arbitrary translation-unit source order, we do not
6591 // advance the token index one by one until a token fails the range test.
6592 // We only advance once past all of the macro arg tokens if all of them
6593 // pass the range test. If one of them fails we keep the token index pointing
6594 // at the start of the macro arg tokens so that the failing token will be
6595 // annotated by a subsequent annotation try.
6596
6597 bool atLeastOneCompFail = false;
6598
6599 unsigned I = NextToken();
6600 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6601 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6602 if (TokLoc.isFileID())
6603 continue; // not macro arg token, it's parens or comma.
6604 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6605 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6606 Cursors[I] = updateC;
6607 } else
6608 atLeastOneCompFail = true;
6609 }
6610
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006611 if (atLeastOneCompFail)
6612 return false;
6613
6614 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6615 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006616}
6617
6618enum CXChildVisitResult
6619AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006620 SourceRange cursorRange = getRawCursorExtent(cursor);
6621 if (cursorRange.isInvalid())
6622 return CXChildVisit_Recurse;
6623
6624 if (!HasContextSensitiveKeywords) {
6625 // Objective-C properties can have context-sensitive keywords.
6626 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006627 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6629 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6630 }
6631 // Objective-C methods can have context-sensitive keywords.
6632 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6633 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006634 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6636 if (Method->getObjCDeclQualifier())
6637 HasContextSensitiveKeywords = true;
6638 else {
David Majnemer59f77922016-06-24 04:05:48 +00006639 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006640 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006641 HasContextSensitiveKeywords = true;
6642 break;
6643 }
6644 }
6645 }
6646 }
6647 }
6648 // C++ methods can have context-sensitive keywords.
6649 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006650 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006651 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6652 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6653 HasContextSensitiveKeywords = true;
6654 }
6655 }
6656 // C++ classes can have context-sensitive keywords.
6657 else if (cursor.kind == CXCursor_StructDecl ||
6658 cursor.kind == CXCursor_ClassDecl ||
6659 cursor.kind == CXCursor_ClassTemplate ||
6660 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006661 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006662 if (D->hasAttr<FinalAttr>())
6663 HasContextSensitiveKeywords = true;
6664 }
6665 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006666
6667 // Don't override a property annotation with its getter/setter method.
6668 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6669 parent.kind == CXCursor_ObjCPropertyDecl)
6670 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006671
6672 if (clang_isPreprocessing(cursor.kind)) {
6673 // Items in the preprocessing record are kept separate from items in
6674 // declarations, so we keep a separate token index.
6675 unsigned SavedTokIdx = TokIdx;
6676 TokIdx = PreprocessingTokIdx;
6677
6678 // Skip tokens up until we catch up to the beginning of the preprocessing
6679 // entry.
6680 while (MoreTokens()) {
6681 const unsigned I = NextToken();
6682 SourceLocation TokLoc = GetTokenLoc(I);
6683 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6684 case RangeBefore:
6685 AdvanceToken();
6686 continue;
6687 case RangeAfter:
6688 case RangeOverlap:
6689 break;
6690 }
6691 break;
6692 }
6693
6694 // Look at all of the tokens within this range.
6695 while (MoreTokens()) {
6696 const unsigned I = NextToken();
6697 SourceLocation TokLoc = GetTokenLoc(I);
6698 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6699 case RangeBefore:
6700 llvm_unreachable("Infeasible");
6701 case RangeAfter:
6702 break;
6703 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006704 // For macro expansions, just note where the beginning of the macro
6705 // expansion occurs.
6706 if (cursor.kind == CXCursor_MacroExpansion) {
6707 if (TokLoc == cursorRange.getBegin())
6708 Cursors[I] = cursor;
6709 AdvanceToken();
6710 break;
6711 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006712 // We may have already annotated macro names inside macro definitions.
6713 if (Cursors[I].kind != CXCursor_MacroExpansion)
6714 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006715 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006716 continue;
6717 }
6718 break;
6719 }
6720
6721 // Save the preprocessing token index; restore the non-preprocessing
6722 // token index.
6723 PreprocessingTokIdx = TokIdx;
6724 TokIdx = SavedTokIdx;
6725 return CXChildVisit_Recurse;
6726 }
6727
6728 if (cursorRange.isInvalid())
6729 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006730
6731 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006732 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006733 const enum CXCursorKind K = clang_getCursorKind(parent);
6734 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006735 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6736 // Attributes are annotated out-of-order, skip tokens until we reach it.
6737 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006738 ? clang_getNullCursor() : parent;
6739
6740 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6741
6742 // Avoid having the cursor of an expression "overwrite" the annotation of the
6743 // variable declaration that it belongs to.
6744 // This can happen for C++ constructor expressions whose range generally
6745 // include the variable declaration, e.g.:
6746 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006747 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006748 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006749 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006750 const unsigned I = NextToken();
6751 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6752 E->getLocStart() == D->getLocation() &&
6753 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006754 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006755 AdvanceToken();
6756 }
6757 }
6758 }
6759
6760 // Before recursing into the children keep some state that we are going
6761 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6762 // extra work after the child nodes are visited.
6763 // Note that we don't call VisitChildren here to avoid traversing statements
6764 // code-recursively which can blow the stack.
6765
6766 PostChildrenInfo Info;
6767 Info.Cursor = cursor;
6768 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006769 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006770 Info.BeforeChildrenTokenIdx = NextToken();
6771 PostChildrenInfos.push_back(Info);
6772
6773 return CXChildVisit_Recurse;
6774}
6775
6776bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6777 if (PostChildrenInfos.empty())
6778 return false;
6779 const PostChildrenInfo &Info = PostChildrenInfos.back();
6780 if (!clang_equalCursors(Info.Cursor, cursor))
6781 return false;
6782
6783 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6784 const unsigned AfterChildren = NextToken();
6785 SourceRange cursorRange = Info.CursorRange;
6786
6787 // Scan the tokens that are at the end of the cursor, but are not captured
6788 // but the child cursors.
6789 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6790
6791 // Scan the tokens that are at the beginning of the cursor, but are not
6792 // capture by the child cursors.
6793 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6794 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6795 break;
6796
6797 Cursors[I] = cursor;
6798 }
6799
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006800 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6801 // encountered the attribute cursor.
6802 if (clang_isAttribute(cursor.kind))
6803 TokIdx = Info.BeforeReachingCursorIdx;
6804
Guy Benyei11169dd2012-12-18 14:30:41 +00006805 PostChildrenInfos.pop_back();
6806 return false;
6807}
6808
6809static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6810 CXCursor parent,
6811 CXClientData client_data) {
6812 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6813}
6814
6815static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6816 CXClientData client_data) {
6817 return static_cast<AnnotateTokensWorker*>(client_data)->
6818 postVisitChildren(cursor);
6819}
6820
6821namespace {
6822
6823/// \brief Uses the macro expansions in the preprocessing record to find
6824/// and mark tokens that are macro arguments. This info is used by the
6825/// AnnotateTokensWorker.
6826class MarkMacroArgTokensVisitor {
6827 SourceManager &SM;
6828 CXToken *Tokens;
6829 unsigned NumTokens;
6830 unsigned CurIdx;
6831
6832public:
6833 MarkMacroArgTokensVisitor(SourceManager &SM,
6834 CXToken *tokens, unsigned numTokens)
6835 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6836
6837 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6838 if (cursor.kind != CXCursor_MacroExpansion)
6839 return CXChildVisit_Continue;
6840
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006841 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006842 if (macroRange.getBegin() == macroRange.getEnd())
6843 return CXChildVisit_Continue; // it's not a function macro.
6844
6845 for (; CurIdx < NumTokens; ++CurIdx) {
6846 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6847 macroRange.getBegin()))
6848 break;
6849 }
6850
6851 if (CurIdx == NumTokens)
6852 return CXChildVisit_Break;
6853
6854 for (; CurIdx < NumTokens; ++CurIdx) {
6855 SourceLocation tokLoc = getTokenLoc(CurIdx);
6856 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6857 break;
6858
6859 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6860 }
6861
6862 if (CurIdx == NumTokens)
6863 return CXChildVisit_Break;
6864
6865 return CXChildVisit_Continue;
6866 }
6867
6868private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006869 CXToken &getTok(unsigned Idx) {
6870 assert(Idx < NumTokens);
6871 return Tokens[Idx];
6872 }
6873 const CXToken &getTok(unsigned Idx) const {
6874 assert(Idx < NumTokens);
6875 return Tokens[Idx];
6876 }
6877
Guy Benyei11169dd2012-12-18 14:30:41 +00006878 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006879 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006880 }
6881
6882 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6883 // The third field is reserved and currently not used. Use it here
6884 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006885 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006886 }
6887};
6888
6889} // end anonymous namespace
6890
6891static CXChildVisitResult
6892MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6893 CXClientData client_data) {
6894 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6895 parent);
6896}
6897
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006898/// \brief Used by \c annotatePreprocessorTokens.
6899/// \returns true if lexing was finished, false otherwise.
6900static bool lexNext(Lexer &Lex, Token &Tok,
6901 unsigned &NextIdx, unsigned NumTokens) {
6902 if (NextIdx >= NumTokens)
6903 return true;
6904
6905 ++NextIdx;
6906 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006907 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006908}
6909
Guy Benyei11169dd2012-12-18 14:30:41 +00006910static void annotatePreprocessorTokens(CXTranslationUnit TU,
6911 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006912 CXCursor *Cursors,
6913 CXToken *Tokens,
6914 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006915 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006916
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006917 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006918 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6919 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006920 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006921 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006922 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006923
6924 if (BeginLocInfo.first != EndLocInfo.first)
6925 return;
6926
6927 StringRef Buffer;
6928 bool Invalid = false;
6929 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6930 if (Buffer.empty() || Invalid)
6931 return;
6932
6933 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6934 CXXUnit->getASTContext().getLangOpts(),
6935 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6936 Buffer.end());
6937 Lex.SetCommentRetentionState(true);
6938
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006939 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006940 // Lex tokens in raw mode until we hit the end of the range, to avoid
6941 // entering #includes or expanding macros.
6942 while (true) {
6943 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006944 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6945 break;
6946 unsigned TokIdx = NextIdx-1;
6947 assert(Tok.getLocation() ==
6948 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006949
6950 reprocess:
6951 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006952 // We have found a preprocessing directive. Annotate the tokens
6953 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006954 //
6955 // FIXME: Some simple tests here could identify macro definitions and
6956 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006957
6958 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006959 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6960 break;
6961
Craig Topper69186e72014-06-08 08:38:04 +00006962 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006963 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006964 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6965 break;
6966
6967 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006968 IdentifierInfo &II =
6969 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006970 SourceLocation MappedTokLoc =
6971 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6972 MI = getMacroInfo(II, MappedTokLoc, TU);
6973 }
6974 }
6975
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006976 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006977 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006978 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6979 finished = true;
6980 break;
6981 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006982 // If we are in a macro definition, check if the token was ever a
6983 // macro name and annotate it if that's the case.
6984 if (MI) {
6985 SourceLocation SaveLoc = Tok.getLocation();
6986 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006987 MacroDefinitionRecord *MacroDef =
6988 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006989 Tok.setLocation(SaveLoc);
6990 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00006991 Cursors[NextIdx - 1] =
6992 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006993 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006994 } while (!Tok.isAtStartOfLine());
6995
6996 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6997 assert(TokIdx <= LastIdx);
6998 SourceLocation EndLoc =
6999 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7000 CXCursor Cursor =
7001 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7002
7003 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007004 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007005
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007006 if (finished)
7007 break;
7008 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007009 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007010 }
7011}
7012
7013// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007014static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7015 CXToken *Tokens, unsigned NumTokens,
7016 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007017 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007018 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7019 setThreadBackgroundPriority();
7020
7021 // Determine the region of interest, which contains all of the tokens.
7022 SourceRange RegionOfInterest;
7023 RegionOfInterest.setBegin(
7024 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7025 RegionOfInterest.setEnd(
7026 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7027 Tokens[NumTokens-1])));
7028
Guy Benyei11169dd2012-12-18 14:30:41 +00007029 // Relex the tokens within the source range to look for preprocessing
7030 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007031 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007032
7033 // If begin location points inside a macro argument, set it to the expansion
7034 // location so we can have the full context when annotating semantically.
7035 {
7036 SourceManager &SM = CXXUnit->getSourceManager();
7037 SourceLocation Loc =
7038 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7039 if (Loc.isMacroID())
7040 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7041 }
7042
Guy Benyei11169dd2012-12-18 14:30:41 +00007043 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7044 // Search and mark tokens that are macro argument expansions.
7045 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7046 Tokens, NumTokens);
7047 CursorVisitor MacroArgMarker(TU,
7048 MarkMacroArgTokensVisitorDelegate, &Visitor,
7049 /*VisitPreprocessorLast=*/true,
7050 /*VisitIncludedEntities=*/false,
7051 RegionOfInterest);
7052 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7053 }
7054
7055 // Annotate all of the source locations in the region of interest that map to
7056 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007057 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007058
7059 // FIXME: We use a ridiculous stack size here because the data-recursion
7060 // algorithm uses a large stack frame than the non-data recursive version,
7061 // and AnnotationTokensWorker currently transforms the data-recursion
7062 // algorithm back into a traditional recursion by explicitly calling
7063 // VisitChildren(). We will need to remove this explicit recursive call.
7064 W.AnnotateTokens();
7065
7066 // If we ran into any entities that involve context-sensitive keywords,
7067 // take another pass through the tokens to mark them as such.
7068 if (W.hasContextSensitiveKeywords()) {
7069 for (unsigned I = 0; I != NumTokens; ++I) {
7070 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7071 continue;
7072
7073 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7074 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007075 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007076 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7077 if (Property->getPropertyAttributesAsWritten() != 0 &&
7078 llvm::StringSwitch<bool>(II->getName())
7079 .Case("readonly", true)
7080 .Case("assign", true)
7081 .Case("unsafe_unretained", true)
7082 .Case("readwrite", true)
7083 .Case("retain", true)
7084 .Case("copy", true)
7085 .Case("nonatomic", true)
7086 .Case("atomic", true)
7087 .Case("getter", true)
7088 .Case("setter", true)
7089 .Case("strong", true)
7090 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007091 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007092 .Default(false))
7093 Tokens[I].int_data[0] = CXToken_Keyword;
7094 }
7095 continue;
7096 }
7097
7098 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7099 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7100 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7101 if (llvm::StringSwitch<bool>(II->getName())
7102 .Case("in", true)
7103 .Case("out", true)
7104 .Case("inout", true)
7105 .Case("oneway", true)
7106 .Case("bycopy", true)
7107 .Case("byref", true)
7108 .Default(false))
7109 Tokens[I].int_data[0] = CXToken_Keyword;
7110 continue;
7111 }
7112
7113 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7114 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7115 Tokens[I].int_data[0] = CXToken_Keyword;
7116 continue;
7117 }
7118 }
7119 }
7120}
7121
Guy Benyei11169dd2012-12-18 14:30:41 +00007122void clang_annotateTokens(CXTranslationUnit TU,
7123 CXToken *Tokens, unsigned NumTokens,
7124 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007125 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007126 LOG_BAD_TU(TU);
7127 return;
7128 }
7129 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007130 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007131 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007132 }
7133
7134 LOG_FUNC_SECTION {
7135 *Log << TU << ' ';
7136 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7137 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7138 *Log << clang_getRange(bloc, eloc);
7139 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007140
7141 // Any token we don't specifically annotate will have a NULL cursor.
7142 CXCursor C = clang_getNullCursor();
7143 for (unsigned I = 0; I != NumTokens; ++I)
7144 Cursors[I] = C;
7145
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007146 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007147 if (!CXXUnit)
7148 return;
7149
7150 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007151
7152 auto AnnotateTokensImpl = [=]() {
7153 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7154 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007155 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007156 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007157 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7158 }
7159}
7160
Guy Benyei11169dd2012-12-18 14:30:41 +00007161//===----------------------------------------------------------------------===//
7162// Operations for querying linkage of a cursor.
7163//===----------------------------------------------------------------------===//
7164
Guy Benyei11169dd2012-12-18 14:30:41 +00007165CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7166 if (!clang_isDeclaration(cursor.kind))
7167 return CXLinkage_Invalid;
7168
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007169 const Decl *D = cxcursor::getCursorDecl(cursor);
7170 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007171 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007172 case NoLinkage:
7173 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007174 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007175 case InternalLinkage: return CXLinkage_Internal;
7176 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007177 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007178 case ExternalLinkage: return CXLinkage_External;
7179 };
7180
7181 return CXLinkage_Invalid;
7182}
Guy Benyei11169dd2012-12-18 14:30:41 +00007183
7184//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007185// Operations for querying visibility of a cursor.
7186//===----------------------------------------------------------------------===//
7187
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007188CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7189 if (!clang_isDeclaration(cursor.kind))
7190 return CXVisibility_Invalid;
7191
7192 const Decl *D = cxcursor::getCursorDecl(cursor);
7193 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7194 switch (ND->getVisibility()) {
7195 case HiddenVisibility: return CXVisibility_Hidden;
7196 case ProtectedVisibility: return CXVisibility_Protected;
7197 case DefaultVisibility: return CXVisibility_Default;
7198 };
7199
7200 return CXVisibility_Invalid;
7201}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007202
7203//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007204// Operations for querying language of a cursor.
7205//===----------------------------------------------------------------------===//
7206
7207static CXLanguageKind getDeclLanguage(const Decl *D) {
7208 if (!D)
7209 return CXLanguage_C;
7210
7211 switch (D->getKind()) {
7212 default:
7213 break;
7214 case Decl::ImplicitParam:
7215 case Decl::ObjCAtDefsField:
7216 case Decl::ObjCCategory:
7217 case Decl::ObjCCategoryImpl:
7218 case Decl::ObjCCompatibleAlias:
7219 case Decl::ObjCImplementation:
7220 case Decl::ObjCInterface:
7221 case Decl::ObjCIvar:
7222 case Decl::ObjCMethod:
7223 case Decl::ObjCProperty:
7224 case Decl::ObjCPropertyImpl:
7225 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007226 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007227 return CXLanguage_ObjC;
7228 case Decl::CXXConstructor:
7229 case Decl::CXXConversion:
7230 case Decl::CXXDestructor:
7231 case Decl::CXXMethod:
7232 case Decl::CXXRecord:
7233 case Decl::ClassTemplate:
7234 case Decl::ClassTemplatePartialSpecialization:
7235 case Decl::ClassTemplateSpecialization:
7236 case Decl::Friend:
7237 case Decl::FriendTemplate:
7238 case Decl::FunctionTemplate:
7239 case Decl::LinkageSpec:
7240 case Decl::Namespace:
7241 case Decl::NamespaceAlias:
7242 case Decl::NonTypeTemplateParm:
7243 case Decl::StaticAssert:
7244 case Decl::TemplateTemplateParm:
7245 case Decl::TemplateTypeParm:
7246 case Decl::UnresolvedUsingTypename:
7247 case Decl::UnresolvedUsingValue:
7248 case Decl::Using:
7249 case Decl::UsingDirective:
7250 case Decl::UsingShadow:
7251 return CXLanguage_CPlusPlus;
7252 }
7253
7254 return CXLanguage_C;
7255}
7256
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007257static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7258 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007259 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007260
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007261 switch (D->getAvailability()) {
7262 case AR_Available:
7263 case AR_NotYetIntroduced:
7264 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007265 return getCursorAvailabilityForDecl(
7266 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007267 return CXAvailability_Available;
7268
7269 case AR_Deprecated:
7270 return CXAvailability_Deprecated;
7271
7272 case AR_Unavailable:
7273 return CXAvailability_NotAvailable;
7274 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007275
7276 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007277}
7278
Guy Benyei11169dd2012-12-18 14:30:41 +00007279enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7280 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007281 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7282 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007283
7284 return CXAvailability_Available;
7285}
7286
7287static CXVersion convertVersion(VersionTuple In) {
7288 CXVersion Out = { -1, -1, -1 };
7289 if (In.empty())
7290 return Out;
7291
7292 Out.Major = In.getMajor();
7293
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007294 Optional<unsigned> Minor = In.getMinor();
7295 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007296 Out.Minor = *Minor;
7297 else
7298 return Out;
7299
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007300 Optional<unsigned> Subminor = In.getSubminor();
7301 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007302 Out.Subminor = *Subminor;
7303
7304 return Out;
7305}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007306
Alex Lorenz1345ea22017-06-12 19:06:30 +00007307static void getCursorPlatformAvailabilityForDecl(
7308 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7309 int *always_unavailable, CXString *unavailable_message,
7310 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007311 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007312 for (auto A : D->attrs()) {
7313 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007314 HadAvailAttr = true;
7315 if (always_deprecated)
7316 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007317 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007318 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007319 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007320 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007321 continue;
7322 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007323
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007324 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007325 HadAvailAttr = true;
7326 if (always_unavailable)
7327 *always_unavailable = 1;
7328 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007329 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007330 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7331 }
7332 continue;
7333 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007334
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007335 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007336 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007337 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007338 }
7339 }
7340
7341 if (!HadAvailAttr)
7342 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7343 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007344 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7345 deprecated_message, always_unavailable, unavailable_message,
7346 AvailabilityAttrs);
7347
7348 if (AvailabilityAttrs.empty())
7349 return;
7350
7351 std::sort(AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7352 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
Reid Klecknere6cde142017-08-04 21:52:25 +00007353 return LHS->getPlatform()->getName() <
7354 RHS->getPlatform()->getName();
Alex Lorenz1345ea22017-06-12 19:06:30 +00007355 });
7356 ASTContext &Ctx = D->getASTContext();
7357 auto It = std::unique(
7358 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7359 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7360 if (LHS->getPlatform() != RHS->getPlatform())
7361 return false;
7362
7363 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7364 LHS->getDeprecated() == RHS->getDeprecated() &&
7365 LHS->getObsoleted() == RHS->getObsoleted() &&
7366 LHS->getMessage() == RHS->getMessage() &&
7367 LHS->getReplacement() == RHS->getReplacement())
7368 return true;
7369
7370 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7371 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7372 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7373 return false;
7374
7375 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7376 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7377
7378 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7379 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7380 if (LHS->getMessage().empty())
7381 LHS->setMessage(Ctx, RHS->getMessage());
7382 if (LHS->getReplacement().empty())
7383 LHS->setReplacement(Ctx, RHS->getReplacement());
7384 }
7385
7386 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7387 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7388 if (LHS->getMessage().empty())
7389 LHS->setMessage(Ctx, RHS->getMessage());
7390 if (LHS->getReplacement().empty())
7391 LHS->setReplacement(Ctx, RHS->getReplacement());
7392 }
7393
7394 return true;
7395 });
7396 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007397}
7398
Alex Lorenz1345ea22017-06-12 19:06:30 +00007399int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007400 CXString *deprecated_message,
7401 int *always_unavailable,
7402 CXString *unavailable_message,
7403 CXPlatformAvailability *availability,
7404 int availability_size) {
7405 if (always_deprecated)
7406 *always_deprecated = 0;
7407 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007408 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007409 if (always_unavailable)
7410 *always_unavailable = 0;
7411 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007412 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007413
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 if (!clang_isDeclaration(cursor.kind))
7415 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007416
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007417 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007418 if (!D)
7419 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007420
Alex Lorenz1345ea22017-06-12 19:06:30 +00007421 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7422 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7423 always_unavailable, unavailable_message,
7424 AvailabilityAttrs);
7425 for (const auto &Avail :
7426 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7427 .take_front(availability_size))) {
7428 availability[Avail.index()].Platform =
7429 cxstring::createDup(Avail.value()->getPlatform()->getName());
7430 availability[Avail.index()].Introduced =
7431 convertVersion(Avail.value()->getIntroduced());
7432 availability[Avail.index()].Deprecated =
7433 convertVersion(Avail.value()->getDeprecated());
7434 availability[Avail.index()].Obsoleted =
7435 convertVersion(Avail.value()->getObsoleted());
7436 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7437 availability[Avail.index()].Message =
7438 cxstring::createDup(Avail.value()->getMessage());
7439 }
7440
7441 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007442}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007443
Guy Benyei11169dd2012-12-18 14:30:41 +00007444void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7445 clang_disposeString(availability->Platform);
7446 clang_disposeString(availability->Message);
7447}
7448
7449CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7450 if (clang_isDeclaration(cursor.kind))
7451 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7452
7453 return CXLanguage_Invalid;
7454}
7455
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007456CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7457 const Decl *D = cxcursor::getCursorDecl(cursor);
7458 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7459 switch (VD->getTLSKind()) {
7460 case VarDecl::TLS_None:
7461 return CXTLS_None;
7462 case VarDecl::TLS_Dynamic:
7463 return CXTLS_Dynamic;
7464 case VarDecl::TLS_Static:
7465 return CXTLS_Static;
7466 }
7467 }
7468
7469 return CXTLS_None;
7470}
7471
Guy Benyei11169dd2012-12-18 14:30:41 +00007472 /// \brief If the given cursor is the "templated" declaration
7473 /// descibing a class or function template, return the class or
7474 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007475static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007476 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007477 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007478
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007479 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007480 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7481 return FunTmpl;
7482
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007483 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007484 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7485 return ClassTmpl;
7486
7487 return D;
7488}
7489
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007490
7491enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7492 StorageClass sc = SC_None;
7493 const Decl *D = getCursorDecl(C);
7494 if (D) {
7495 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7496 sc = FD->getStorageClass();
7497 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7498 sc = VD->getStorageClass();
7499 } else {
7500 return CX_SC_Invalid;
7501 }
7502 } else {
7503 return CX_SC_Invalid;
7504 }
7505 switch (sc) {
7506 case SC_None:
7507 return CX_SC_None;
7508 case SC_Extern:
7509 return CX_SC_Extern;
7510 case SC_Static:
7511 return CX_SC_Static;
7512 case SC_PrivateExtern:
7513 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007514 case SC_Auto:
7515 return CX_SC_Auto;
7516 case SC_Register:
7517 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007518 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007519 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007520}
7521
Guy Benyei11169dd2012-12-18 14:30:41 +00007522CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7523 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007524 if (const Decl *D = getCursorDecl(cursor)) {
7525 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007526 if (!DC)
7527 return clang_getNullCursor();
7528
7529 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7530 getCursorTU(cursor));
7531 }
7532 }
7533
7534 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007535 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007536 return MakeCXCursor(D, getCursorTU(cursor));
7537 }
7538
7539 return clang_getNullCursor();
7540}
7541
7542CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7543 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007544 if (const Decl *D = getCursorDecl(cursor)) {
7545 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007546 if (!DC)
7547 return clang_getNullCursor();
7548
7549 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7550 getCursorTU(cursor));
7551 }
7552 }
7553
7554 // FIXME: Note that we can't easily compute the lexical context of a
7555 // statement or expression, so we return nothing.
7556 return clang_getNullCursor();
7557}
7558
7559CXFile clang_getIncludedFile(CXCursor cursor) {
7560 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007561 return nullptr;
7562
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007563 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007564 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007565}
7566
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007567unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7568 if (C.kind != CXCursor_ObjCPropertyDecl)
7569 return CXObjCPropertyAttr_noattr;
7570
7571 unsigned Result = CXObjCPropertyAttr_noattr;
7572 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7573 ObjCPropertyDecl::PropertyAttributeKind Attr =
7574 PD->getPropertyAttributesAsWritten();
7575
7576#define SET_CXOBJCPROP_ATTR(A) \
7577 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7578 Result |= CXObjCPropertyAttr_##A
7579 SET_CXOBJCPROP_ATTR(readonly);
7580 SET_CXOBJCPROP_ATTR(getter);
7581 SET_CXOBJCPROP_ATTR(assign);
7582 SET_CXOBJCPROP_ATTR(readwrite);
7583 SET_CXOBJCPROP_ATTR(retain);
7584 SET_CXOBJCPROP_ATTR(copy);
7585 SET_CXOBJCPROP_ATTR(nonatomic);
7586 SET_CXOBJCPROP_ATTR(setter);
7587 SET_CXOBJCPROP_ATTR(atomic);
7588 SET_CXOBJCPROP_ATTR(weak);
7589 SET_CXOBJCPROP_ATTR(strong);
7590 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007591 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007592#undef SET_CXOBJCPROP_ATTR
7593
7594 return Result;
7595}
7596
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007597unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7598 if (!clang_isDeclaration(C.kind))
7599 return CXObjCDeclQualifier_None;
7600
7601 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7602 const Decl *D = getCursorDecl(C);
7603 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7604 QT = MD->getObjCDeclQualifier();
7605 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7606 QT = PD->getObjCDeclQualifier();
7607 if (QT == Decl::OBJC_TQ_None)
7608 return CXObjCDeclQualifier_None;
7609
7610 unsigned Result = CXObjCDeclQualifier_None;
7611 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7612 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7613 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7614 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7615 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7616 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7617
7618 return Result;
7619}
7620
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007621unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7622 if (!clang_isDeclaration(C.kind))
7623 return 0;
7624
7625 const Decl *D = getCursorDecl(C);
7626 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7627 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7628 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7629 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7630
7631 return 0;
7632}
7633
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007634unsigned clang_Cursor_isVariadic(CXCursor C) {
7635 if (!clang_isDeclaration(C.kind))
7636 return 0;
7637
7638 const Decl *D = getCursorDecl(C);
7639 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7640 return FD->isVariadic();
7641 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7642 return MD->isVariadic();
7643
7644 return 0;
7645}
7646
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007647unsigned clang_Cursor_isExternalSymbol(CXCursor C,
7648 CXString *language, CXString *definedIn,
7649 unsigned *isGenerated) {
7650 if (!clang_isDeclaration(C.kind))
7651 return 0;
7652
7653 const Decl *D = getCursorDecl(C);
7654
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00007655 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007656 if (language)
7657 *language = cxstring::createDup(attr->getLanguage());
7658 if (definedIn)
7659 *definedIn = cxstring::createDup(attr->getDefinedIn());
7660 if (isGenerated)
7661 *isGenerated = attr->getGeneratedDeclaration();
7662 return 1;
7663 }
7664 return 0;
7665}
7666
Guy Benyei11169dd2012-12-18 14:30:41 +00007667CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7668 if (!clang_isDeclaration(C.kind))
7669 return clang_getNullRange();
7670
7671 const Decl *D = getCursorDecl(C);
7672 ASTContext &Context = getCursorContext(C);
7673 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7674 if (!RC)
7675 return clang_getNullRange();
7676
7677 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7678}
7679
7680CXString clang_Cursor_getRawCommentText(CXCursor C) {
7681 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007682 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007683
7684 const Decl *D = getCursorDecl(C);
7685 ASTContext &Context = getCursorContext(C);
7686 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7687 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7688 StringRef();
7689
7690 // Don't duplicate the string because RawText points directly into source
7691 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007692 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007693}
7694
7695CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7696 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007697 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007698
7699 const Decl *D = getCursorDecl(C);
7700 const ASTContext &Context = getCursorContext(C);
7701 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7702
7703 if (RC) {
7704 StringRef BriefText = RC->getBriefText(Context);
7705
7706 // Don't duplicate the string because RawComment ensures that this memory
7707 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007708 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007709 }
7710
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007711 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007712}
7713
Guy Benyei11169dd2012-12-18 14:30:41 +00007714CXModule clang_Cursor_getModule(CXCursor C) {
7715 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007716 if (const ImportDecl *ImportD =
7717 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 return ImportD->getImportedModule();
7719 }
7720
Craig Topper69186e72014-06-08 08:38:04 +00007721 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007722}
7723
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007724CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7725 if (isNotUsableTU(TU)) {
7726 LOG_BAD_TU(TU);
7727 return nullptr;
7728 }
7729 if (!File)
7730 return nullptr;
7731 FileEntry *FE = static_cast<FileEntry *>(File);
7732
7733 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7734 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7735 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7736
Richard Smithfeb54b62014-10-23 02:01:19 +00007737 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007738}
7739
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007740CXFile clang_Module_getASTFile(CXModule CXMod) {
7741 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007742 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007743 Module *Mod = static_cast<Module*>(CXMod);
7744 return const_cast<FileEntry *>(Mod->getASTFile());
7745}
7746
Guy Benyei11169dd2012-12-18 14:30:41 +00007747CXModule clang_Module_getParent(CXModule CXMod) {
7748 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007749 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007750 Module *Mod = static_cast<Module*>(CXMod);
7751 return Mod->Parent;
7752}
7753
7754CXString clang_Module_getName(CXModule CXMod) {
7755 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007756 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007757 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007758 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007759}
7760
7761CXString clang_Module_getFullName(CXModule CXMod) {
7762 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007763 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007764 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007765 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007766}
7767
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007768int clang_Module_isSystem(CXModule CXMod) {
7769 if (!CXMod)
7770 return 0;
7771 Module *Mod = static_cast<Module*>(CXMod);
7772 return Mod->IsSystem;
7773}
7774
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007775unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7776 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007777 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007778 LOG_BAD_TU(TU);
7779 return 0;
7780 }
7781 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007782 return 0;
7783 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007784 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7785 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7786 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007787}
7788
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007789CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7790 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007791 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007792 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007793 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007794 }
7795 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007796 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007797 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007798 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007799
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007800 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7801 if (Index < TopHeaders.size())
7802 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007803
Craig Topper69186e72014-06-08 08:38:04 +00007804 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007805}
7806
Guy Benyei11169dd2012-12-18 14:30:41 +00007807//===----------------------------------------------------------------------===//
7808// C++ AST instrospection.
7809//===----------------------------------------------------------------------===//
7810
Jonathan Coe29565352016-04-27 12:48:25 +00007811unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
7812 if (!clang_isDeclaration(C.kind))
7813 return 0;
7814
7815 const Decl *D = cxcursor::getCursorDecl(C);
7816 const CXXConstructorDecl *Constructor =
7817 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7818 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
7819}
7820
7821unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
7822 if (!clang_isDeclaration(C.kind))
7823 return 0;
7824
7825 const Decl *D = cxcursor::getCursorDecl(C);
7826 const CXXConstructorDecl *Constructor =
7827 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7828 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
7829}
7830
7831unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
7832 if (!clang_isDeclaration(C.kind))
7833 return 0;
7834
7835 const Decl *D = cxcursor::getCursorDecl(C);
7836 const CXXConstructorDecl *Constructor =
7837 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7838 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7839}
7840
7841unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7842 if (!clang_isDeclaration(C.kind))
7843 return 0;
7844
7845 const Decl *D = cxcursor::getCursorDecl(C);
7846 const CXXConstructorDecl *Constructor =
7847 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7848 // Passing 'false' excludes constructors marked 'explicit'.
7849 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7850}
7851
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007852unsigned clang_CXXField_isMutable(CXCursor C) {
7853 if (!clang_isDeclaration(C.kind))
7854 return 0;
7855
7856 if (const auto D = cxcursor::getCursorDecl(C))
7857 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7858 return FD->isMutable() ? 1 : 0;
7859 return 0;
7860}
7861
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007862unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7863 if (!clang_isDeclaration(C.kind))
7864 return 0;
7865
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007866 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007867 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007868 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007869 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7870}
7871
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007872unsigned clang_CXXMethod_isConst(CXCursor C) {
7873 if (!clang_isDeclaration(C.kind))
7874 return 0;
7875
7876 const Decl *D = cxcursor::getCursorDecl(C);
7877 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007878 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007879 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7880}
7881
Jonathan Coe29565352016-04-27 12:48:25 +00007882unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7883 if (!clang_isDeclaration(C.kind))
7884 return 0;
7885
7886 const Decl *D = cxcursor::getCursorDecl(C);
7887 const CXXMethodDecl *Method =
7888 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7889 return (Method && Method->isDefaulted()) ? 1 : 0;
7890}
7891
Guy Benyei11169dd2012-12-18 14:30:41 +00007892unsigned clang_CXXMethod_isStatic(CXCursor C) {
7893 if (!clang_isDeclaration(C.kind))
7894 return 0;
7895
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007896 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007897 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007898 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007899 return (Method && Method->isStatic()) ? 1 : 0;
7900}
7901
7902unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7903 if (!clang_isDeclaration(C.kind))
7904 return 0;
7905
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007906 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007907 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007908 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007909 return (Method && Method->isVirtual()) ? 1 : 0;
7910}
Guy Benyei11169dd2012-12-18 14:30:41 +00007911
Alex Lorenzff7f42e2017-07-12 11:35:11 +00007912unsigned clang_EnumDecl_isScoped(CXCursor C) {
7913 if (!clang_isDeclaration(C.kind))
7914 return 0;
7915
7916 const Decl *D = cxcursor::getCursorDecl(C);
7917 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
7918 return (Enum && Enum->isScoped()) ? 1 : 0;
7919}
7920
Guy Benyei11169dd2012-12-18 14:30:41 +00007921//===----------------------------------------------------------------------===//
7922// Attribute introspection.
7923//===----------------------------------------------------------------------===//
7924
Guy Benyei11169dd2012-12-18 14:30:41 +00007925CXType clang_getIBOutletCollectionType(CXCursor C) {
7926 if (C.kind != CXCursor_IBOutletCollectionAttr)
7927 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7928
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007929 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007930 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7931
7932 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7933}
Guy Benyei11169dd2012-12-18 14:30:41 +00007934
7935//===----------------------------------------------------------------------===//
7936// Inspecting memory usage.
7937//===----------------------------------------------------------------------===//
7938
7939typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7940
7941static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7942 enum CXTUResourceUsageKind k,
7943 unsigned long amount) {
7944 CXTUResourceUsageEntry entry = { k, amount };
7945 entries.push_back(entry);
7946}
7947
Guy Benyei11169dd2012-12-18 14:30:41 +00007948const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7949 const char *str = "";
7950 switch (kind) {
7951 case CXTUResourceUsage_AST:
7952 str = "ASTContext: expressions, declarations, and types";
7953 break;
7954 case CXTUResourceUsage_Identifiers:
7955 str = "ASTContext: identifiers";
7956 break;
7957 case CXTUResourceUsage_Selectors:
7958 str = "ASTContext: selectors";
7959 break;
7960 case CXTUResourceUsage_GlobalCompletionResults:
7961 str = "Code completion: cached global results";
7962 break;
7963 case CXTUResourceUsage_SourceManagerContentCache:
7964 str = "SourceManager: content cache allocator";
7965 break;
7966 case CXTUResourceUsage_AST_SideTables:
7967 str = "ASTContext: side tables";
7968 break;
7969 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7970 str = "SourceManager: malloc'ed memory buffers";
7971 break;
7972 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7973 str = "SourceManager: mmap'ed memory buffers";
7974 break;
7975 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7976 str = "ExternalASTSource: malloc'ed memory buffers";
7977 break;
7978 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
7979 str = "ExternalASTSource: mmap'ed memory buffers";
7980 break;
7981 case CXTUResourceUsage_Preprocessor:
7982 str = "Preprocessor: malloc'ed memory";
7983 break;
7984 case CXTUResourceUsage_PreprocessingRecord:
7985 str = "Preprocessor: PreprocessingRecord";
7986 break;
7987 case CXTUResourceUsage_SourceManager_DataStructures:
7988 str = "SourceManager: data structures and tables";
7989 break;
7990 case CXTUResourceUsage_Preprocessor_HeaderSearch:
7991 str = "Preprocessor: header search tables";
7992 break;
7993 }
7994 return str;
7995}
7996
7997CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007998 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007999 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008000 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 return usage;
8002 }
8003
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008004 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008005 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008006 ASTContext &astContext = astUnit->getASTContext();
8007
8008 // How much memory is used by AST nodes and types?
8009 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8010 (unsigned long) astContext.getASTAllocatedMemory());
8011
8012 // How much memory is used by identifiers?
8013 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8014 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8015
8016 // How much memory is used for selectors?
8017 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8018 (unsigned long) astContext.Selectors.getTotalMemory());
8019
8020 // How much memory is used by ASTContext's side tables?
8021 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8022 (unsigned long) astContext.getSideTableAllocatedMemory());
8023
8024 // How much memory is used for caching global code completion results?
8025 unsigned long completionBytes = 0;
8026 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008027 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008028 completionBytes = completionAllocator->getTotalMemory();
8029 }
8030 createCXTUResourceUsageEntry(*entries,
8031 CXTUResourceUsage_GlobalCompletionResults,
8032 completionBytes);
8033
8034 // How much memory is being used by SourceManager's content cache?
8035 createCXTUResourceUsageEntry(*entries,
8036 CXTUResourceUsage_SourceManagerContentCache,
8037 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8038
8039 // How much memory is being used by the MemoryBuffer's in SourceManager?
8040 const SourceManager::MemoryBufferSizes &srcBufs =
8041 astUnit->getSourceManager().getMemoryBufferSizes();
8042
8043 createCXTUResourceUsageEntry(*entries,
8044 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8045 (unsigned long) srcBufs.malloc_bytes);
8046 createCXTUResourceUsageEntry(*entries,
8047 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8048 (unsigned long) srcBufs.mmap_bytes);
8049 createCXTUResourceUsageEntry(*entries,
8050 CXTUResourceUsage_SourceManager_DataStructures,
8051 (unsigned long) astContext.getSourceManager()
8052 .getDataStructureSizes());
8053
8054 // How much memory is being used by the ExternalASTSource?
8055 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8056 const ExternalASTSource::MemoryBufferSizes &sizes =
8057 esrc->getMemoryBufferSizes();
8058
8059 createCXTUResourceUsageEntry(*entries,
8060 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8061 (unsigned long) sizes.malloc_bytes);
8062 createCXTUResourceUsageEntry(*entries,
8063 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8064 (unsigned long) sizes.mmap_bytes);
8065 }
8066
8067 // How much memory is being used by the Preprocessor?
8068 Preprocessor &pp = astUnit->getPreprocessor();
8069 createCXTUResourceUsageEntry(*entries,
8070 CXTUResourceUsage_Preprocessor,
8071 pp.getTotalMemory());
8072
8073 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8074 createCXTUResourceUsageEntry(*entries,
8075 CXTUResourceUsage_PreprocessingRecord,
8076 pRec->getTotalMemory());
8077 }
8078
8079 createCXTUResourceUsageEntry(*entries,
8080 CXTUResourceUsage_Preprocessor_HeaderSearch,
8081 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008082
Guy Benyei11169dd2012-12-18 14:30:41 +00008083 CXTUResourceUsage usage = { (void*) entries.get(),
8084 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008085 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008086 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008087 return usage;
8088}
8089
8090void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8091 if (usage.data)
8092 delete (MemUsageEntries*) usage.data;
8093}
8094
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008095CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8096 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008097 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008098 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008099
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008100 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008101 LOG_BAD_TU(TU);
8102 return skipped;
8103 }
8104
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008105 if (!file)
8106 return skipped;
8107
8108 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8109 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8110 if (!ppRec)
8111 return skipped;
8112
8113 ASTContext &Ctx = astUnit->getASTContext();
8114 SourceManager &sm = Ctx.getSourceManager();
8115 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8116 FileID wantedFileID = sm.translateFile(fileEntry);
8117
8118 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8119 std::vector<SourceRange> wantedRanges;
8120 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8121 i != ei; ++i) {
8122 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8123 wantedRanges.push_back(*i);
8124 }
8125
8126 skipped->count = wantedRanges.size();
8127 skipped->ranges = new CXSourceRange[skipped->count];
8128 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8129 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8130
8131 return skipped;
8132}
8133
Cameron Desrochersd8091282016-08-18 15:43:55 +00008134CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8135 CXSourceRangeList *skipped = new CXSourceRangeList;
8136 skipped->count = 0;
8137 skipped->ranges = nullptr;
8138
8139 if (isNotUsableTU(TU)) {
8140 LOG_BAD_TU(TU);
8141 return skipped;
8142 }
8143
8144 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8145 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8146 if (!ppRec)
8147 return skipped;
8148
8149 ASTContext &Ctx = astUnit->getASTContext();
8150
8151 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8152
8153 skipped->count = SkippedRanges.size();
8154 skipped->ranges = new CXSourceRange[skipped->count];
8155 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8156 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8157
8158 return skipped;
8159}
8160
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008161void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8162 if (ranges) {
8163 delete[] ranges->ranges;
8164 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008165 }
8166}
8167
Guy Benyei11169dd2012-12-18 14:30:41 +00008168void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8169 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8170 for (unsigned I = 0; I != Usage.numEntries; ++I)
8171 fprintf(stderr, " %s: %lu\n",
8172 clang_getTUResourceUsageName(Usage.entries[I].kind),
8173 Usage.entries[I].amount);
8174
8175 clang_disposeCXTUResourceUsage(Usage);
8176}
8177
8178//===----------------------------------------------------------------------===//
8179// Misc. utility functions.
8180//===----------------------------------------------------------------------===//
8181
8182/// Default to using an 8 MB stack size on "safety" threads.
8183static unsigned SafetyStackThreadSize = 8 << 20;
8184
8185namespace clang {
8186
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008187bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008188 unsigned Size) {
8189 if (!Size)
8190 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008191 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008192 return CRC.RunSafelyOnThread(Fn, Size);
8193 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008194}
8195
8196unsigned GetSafetyThreadStackSize() {
8197 return SafetyStackThreadSize;
8198}
8199
8200void SetSafetyThreadStackSize(unsigned Value) {
8201 SafetyStackThreadSize = Value;
8202}
8203
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008204}
Guy Benyei11169dd2012-12-18 14:30:41 +00008205
8206void clang::setThreadBackgroundPriority() {
8207 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8208 return;
8209
Alp Toker1a86ad22014-07-06 06:24:00 +00008210#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8212#endif
8213}
8214
8215void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8216 if (!Unit)
8217 return;
8218
8219 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8220 DEnd = Unit->stored_diag_end();
8221 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008222 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008223 CXString Msg = clang_formatDiagnostic(&Diag,
8224 clang_defaultDiagnosticDisplayOptions());
8225 fprintf(stderr, "%s\n", clang_getCString(Msg));
8226 clang_disposeString(Msg);
8227 }
8228#ifdef LLVM_ON_WIN32
8229 // On Windows, force a flush, since there may be multiple copies of
8230 // stderr and stdout in the file system, all with different buffers
8231 // but writing to the same device.
8232 fflush(stderr);
8233#endif
8234}
8235
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008236MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8237 SourceLocation MacroDefLoc,
8238 CXTranslationUnit TU){
8239 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008240 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008241 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008242 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008243
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008244 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008245 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008246 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008247 if (MD) {
8248 for (MacroDirective::DefInfo
8249 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8250 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8251 return Def.getMacroInfo();
8252 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008253 }
8254
Craig Topper69186e72014-06-08 08:38:04 +00008255 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008256}
8257
Richard Smith66a81862015-05-04 02:25:31 +00008258const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008259 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008260 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008261 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008262 const IdentifierInfo *II = MacroDef->getName();
8263 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008264 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008265
8266 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8267}
8268
Richard Smith66a81862015-05-04 02:25:31 +00008269MacroDefinitionRecord *
8270cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8271 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008272 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008273 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008274 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008275 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008276
8277 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008278 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008279 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8280 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008281 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008282
8283 // Check that the token is inside the definition and not its argument list.
8284 SourceManager &SM = Unit->getSourceManager();
8285 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008286 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008287 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008288 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008289
8290 Preprocessor &PP = Unit->getPreprocessor();
8291 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8292 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008293 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008294
Alp Toker2d57cea2014-05-17 04:53:25 +00008295 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008296 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008297 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008298
8299 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008300 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008301 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008302
Richard Smith20e883e2015-04-29 23:20:19 +00008303 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008304 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008305 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008306
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008307 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008308}
8309
Richard Smith66a81862015-05-04 02:25:31 +00008310MacroDefinitionRecord *
8311cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8312 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008313 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008314 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008315
8316 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008317 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008318 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008319 Preprocessor &PP = Unit->getPreprocessor();
8320 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008321 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008322 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8323 Token Tok;
8324 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008325 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008326
8327 return checkForMacroInMacroDefinition(MI, Tok, TU);
8328}
8329
Guy Benyei11169dd2012-12-18 14:30:41 +00008330CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008331 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008332}
8333
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008334Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8335 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008336 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008337 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008338 if (Unit->isMainFileAST())
8339 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008340 return *this;
8341 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008342 } else {
8343 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008344 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008345 return *this;
8346}
8347
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008348Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8349 *this << FE->getName();
8350 return *this;
8351}
8352
8353Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8354 CXString cursorName = clang_getCursorDisplayName(cursor);
8355 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8356 clang_disposeString(cursorName);
8357 return *this;
8358}
8359
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008360Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8361 CXFile File;
8362 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008363 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008364 CXString FileName = clang_getFileName(File);
8365 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8366 clang_disposeString(FileName);
8367 return *this;
8368}
8369
8370Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8371 CXSourceLocation BLoc = clang_getRangeStart(range);
8372 CXSourceLocation ELoc = clang_getRangeEnd(range);
8373
8374 CXFile BFile;
8375 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008376 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008377
8378 CXFile EFile;
8379 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008380 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008381
8382 CXString BFileName = clang_getFileName(BFile);
8383 if (BFile == EFile) {
8384 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8385 BLine, BColumn, ELine, EColumn);
8386 } else {
8387 CXString EFileName = clang_getFileName(EFile);
8388 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8389 BLine, BColumn)
8390 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8391 ELine, EColumn);
8392 clang_disposeString(EFileName);
8393 }
8394 clang_disposeString(BFileName);
8395 return *this;
8396}
8397
8398Logger &cxindex::Logger::operator<<(CXString Str) {
8399 *this << clang_getCString(Str);
8400 return *this;
8401}
8402
8403Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8404 LogOS << Fmt;
8405 return *this;
8406}
8407
Chandler Carruth37ad2582014-06-27 15:14:39 +00008408static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8409
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008410cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008411 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008412
8413 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8414
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008415 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008416 OS << "[libclang:" << Name << ':';
8417
Alp Toker1a86ad22014-07-06 06:24:00 +00008418#ifdef USE_DARWIN_THREADS
8419 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008420 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8421 OS << tid << ':';
8422#endif
8423
8424 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8425 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008426 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008427
8428 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008429 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008430 OS << "--------------------------------------------------\n";
8431 }
8432}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008433
8434#ifdef CLANG_TOOL_EXTRA_BUILD
8435// This anchor is used to force the linker to link the clang-tidy plugin.
8436extern volatile int ClangTidyPluginAnchorSource;
8437static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8438 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008439
8440// This anchor is used to force the linker to link the clang-include-fixer
8441// plugin.
8442extern volatile int ClangIncludeFixerPluginAnchorSource;
8443static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8444 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008445#endif