blob: f4d347108c9ff92768ee44b465b50e1cba7ea1c7 [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;
Alex Lorenz690f0e22017-12-07 20:37:50 +000084 D->ParsingOptions = 0;
85 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000086 return D;
87}
88
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000089bool cxtu::isASTReadError(ASTUnit *AU) {
90 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
91 DEnd = AU->stored_diag_end();
92 D != DEnd; ++D) {
93 if (D->getLevel() >= DiagnosticsEngine::Error &&
94 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
95 diag::DiagCat_AST_Deserialization_Issue)
96 return true;
97 }
98 return false;
99}
100
Guy Benyei11169dd2012-12-18 14:30:41 +0000101cxtu::CXTUOwner::~CXTUOwner() {
102 if (TU)
103 clang_disposeTranslationUnit(TU);
104}
105
106/// \brief Compare two source ranges to determine their relative position in
107/// the translation unit.
108static RangeComparisonResult RangeCompare(SourceManager &SM,
109 SourceRange R1,
110 SourceRange R2) {
111 assert(R1.isValid() && "First range is invalid?");
112 assert(R2.isValid() && "Second range is invalid?");
113 if (R1.getEnd() != R2.getBegin() &&
114 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
115 return RangeBefore;
116 if (R2.getEnd() != R1.getBegin() &&
117 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
118 return RangeAfter;
119 return RangeOverlap;
120}
121
122/// \brief Determine if a source location falls within, before, or after a
123/// a given source range.
124static RangeComparisonResult LocationCompare(SourceManager &SM,
125 SourceLocation L, SourceRange R) {
126 assert(R.isValid() && "First range is invalid?");
127 assert(L.isValid() && "Second range is invalid?");
128 if (L == R.getBegin() || L == R.getEnd())
129 return RangeOverlap;
130 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
131 return RangeBefore;
132 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
133 return RangeAfter;
134 return RangeOverlap;
135}
136
137/// \brief Translate a Clang source range into a CIndex source range.
138///
139/// Clang internally represents ranges where the end location points to the
140/// start of the token at the end. However, for external clients it is more
141/// useful to have a CXSourceRange be a proper half-open interval. This routine
142/// does the appropriate translation.
143CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
144 const LangOptions &LangOpts,
145 const CharSourceRange &R) {
146 // We want the last character in this location, so we will adjust the
147 // location accordingly.
148 SourceLocation EndLoc = R.getEnd();
149 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
150 EndLoc = SM.getExpansionRange(EndLoc).second;
Yaron Keren8b563662015-10-03 10:46:20 +0000151 if (R.isTokenRange() && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000152 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
153 SM, LangOpts);
154 EndLoc = EndLoc.getLocWithOffset(Length);
155 }
156
Bill Wendlingeade3622013-01-23 08:25:41 +0000157 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000158 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000159 R.getBegin().getRawEncoding(),
160 EndLoc.getRawEncoding()
161 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000162 return Result;
163}
164
165//===----------------------------------------------------------------------===//
166// Cursor visitor.
167//===----------------------------------------------------------------------===//
168
169static SourceRange getRawCursorExtent(CXCursor C);
170static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
171
172
173RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
174 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
175}
176
177/// \brief Visit the given cursor and, if requested by the visitor,
178/// its children.
179///
180/// \param Cursor the cursor to visit.
181///
182/// \param CheckedRegionOfInterest if true, then the caller already checked
183/// that this cursor is within the region of interest.
184///
185/// \returns true if the visitation should be aborted, false if it
186/// should continue.
187bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
188 if (clang_isInvalid(Cursor.kind))
189 return false;
190
191 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000192 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000193 if (!D) {
194 assert(0 && "Invalid declaration cursor");
195 return true; // abort.
196 }
197
198 // Ignore implicit declarations, unless it's an objc method because
199 // currently we should report implicit methods for properties when indexing.
200 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
201 return false;
202 }
203
204 // If we have a range of interest, and this cursor doesn't intersect with it,
205 // we're done.
206 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
207 SourceRange Range = getRawCursorExtent(Cursor);
208 if (Range.isInvalid() || CompareRegionOfInterest(Range))
209 return false;
210 }
211
212 switch (Visitor(Cursor, Parent, ClientData)) {
213 case CXChildVisit_Break:
214 return true;
215
216 case CXChildVisit_Continue:
217 return false;
218
219 case CXChildVisit_Recurse: {
220 bool ret = VisitChildren(Cursor);
221 if (PostChildrenVisitor)
222 if (PostChildrenVisitor(Cursor, ClientData))
223 return true;
224 return ret;
225 }
226 }
227
228 llvm_unreachable("Invalid CXChildVisitResult!");
229}
230
231static bool visitPreprocessedEntitiesInRange(SourceRange R,
232 PreprocessingRecord &PPRec,
233 CursorVisitor &Visitor) {
234 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
235 FileID FID;
236
237 if (!Visitor.shouldVisitIncludedEntities()) {
238 // If the begin/end of the range lie in the same FileID, do the optimization
239 // where we skip preprocessed entities that do not come from the same FileID.
240 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
241 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
242 FID = FileID();
243 }
244
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000245 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
246 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000247 PPRec, FID);
248}
249
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000250bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000251 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000252 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000253
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000254 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000255 SourceManager &SM = Unit->getSourceManager();
256
257 std::pair<FileID, unsigned>
258 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
259 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
260
261 if (End.first != Begin.first) {
262 // If the end does not reside in the same file, try to recover by
263 // picking the end of the file of begin location.
264 End.first = Begin.first;
265 End.second = SM.getFileIDSize(Begin.first);
266 }
267
268 assert(Begin.first == End.first);
269 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000270 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000271
272 FileID File = Begin.first;
273 unsigned Offset = Begin.second;
274 unsigned Length = End.second - Begin.second;
275
276 if (!VisitDeclsOnly && !VisitPreprocessorLast)
277 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000278 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000279
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000280 if (visitDeclsFromFileRegion(File, Offset, Length))
281 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000282
283 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000284 return visitPreprocessedEntitiesInRegion();
285
286 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000287}
288
289static bool isInLexicalContext(Decl *D, DeclContext *DC) {
290 if (!DC)
291 return false;
292
293 for (DeclContext *DeclDC = D->getLexicalDeclContext();
294 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
295 if (DeclDC == DC)
296 return true;
297 }
298 return false;
299}
300
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000301bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000302 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000303 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000304 SourceManager &SM = Unit->getSourceManager();
305 SourceRange Range = RegionOfInterest;
306
307 SmallVector<Decl *, 16> Decls;
308 Unit->findFileRegionDecls(File, Offset, Length, Decls);
309
310 // If we didn't find any file level decls for the file, try looking at the
311 // file that it was included from.
312 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
313 bool Invalid = false;
314 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
315 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000316 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000317
318 SourceLocation Outer;
319 if (SLEntry.isFile())
320 Outer = SLEntry.getFile().getIncludeLoc();
321 else
322 Outer = SLEntry.getExpansion().getExpansionLocStart();
323 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000324 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000325
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000326 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000327 Length = 0;
328 Unit->findFileRegionDecls(File, Offset, Length, Decls);
329 }
330
331 assert(!Decls.empty());
332
333 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000334 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000335 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
336 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000337 Decl *D = *DIt;
338 if (D->getSourceRange().isInvalid())
339 continue;
340
341 if (isInLexicalContext(D, CurDC))
342 continue;
343
344 CurDC = dyn_cast<DeclContext>(D);
345
346 if (TagDecl *TD = dyn_cast<TagDecl>(D))
347 if (!TD->isFreeStanding())
348 continue;
349
350 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
351 if (CompRes == RangeBefore)
352 continue;
353 if (CompRes == RangeAfter)
354 break;
355
356 assert(CompRes == RangeOverlap);
357 VisitedAtLeastOnce = true;
358
359 if (isa<ObjCContainerDecl>(D)) {
360 FileDI_current = &DIt;
361 FileDE_current = DE;
362 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000363 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000364 }
365
366 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000367 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000368 }
369
370 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000371 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000372
373 // No Decls overlapped with the range. Move up the lexical context until there
374 // is a context that contains the range or we reach the translation unit
375 // level.
376 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
377 : (*(DIt-1))->getLexicalDeclContext();
378
379 while (DC && !DC->isTranslationUnit()) {
380 Decl *D = cast<Decl>(DC);
381 SourceRange CurDeclRange = D->getSourceRange();
382 if (CurDeclRange.isInvalid())
383 break;
384
385 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000386 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
387 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000388 }
389
390 DC = D->getLexicalDeclContext();
391 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000392
393 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000394}
395
396bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
397 if (!AU->getPreprocessor().getPreprocessingRecord())
398 return false;
399
400 PreprocessingRecord &PPRec
401 = *AU->getPreprocessor().getPreprocessingRecord();
402 SourceManager &SM = AU->getSourceManager();
403
404 if (RegionOfInterest.isValid()) {
405 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
406 SourceLocation B = MappedRange.getBegin();
407 SourceLocation E = MappedRange.getEnd();
408
409 if (AU->isInPreambleFileID(B)) {
410 if (SM.isLoadedSourceLocation(E))
411 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
412 PPRec, *this);
413
414 // Beginning of range lies in the preamble but it also extends beyond
415 // it into the main file. Split the range into 2 parts, one covering
416 // the preamble and another covering the main file. This allows subsequent
417 // calls to visitPreprocessedEntitiesInRange to accept a source range that
418 // lies in the same FileID, allowing it to skip preprocessed entities that
419 // do not come from the same FileID.
420 bool breaked =
421 visitPreprocessedEntitiesInRange(
422 SourceRange(B, AU->getEndOfPreambleFileID()),
423 PPRec, *this);
424 if (breaked) return true;
425 return visitPreprocessedEntitiesInRange(
426 SourceRange(AU->getStartOfMainFileID(), E),
427 PPRec, *this);
428 }
429
430 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
431 }
432
433 bool OnlyLocalDecls
434 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
435
436 if (OnlyLocalDecls)
437 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
438 PPRec);
439
440 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
441}
442
443template<typename InputIterator>
444bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
445 InputIterator Last,
446 PreprocessingRecord &PPRec,
447 FileID FID) {
448 for (; First != Last; ++First) {
449 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
450 continue;
451
452 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000453 if (!PPE)
454 continue;
455
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
457 if (Visit(MakeMacroExpansionCursor(ME, TU)))
458 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000459
Guy Benyei11169dd2012-12-18 14:30:41 +0000460 continue;
461 }
Richard Smith66a81862015-05-04 02:25:31 +0000462
463 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000464 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
465 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000466
Guy Benyei11169dd2012-12-18 14:30:41 +0000467 continue;
468 }
469
470 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
471 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
472 return true;
473
474 continue;
475 }
476 }
477
478 return false;
479}
480
481/// \brief Visit the children of the given cursor.
482///
483/// \returns true if the visitation should be aborted, false if it
484/// should continue.
485bool CursorVisitor::VisitChildren(CXCursor Cursor) {
486 if (clang_isReference(Cursor.kind) &&
487 Cursor.kind != CXCursor_CXXBaseSpecifier) {
488 // By definition, references have no children.
489 return false;
490 }
491
492 // Set the Parent field to Cursor, then back to its old value once we're
493 // done.
494 SetParentRAII SetParent(Parent, StmtParent, Cursor);
495
496 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000497 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000498 if (!D)
499 return false;
500
501 return VisitAttributes(D) || Visit(D);
502 }
503
504 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000505 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000506 return Visit(S);
507
508 return false;
509 }
510
511 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000512 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000513 return Visit(E);
514
515 return false;
516 }
517
518 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000519 CXTranslationUnit TU = getCursorTU(Cursor);
520 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000521
522 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
523 for (unsigned I = 0; I != 2; ++I) {
524 if (VisitOrder[I]) {
525 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
526 RegionOfInterest.isInvalid()) {
527 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
528 TLEnd = CXXUnit->top_level_end();
529 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000530 const Optional<bool> V = handleDeclForVisitation(*TL);
531 if (!V.hasValue())
532 continue;
533 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000534 }
535 } else if (VisitDeclContext(
536 CXXUnit->getASTContext().getTranslationUnitDecl()))
537 return true;
538 continue;
539 }
540
541 // Walk the preprocessing record.
542 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
543 visitPreprocessedEntitiesInRegion();
544 }
545
546 return false;
547 }
548
549 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000550 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000551 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
552 return Visit(BaseTSInfo->getTypeLoc());
553 }
554 }
555 }
556
557 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000558 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000559 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000560 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000561 return Visit(cxcursor::MakeCursorObjCClassRef(
562 ObjT->getInterface(),
563 A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 }
565
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000566 // If pointing inside a macro definition, check if the token is an identifier
567 // that was ever defined as a macro. In such a case, create a "pseudo" macro
568 // expansion cursor for that token.
569 SourceLocation BeginLoc = RegionOfInterest.getBegin();
570 if (Cursor.kind == CXCursor_MacroDefinition &&
571 BeginLoc == RegionOfInterest.getEnd()) {
572 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000573 const MacroInfo *MI =
574 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000575 if (MacroDefinitionRecord *MacroDef =
576 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000577 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
578 }
579
Guy Benyei11169dd2012-12-18 14:30:41 +0000580 // Nothing to visit at the moment.
581 return false;
582}
583
584bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
585 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
586 if (Visit(TSInfo->getTypeLoc()))
587 return true;
588
589 if (Stmt *Body = B->getBody())
590 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
591
592 return false;
593}
594
Ted Kremenek03325582013-02-21 01:29:01 +0000595Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000596 if (RegionOfInterest.isValid()) {
597 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
598 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000599 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000600
601 switch (CompareRegionOfInterest(Range)) {
602 case RangeBefore:
603 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000604 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000605
606 case RangeAfter:
607 // This declaration comes after the region of interest; we're done.
608 return false;
609
610 case RangeOverlap:
611 // This declaration overlaps the region of interest; visit it.
612 break;
613 }
614 }
615 return true;
616}
617
618bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
619 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
620
621 // FIXME: Eventually remove. This part of a hack to support proper
622 // iteration over all Decls contained lexically within an ObjC container.
623 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
624 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
625
626 for ( ; I != E; ++I) {
627 Decl *D = *I;
628 if (D->getLexicalDeclContext() != DC)
629 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000630 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000631 if (!V.hasValue())
632 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000633 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000634 }
635 return false;
636}
637
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000638Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
639 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
640
641 // Ignore synthesized ivars here, otherwise if we have something like:
642 // @synthesize prop = _prop;
643 // and '_prop' is not declared, we will encounter a '_prop' ivar before
644 // encountering the 'prop' synthesize declaration and we will think that
645 // we passed the region-of-interest.
646 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
647 if (ivarD->getSynthesize())
648 return None;
649 }
650
651 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
652 // declarations is a mismatch with the compiler semantics.
653 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
654 auto *ID = cast<ObjCInterfaceDecl>(D);
655 if (!ID->isThisDeclarationADefinition())
656 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
657
658 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
659 auto *PD = cast<ObjCProtocolDecl>(D);
660 if (!PD->isThisDeclarationADefinition())
661 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
662 }
663
664 const Optional<bool> V = shouldVisitCursor(Cursor);
665 if (!V.hasValue())
666 return None;
667 if (!V.getValue())
668 return false;
669 if (Visit(Cursor, true))
670 return true;
671 return None;
672}
673
Guy Benyei11169dd2012-12-18 14:30:41 +0000674bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
675 llvm_unreachable("Translation units are visited directly by Visit()");
676}
677
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000678bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
679 if (VisitTemplateParameters(D->getTemplateParameters()))
680 return true;
681
682 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
683}
684
Guy Benyei11169dd2012-12-18 14:30:41 +0000685bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
686 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
687 return Visit(TSInfo->getTypeLoc());
688
689 return false;
690}
691
692bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
693 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
694 return Visit(TSInfo->getTypeLoc());
695
696 return false;
697}
698
699bool CursorVisitor::VisitTagDecl(TagDecl *D) {
700 return VisitDeclContext(D);
701}
702
703bool CursorVisitor::VisitClassTemplateSpecializationDecl(
704 ClassTemplateSpecializationDecl *D) {
705 bool ShouldVisitBody = false;
706 switch (D->getSpecializationKind()) {
707 case TSK_Undeclared:
708 case TSK_ImplicitInstantiation:
709 // Nothing to visit
710 return false;
711
712 case TSK_ExplicitInstantiationDeclaration:
713 case TSK_ExplicitInstantiationDefinition:
714 break;
715
716 case TSK_ExplicitSpecialization:
717 ShouldVisitBody = true;
718 break;
719 }
720
721 // Visit the template arguments used in the specialization.
722 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
723 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000724 if (TemplateSpecializationTypeLoc TSTLoc =
725 TL.getAs<TemplateSpecializationTypeLoc>()) {
726 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
727 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 return true;
729 }
730 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000731
732 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000733}
734
735bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
736 ClassTemplatePartialSpecializationDecl *D) {
737 // FIXME: Visit the "outer" template parameter lists on the TagDecl
738 // before visiting these template parameters.
739 if (VisitTemplateParameters(D->getTemplateParameters()))
740 return true;
741
742 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000743 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
744 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
745 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000746 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
747 return true;
748
749 return VisitCXXRecordDecl(D);
750}
751
752bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
753 // Visit the default argument.
754 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
755 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
756 if (Visit(DefArg->getTypeLoc()))
757 return true;
758
759 return false;
760}
761
762bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
763 if (Expr *Init = D->getInitExpr())
764 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
765 return false;
766}
767
768bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000769 unsigned NumParamList = DD->getNumTemplateParameterLists();
770 for (unsigned i = 0; i < NumParamList; i++) {
771 TemplateParameterList* Params = DD->getTemplateParameterList(i);
772 if (VisitTemplateParameters(Params))
773 return true;
774 }
775
Guy Benyei11169dd2012-12-18 14:30:41 +0000776 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
777 if (Visit(TSInfo->getTypeLoc()))
778 return true;
779
780 // Visit the nested-name-specifier, if present.
781 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
782 if (VisitNestedNameSpecifierLoc(QualifierLoc))
783 return true;
784
785 return false;
786}
787
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000788/// \brief Compare two base or member initializers based on their source order.
789static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
790 CXXCtorInitializer *const *Y) {
791 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
792}
793
Guy Benyei11169dd2012-12-18 14:30:41 +0000794bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000795 unsigned NumParamList = ND->getNumTemplateParameterLists();
796 for (unsigned i = 0; i < NumParamList; i++) {
797 TemplateParameterList* Params = ND->getTemplateParameterList(i);
798 if (VisitTemplateParameters(Params))
799 return true;
800 }
801
Guy Benyei11169dd2012-12-18 14:30:41 +0000802 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
803 // Visit the function declaration's syntactic components in the order
804 // written. This requires a bit of work.
805 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +0000806 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Guy Benyei11169dd2012-12-18 14:30:41 +0000807
808 // If we have a function declared directly (without the use of a typedef),
809 // visit just the return type. Otherwise, just visit the function's type
810 // now.
Alp Toker42a16a62014-01-25 23:51:36 +0000811 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
Guy Benyei11169dd2012-12-18 14:30:41 +0000812 (!FTL && Visit(TL)))
813 return true;
814
815 // Visit the nested-name-specifier, if present.
816 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
817 if (VisitNestedNameSpecifierLoc(QualifierLoc))
818 return true;
819
820 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000821 if (!isa<CXXDestructorDecl>(ND))
822 if (VisitDeclarationNameInfo(ND->getNameInfo()))
823 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000824
825 // FIXME: Visit explicitly-specified template arguments!
826
827 // Visit the function parameters, if we have a function type.
David Blaikie6adc78e2013-02-18 22:06:02 +0000828 if (FTL && VisitFunctionTypeLoc(FTL, true))
Guy Benyei11169dd2012-12-18 14:30:41 +0000829 return true;
830
Bill Wendling44426052012-12-20 19:22:21 +0000831 // FIXME: Attributes?
Guy Benyei11169dd2012-12-18 14:30:41 +0000832 }
833
834 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
835 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
836 // Find the initializers that were written in the source.
837 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000838 for (auto *I : Constructor->inits()) {
839 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000840 continue;
841
Aaron Ballman0ad78302014-03-13 17:34:31 +0000842 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000843 }
844
845 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000846 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
847 &CompareCXXCtorInitializers);
848
Guy Benyei11169dd2012-12-18 14:30:41 +0000849 // Visit the initializers in source order
850 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
851 CXXCtorInitializer *Init = WrittenInits[I];
852 if (Init->isAnyMemberInitializer()) {
853 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
854 Init->getMemberLocation(), TU)))
855 return true;
856 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
857 if (Visit(TInfo->getTypeLoc()))
858 return true;
859 }
860
861 // Visit the initializer value.
862 if (Expr *Initializer = Init->getInit())
863 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
864 return true;
865 }
866 }
867
868 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
869 return true;
870 }
871
872 return false;
873}
874
875bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
876 if (VisitDeclaratorDecl(D))
877 return true;
878
879 if (Expr *BitWidth = D->getBitWidth())
880 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
881
Benjamin Kramer99f97592017-11-15 12:20:41 +0000882 if (Expr *Init = D->getInClassInitializer())
883 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
884
Guy Benyei11169dd2012-12-18 14:30:41 +0000885 return false;
886}
887
888bool CursorVisitor::VisitVarDecl(VarDecl *D) {
889 if (VisitDeclaratorDecl(D))
890 return true;
891
892 if (Expr *Init = D->getInit())
893 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
894
895 return false;
896}
897
898bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
899 if (VisitDeclaratorDecl(D))
900 return true;
901
902 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
903 if (Expr *DefArg = D->getDefaultArgument())
904 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
905
906 return false;
907}
908
909bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
910 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
911 // before visiting these template parameters.
912 if (VisitTemplateParameters(D->getTemplateParameters()))
913 return true;
914
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000915 auto* FD = D->getTemplatedDecl();
916 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000917}
918
919bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
920 // FIXME: Visit the "outer" template parameter lists on the TagDecl
921 // before visiting these template parameters.
922 if (VisitTemplateParameters(D->getTemplateParameters()))
923 return true;
924
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000925 auto* CD = D->getTemplatedDecl();
926 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000927}
928
929bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
930 if (VisitTemplateParameters(D->getTemplateParameters()))
931 return true;
932
933 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
934 VisitTemplateArgumentLoc(D->getDefaultArgument()))
935 return true;
936
937 return false;
938}
939
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000940bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
941 // Visit the bound, if it's explicit.
942 if (D->hasExplicitBound()) {
943 if (auto TInfo = D->getTypeSourceInfo()) {
944 if (Visit(TInfo->getTypeLoc()))
945 return true;
946 }
947 }
948
949 return false;
950}
951
Guy Benyei11169dd2012-12-18 14:30:41 +0000952bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000953 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000954 if (Visit(TSInfo->getTypeLoc()))
955 return true;
956
David Majnemer59f77922016-06-24 04:05:48 +0000957 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000958 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 return true;
960 }
961
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000962 return ND->isThisDeclarationADefinition() &&
963 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000964}
965
966template <typename DeclIt>
967static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
968 SourceManager &SM, SourceLocation EndLoc,
969 SmallVectorImpl<Decl *> &Decls) {
970 DeclIt next = *DI_current;
971 while (++next != DE_current) {
972 Decl *D_next = *next;
973 if (!D_next)
974 break;
975 SourceLocation L = D_next->getLocStart();
976 if (!L.isValid())
977 break;
978 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
979 *DI_current = next;
980 Decls.push_back(D_next);
981 continue;
982 }
983 break;
984 }
985}
986
Guy Benyei11169dd2012-12-18 14:30:41 +0000987bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
988 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
989 // an @implementation can lexically contain Decls that are not properly
990 // nested in the AST. When we identify such cases, we need to retrofit
991 // this nesting here.
992 if (!DI_current && !FileDI_current)
993 return VisitDeclContext(D);
994
995 // Scan the Decls that immediately come after the container
996 // in the current DeclContext. If any fall within the
997 // container's lexical region, stash them into a vector
998 // for later processing.
999 SmallVector<Decl *, 24> DeclsInContainer;
1000 SourceLocation EndLoc = D->getSourceRange().getEnd();
1001 SourceManager &SM = AU->getSourceManager();
1002 if (EndLoc.isValid()) {
1003 if (DI_current) {
1004 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1005 DeclsInContainer);
1006 } else {
1007 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1008 DeclsInContainer);
1009 }
1010 }
1011
1012 // The common case.
1013 if (DeclsInContainer.empty())
1014 return VisitDeclContext(D);
1015
1016 // Get all the Decls in the DeclContext, and sort them with the
1017 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001018 for (auto *SubDecl : D->decls()) {
1019 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1020 SubDecl->getLocStart().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001021 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001022 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 }
1024
1025 // Now sort the Decls so that they appear in lexical order.
1026 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001027 [&SM](Decl *A, Decl *B) {
1028 SourceLocation L_A = A->getLocStart();
1029 SourceLocation L_B = B->getLocStart();
Mandeep Singh Grangfa51e1d2017-11-29 20:55:13 +00001030 return L_A != L_B ?
1031 SM.isBeforeInTranslationUnit(L_A, L_B) :
1032 SM.isBeforeInTranslationUnit(A->getLocEnd(), B->getLocEnd());
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001033 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001034
1035 // Now visit the decls.
1036 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1037 E = DeclsInContainer.end(); I != E; ++I) {
1038 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001039 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001040 if (!V.hasValue())
1041 continue;
1042 if (!V.getValue())
1043 return false;
1044 if (Visit(Cursor, true))
1045 return true;
1046 }
1047 return false;
1048}
1049
1050bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1051 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1052 TU)))
1053 return true;
1054
Douglas Gregore9d95f12015-07-07 03:57:35 +00001055 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1056 return true;
1057
Guy Benyei11169dd2012-12-18 14:30:41 +00001058 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1059 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1060 E = ND->protocol_end(); I != E; ++I, ++PL)
1061 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1062 return true;
1063
1064 return VisitObjCContainerDecl(ND);
1065}
1066
1067bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1068 if (!PID->isThisDeclarationADefinition())
1069 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1070
1071 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1072 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1073 E = PID->protocol_end(); I != E; ++I, ++PL)
1074 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1075 return true;
1076
1077 return VisitObjCContainerDecl(PID);
1078}
1079
1080bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1081 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1082 return true;
1083
1084 // FIXME: This implements a workaround with @property declarations also being
1085 // installed in the DeclContext for the @interface. Eventually this code
1086 // should be removed.
1087 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1088 if (!CDecl || !CDecl->IsClassExtension())
1089 return false;
1090
1091 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1092 if (!ID)
1093 return false;
1094
1095 IdentifierInfo *PropertyId = PD->getIdentifier();
1096 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001097 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1098 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001099
1100 if (!prevDecl)
1101 return false;
1102
1103 // Visit synthesized methods since they will be skipped when visiting
1104 // the @interface.
1105 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1106 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1107 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1108 return true;
1109
1110 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1111 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1112 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1113 return true;
1114
1115 return false;
1116}
1117
Douglas Gregore9d95f12015-07-07 03:57:35 +00001118bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1119 if (!typeParamList)
1120 return false;
1121
1122 for (auto *typeParam : *typeParamList) {
1123 // Visit the type parameter.
1124 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1125 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001126 }
1127
1128 return false;
1129}
1130
Guy Benyei11169dd2012-12-18 14:30:41 +00001131bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1132 if (!D->isThisDeclarationADefinition()) {
1133 // Forward declaration is treated like a reference.
1134 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1135 }
1136
Douglas Gregore9d95f12015-07-07 03:57:35 +00001137 // Objective-C type parameters.
1138 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1139 return true;
1140
Guy Benyei11169dd2012-12-18 14:30:41 +00001141 // Issue callbacks for super class.
1142 if (D->getSuperClass() &&
1143 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1144 D->getSuperClassLoc(),
1145 TU)))
1146 return true;
1147
Douglas Gregore9d95f12015-07-07 03:57:35 +00001148 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1149 if (Visit(SuperClassTInfo->getTypeLoc()))
1150 return true;
1151
Guy Benyei11169dd2012-12-18 14:30:41 +00001152 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1153 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1154 E = D->protocol_end(); I != E; ++I, ++PL)
1155 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1156 return true;
1157
1158 return VisitObjCContainerDecl(D);
1159}
1160
1161bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1162 return VisitObjCContainerDecl(D);
1163}
1164
1165bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1166 // 'ID' could be null when dealing with invalid code.
1167 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1168 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1169 return true;
1170
1171 return VisitObjCImplDecl(D);
1172}
1173
1174bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1175#if 0
1176 // Issue callbacks for super class.
1177 // FIXME: No source location information!
1178 if (D->getSuperClass() &&
1179 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1180 D->getSuperClassLoc(),
1181 TU)))
1182 return true;
1183#endif
1184
1185 return VisitObjCImplDecl(D);
1186}
1187
1188bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1189 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1190 if (PD->isIvarNameSpecified())
1191 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1192
1193 return false;
1194}
1195
1196bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1197 return VisitDeclContext(D);
1198}
1199
1200bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1201 // Visit nested-name-specifier.
1202 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1203 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1204 return true;
1205
1206 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1207 D->getTargetNameLoc(), TU));
1208}
1209
1210bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1211 // Visit nested-name-specifier.
1212 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1213 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1214 return true;
1215 }
1216
1217 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1218 return true;
1219
1220 return VisitDeclarationNameInfo(D->getNameInfo());
1221}
1222
1223bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1224 // Visit nested-name-specifier.
1225 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1226 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1227 return true;
1228
1229 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1230 D->getIdentLocation(), TU));
1231}
1232
1233bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1234 // Visit nested-name-specifier.
1235 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1236 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1237 return true;
1238 }
1239
1240 return VisitDeclarationNameInfo(D->getNameInfo());
1241}
1242
1243bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1244 UnresolvedUsingTypenameDecl *D) {
1245 // Visit nested-name-specifier.
1246 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1247 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1248 return true;
1249
1250 return false;
1251}
1252
Olivier Goffart81978012016-06-09 16:15:55 +00001253bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1254 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1255 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001256 if (StringLiteral *Message = D->getMessage())
1257 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1258 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001259 return false;
1260}
1261
Olivier Goffartd211c642016-11-04 06:29:27 +00001262bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1263 if (NamedDecl *FriendD = D->getFriendDecl()) {
1264 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1265 return true;
1266 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1267 if (Visit(TI->getTypeLoc()))
1268 return true;
1269 }
1270 return false;
1271}
1272
Guy Benyei11169dd2012-12-18 14:30:41 +00001273bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1274 switch (Name.getName().getNameKind()) {
1275 case clang::DeclarationName::Identifier:
1276 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001277 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001278 case clang::DeclarationName::CXXOperatorName:
1279 case clang::DeclarationName::CXXUsingDirective:
1280 return false;
Richard Smith35845152017-02-07 01:37:30 +00001281
Guy Benyei11169dd2012-12-18 14:30:41 +00001282 case clang::DeclarationName::CXXConstructorName:
1283 case clang::DeclarationName::CXXDestructorName:
1284 case clang::DeclarationName::CXXConversionFunctionName:
1285 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1286 return Visit(TSInfo->getTypeLoc());
1287 return false;
1288
1289 case clang::DeclarationName::ObjCZeroArgSelector:
1290 case clang::DeclarationName::ObjCOneArgSelector:
1291 case clang::DeclarationName::ObjCMultiArgSelector:
1292 // FIXME: Per-identifier location info?
1293 return false;
1294 }
1295
1296 llvm_unreachable("Invalid DeclarationName::Kind!");
1297}
1298
1299bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1300 SourceRange Range) {
1301 // FIXME: This whole routine is a hack to work around the lack of proper
1302 // source information in nested-name-specifiers (PR5791). Since we do have
1303 // a beginning source location, we can visit the first component of the
1304 // nested-name-specifier, if it's a single-token component.
1305 if (!NNS)
1306 return false;
1307
1308 // Get the first component in the nested-name-specifier.
1309 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1310 NNS = Prefix;
1311
1312 switch (NNS->getKind()) {
1313 case NestedNameSpecifier::Namespace:
1314 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1315 TU));
1316
1317 case NestedNameSpecifier::NamespaceAlias:
1318 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1319 Range.getBegin(), TU));
1320
1321 case NestedNameSpecifier::TypeSpec: {
1322 // If the type has a form where we know that the beginning of the source
1323 // range matches up with a reference cursor. Visit the appropriate reference
1324 // cursor.
1325 const Type *T = NNS->getAsType();
1326 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1327 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1328 if (const TagType *Tag = dyn_cast<TagType>(T))
1329 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1330 if (const TemplateSpecializationType *TST
1331 = dyn_cast<TemplateSpecializationType>(T))
1332 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1333 break;
1334 }
1335
1336 case NestedNameSpecifier::TypeSpecWithTemplate:
1337 case NestedNameSpecifier::Global:
1338 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001339 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001340 break;
1341 }
1342
1343 return false;
1344}
1345
1346bool
1347CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1348 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1349 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1350 Qualifiers.push_back(Qualifier);
1351
1352 while (!Qualifiers.empty()) {
1353 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1354 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1355 switch (NNS->getKind()) {
1356 case NestedNameSpecifier::Namespace:
1357 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1358 Q.getLocalBeginLoc(),
1359 TU)))
1360 return true;
1361
1362 break;
1363
1364 case NestedNameSpecifier::NamespaceAlias:
1365 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1366 Q.getLocalBeginLoc(),
1367 TU)))
1368 return true;
1369
1370 break;
1371
1372 case NestedNameSpecifier::TypeSpec:
1373 case NestedNameSpecifier::TypeSpecWithTemplate:
1374 if (Visit(Q.getTypeLoc()))
1375 return true;
1376
1377 break;
1378
1379 case NestedNameSpecifier::Global:
1380 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001381 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 break;
1383 }
1384 }
1385
1386 return false;
1387}
1388
1389bool CursorVisitor::VisitTemplateParameters(
1390 const TemplateParameterList *Params) {
1391 if (!Params)
1392 return false;
1393
1394 for (TemplateParameterList::const_iterator P = Params->begin(),
1395 PEnd = Params->end();
1396 P != PEnd; ++P) {
1397 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1398 return true;
1399 }
1400
1401 return false;
1402}
1403
1404bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1405 switch (Name.getKind()) {
1406 case TemplateName::Template:
1407 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1408
1409 case TemplateName::OverloadedTemplate:
1410 // Visit the overloaded template set.
1411 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1412 return true;
1413
1414 return false;
1415
1416 case TemplateName::DependentTemplate:
1417 // FIXME: Visit nested-name-specifier.
1418 return false;
1419
1420 case TemplateName::QualifiedTemplate:
1421 // FIXME: Visit nested-name-specifier.
1422 return Visit(MakeCursorTemplateRef(
1423 Name.getAsQualifiedTemplateName()->getDecl(),
1424 Loc, TU));
1425
1426 case TemplateName::SubstTemplateTemplateParm:
1427 return Visit(MakeCursorTemplateRef(
1428 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1429 Loc, TU));
1430
1431 case TemplateName::SubstTemplateTemplateParmPack:
1432 return Visit(MakeCursorTemplateRef(
1433 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1434 Loc, TU));
1435 }
1436
1437 llvm_unreachable("Invalid TemplateName::Kind!");
1438}
1439
1440bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1441 switch (TAL.getArgument().getKind()) {
1442 case TemplateArgument::Null:
1443 case TemplateArgument::Integral:
1444 case TemplateArgument::Pack:
1445 return false;
1446
1447 case TemplateArgument::Type:
1448 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1449 return Visit(TSInfo->getTypeLoc());
1450 return false;
1451
1452 case TemplateArgument::Declaration:
1453 if (Expr *E = TAL.getSourceDeclExpression())
1454 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1455 return false;
1456
1457 case TemplateArgument::NullPtr:
1458 if (Expr *E = TAL.getSourceNullPtrExpression())
1459 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1460 return false;
1461
1462 case TemplateArgument::Expression:
1463 if (Expr *E = TAL.getSourceExpression())
1464 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1465 return false;
1466
1467 case TemplateArgument::Template:
1468 case TemplateArgument::TemplateExpansion:
1469 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1470 return true;
1471
1472 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1473 TAL.getTemplateNameLoc());
1474 }
1475
1476 llvm_unreachable("Invalid TemplateArgument::Kind!");
1477}
1478
1479bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1480 return VisitDeclContext(D);
1481}
1482
1483bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1484 return Visit(TL.getUnqualifiedLoc());
1485}
1486
1487bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1488 ASTContext &Context = AU->getASTContext();
1489
1490 // Some builtin types (such as Objective-C's "id", "sel", and
1491 // "Class") have associated declarations. Create cursors for those.
1492 QualType VisitType;
1493 switch (TL.getTypePtr()->getKind()) {
1494
1495 case BuiltinType::Void:
1496 case BuiltinType::NullPtr:
1497 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001498#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1499 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001500#include "clang/Basic/OpenCLImageTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001501 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001502 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001503 case BuiltinType::OCLClkEvent:
1504 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001505 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001506#define BUILTIN_TYPE(Id, SingletonId)
1507#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1508#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1509#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1510#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1511#include "clang/AST/BuiltinTypes.def"
1512 break;
1513
1514 case BuiltinType::ObjCId:
1515 VisitType = Context.getObjCIdType();
1516 break;
1517
1518 case BuiltinType::ObjCClass:
1519 VisitType = Context.getObjCClassType();
1520 break;
1521
1522 case BuiltinType::ObjCSel:
1523 VisitType = Context.getObjCSelType();
1524 break;
1525 }
1526
1527 if (!VisitType.isNull()) {
1528 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1529 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1530 TU));
1531 }
1532
1533 return false;
1534}
1535
1536bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1537 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1538}
1539
1540bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1541 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1542}
1543
1544bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1545 if (TL.isDefinition())
1546 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1547
1548 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1549}
1550
1551bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1552 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1553}
1554
1555bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001556 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001557}
1558
Manman Rene6be26c2016-09-13 17:25:08 +00001559bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1560 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getLocStart(), TU)))
1561 return true;
1562 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1563 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1564 TU)))
1565 return true;
1566 }
1567
1568 return false;
1569}
1570
Guy Benyei11169dd2012-12-18 14:30:41 +00001571bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1572 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1573 return true;
1574
Douglas Gregore9d95f12015-07-07 03:57:35 +00001575 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1576 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1577 return true;
1578 }
1579
Guy Benyei11169dd2012-12-18 14:30:41 +00001580 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1581 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1582 TU)))
1583 return true;
1584 }
1585
1586 return false;
1587}
1588
1589bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1590 return Visit(TL.getPointeeLoc());
1591}
1592
1593bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1594 return Visit(TL.getInnerLoc());
1595}
1596
1597bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1598 return Visit(TL.getPointeeLoc());
1599}
1600
1601bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1602 return Visit(TL.getPointeeLoc());
1603}
1604
1605bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1606 return Visit(TL.getPointeeLoc());
1607}
1608
1609bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1610 return Visit(TL.getPointeeLoc());
1611}
1612
1613bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1614 return Visit(TL.getPointeeLoc());
1615}
1616
1617bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1618 return Visit(TL.getModifiedLoc());
1619}
1620
1621bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1622 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001623 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001624 return true;
1625
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001626 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1627 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001628 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1629 return true;
1630
1631 return false;
1632}
1633
1634bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1635 if (Visit(TL.getElementLoc()))
1636 return true;
1637
1638 if (Expr *Size = TL.getSizeExpr())
1639 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1640
1641 return false;
1642}
1643
Reid Kleckner8a365022013-06-24 17:51:48 +00001644bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1645 return Visit(TL.getOriginalLoc());
1646}
1647
Reid Kleckner0503a872013-12-05 01:23:43 +00001648bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1649 return Visit(TL.getOriginalLoc());
1650}
1651
Richard Smith600b5262017-01-26 20:40:47 +00001652bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1653 DeducedTemplateSpecializationTypeLoc TL) {
1654 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1655 TL.getTemplateNameLoc()))
1656 return true;
1657
1658 return false;
1659}
1660
Guy Benyei11169dd2012-12-18 14:30:41 +00001661bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1662 TemplateSpecializationTypeLoc TL) {
1663 // Visit the template name.
1664 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1665 TL.getTemplateNameLoc()))
1666 return true;
1667
1668 // Visit the template arguments.
1669 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1670 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1671 return true;
1672
1673 return false;
1674}
1675
1676bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1677 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1678}
1679
1680bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1681 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1682 return Visit(TSInfo->getTypeLoc());
1683
1684 return false;
1685}
1686
1687bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1688 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1689 return Visit(TSInfo->getTypeLoc());
1690
1691 return false;
1692}
1693
1694bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001695 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001696}
1697
1698bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1699 DependentTemplateSpecializationTypeLoc TL) {
1700 // Visit the nested-name-specifier, if there is one.
1701 if (TL.getQualifierLoc() &&
1702 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1703 return true;
1704
1705 // Visit the template arguments.
1706 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1707 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1708 return true;
1709
1710 return false;
1711}
1712
1713bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1714 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1715 return true;
1716
1717 return Visit(TL.getNamedTypeLoc());
1718}
1719
1720bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1721 return Visit(TL.getPatternLoc());
1722}
1723
1724bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1725 if (Expr *E = TL.getUnderlyingExpr())
1726 return Visit(MakeCXCursor(E, StmtParent, TU));
1727
1728 return false;
1729}
1730
1731bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1732 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1733}
1734
1735bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1736 return Visit(TL.getValueLoc());
1737}
1738
Xiuli Pan9c14e282016-01-09 12:53:17 +00001739bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1740 return Visit(TL.getValueLoc());
1741}
1742
Guy Benyei11169dd2012-12-18 14:30:41 +00001743#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1744bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1745 return Visit##PARENT##Loc(TL); \
1746}
1747
1748DEFAULT_TYPELOC_IMPL(Complex, Type)
1749DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1750DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1751DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1752DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001753DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001754DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1755DEFAULT_TYPELOC_IMPL(Vector, Type)
1756DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1757DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1758DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1759DEFAULT_TYPELOC_IMPL(Record, TagType)
1760DEFAULT_TYPELOC_IMPL(Enum, TagType)
1761DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1762DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1763DEFAULT_TYPELOC_IMPL(Auto, Type)
1764
1765bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1766 // Visit the nested-name-specifier, if present.
1767 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1768 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1769 return true;
1770
1771 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001772 for (const auto &I : D->bases()) {
1773 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001774 return true;
1775 }
1776 }
1777
1778 return VisitTagDecl(D);
1779}
1780
1781bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001782 for (const auto *I : D->attrs())
1783 if (Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001784 return true;
1785
1786 return false;
1787}
1788
1789//===----------------------------------------------------------------------===//
1790// Data-recursive visitor methods.
1791//===----------------------------------------------------------------------===//
1792
1793namespace {
1794#define DEF_JOB(NAME, DATA, KIND)\
1795class NAME : public VisitorJob {\
1796public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001797 NAME(const DATA *d, CXCursor parent) : \
1798 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001799 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001800 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001801};
1802
1803DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1804DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1805DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1806DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001807DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1808DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1809DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1810#undef DEF_JOB
1811
James Y Knight04ec5bf2015-12-24 02:59:37 +00001812class ExplicitTemplateArgsVisit : public VisitorJob {
1813public:
1814 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1815 const TemplateArgumentLoc *End, CXCursor parent)
1816 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1817 End) {}
1818 static bool classof(const VisitorJob *VJ) {
1819 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1820 }
1821 const TemplateArgumentLoc *begin() const {
1822 return static_cast<const TemplateArgumentLoc *>(data[0]);
1823 }
1824 const TemplateArgumentLoc *end() {
1825 return static_cast<const TemplateArgumentLoc *>(data[1]);
1826 }
1827};
Guy Benyei11169dd2012-12-18 14:30:41 +00001828class DeclVisit : public VisitorJob {
1829public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001830 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001831 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001832 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001833 static bool classof(const VisitorJob *VJ) {
1834 return VJ->getKind() == DeclVisitKind;
1835 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001836 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001837 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001838};
1839class TypeLocVisit : public VisitorJob {
1840public:
1841 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1842 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1843 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1844
1845 static bool classof(const VisitorJob *VJ) {
1846 return VJ->getKind() == TypeLocVisitKind;
1847 }
1848
1849 TypeLoc get() const {
1850 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001851 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001852 }
1853};
1854
1855class LabelRefVisit : public VisitorJob {
1856public:
1857 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1858 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1859 labelLoc.getPtrEncoding()) {}
1860
1861 static bool classof(const VisitorJob *VJ) {
1862 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1863 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001864 const LabelDecl *get() const {
1865 return static_cast<const LabelDecl *>(data[0]);
1866 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 SourceLocation getLoc() const {
1868 return SourceLocation::getFromPtrEncoding(data[1]); }
1869};
1870
1871class NestedNameSpecifierLocVisit : public VisitorJob {
1872public:
1873 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1874 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1875 Qualifier.getNestedNameSpecifier(),
1876 Qualifier.getOpaqueData()) { }
1877
1878 static bool classof(const VisitorJob *VJ) {
1879 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1880 }
1881
1882 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001883 return NestedNameSpecifierLoc(
1884 const_cast<NestedNameSpecifier *>(
1885 static_cast<const NestedNameSpecifier *>(data[0])),
1886 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 }
1888};
1889
1890class DeclarationNameInfoVisit : public VisitorJob {
1891public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001892 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001893 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001894 static bool classof(const VisitorJob *VJ) {
1895 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1896 }
1897 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001898 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001899 switch (S->getStmtClass()) {
1900 default:
1901 llvm_unreachable("Unhandled Stmt");
1902 case clang::Stmt::MSDependentExistsStmtClass:
1903 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1904 case Stmt::CXXDependentScopeMemberExprClass:
1905 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1906 case Stmt::DependentScopeDeclRefExprClass:
1907 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001908 case Stmt::OMPCriticalDirectiveClass:
1909 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 }
1911 }
1912};
1913class MemberRefVisit : public VisitorJob {
1914public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001915 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001916 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1917 L.getPtrEncoding()) {}
1918 static bool classof(const VisitorJob *VJ) {
1919 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1920 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001921 const FieldDecl *get() const {
1922 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001923 }
1924 SourceLocation getLoc() const {
1925 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1926 }
1927};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001928class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001929 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001930 VisitorWorkList &WL;
1931 CXCursor Parent;
1932public:
1933 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1934 : WL(wl), Parent(parent) {}
1935
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001936 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1937 void VisitBlockExpr(const BlockExpr *B);
1938 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1939 void VisitCompoundStmt(const CompoundStmt *S);
1940 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1941 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1942 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1943 void VisitCXXNewExpr(const CXXNewExpr *E);
1944 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1945 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1946 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1947 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1948 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1949 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1950 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1951 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001952 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001953 void VisitDeclRefExpr(const DeclRefExpr *D);
1954 void VisitDeclStmt(const DeclStmt *S);
1955 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1956 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1957 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1958 void VisitForStmt(const ForStmt *FS);
1959 void VisitGotoStmt(const GotoStmt *GS);
1960 void VisitIfStmt(const IfStmt *If);
1961 void VisitInitListExpr(const InitListExpr *IE);
1962 void VisitMemberExpr(const MemberExpr *M);
1963 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1964 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1965 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1966 void VisitOverloadExpr(const OverloadExpr *E);
1967 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1968 void VisitStmt(const Stmt *S);
1969 void VisitSwitchStmt(const SwitchStmt *S);
1970 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001971 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1972 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1973 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1974 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1975 void VisitVAArgExpr(const VAArgExpr *E);
1976 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1977 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1978 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1979 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001980 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00001981 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001982 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001983 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001984 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00001985 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001986 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001987 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001988 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00001989 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001990 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001991 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00001992 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001993 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001994 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00001995 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001996 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00001997 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001998 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001999 void
2000 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002001 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002002 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002003 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002004 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002005 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002006 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002007 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002008 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002009 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002010 void
2011 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002012 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002013 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002014 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002015 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002016 void VisitOMPDistributeParallelForDirective(
2017 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002018 void VisitOMPDistributeParallelForSimdDirective(
2019 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002020 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002021 void VisitOMPTargetParallelForSimdDirective(
2022 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002023 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002024 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002025 void VisitOMPTeamsDistributeSimdDirective(
2026 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002027 void VisitOMPTeamsDistributeParallelForSimdDirective(
2028 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002029 void VisitOMPTeamsDistributeParallelForDirective(
2030 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002031 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002032 void VisitOMPTargetTeamsDistributeDirective(
2033 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002034 void VisitOMPTargetTeamsDistributeParallelForDirective(
2035 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002036 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2037 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002038 void VisitOMPTargetTeamsDistributeSimdDirective(
2039 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002040
Guy Benyei11169dd2012-12-18 14:30:41 +00002041private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002042 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002043 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002044 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2045 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002046 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2047 void AddStmt(const Stmt *S);
2048 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002049 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002050 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002051 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002052};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002053} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002054
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002055void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002056 // 'S' should always be non-null, since it comes from the
2057 // statement we are visiting.
2058 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2059}
2060
2061void
2062EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2063 if (Qualifier)
2064 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2065}
2066
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002067void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002068 if (S)
2069 WL.push_back(StmtVisit(S, Parent));
2070}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002071void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002072 if (D)
2073 WL.push_back(DeclVisit(D, Parent, isFirst));
2074}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002075void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2076 unsigned NumTemplateArgs) {
2077 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002078}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002079void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 if (D)
2081 WL.push_back(MemberRefVisit(D, L, Parent));
2082}
2083void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2084 if (TI)
2085 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2086 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002087void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002088 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002089 for (const Stmt *SubStmt : S->children()) {
2090 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002091 }
2092 if (size == WL.size())
2093 return;
2094 // Now reverse the entries we just added. This will match the DFS
2095 // ordering performed by the worklist.
2096 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2097 std::reverse(I, E);
2098}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002099namespace {
2100class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2101 EnqueueVisitor *Visitor;
Alexey Bataev756c1962013-09-24 03:17:45 +00002102 /// \brief Process clauses with list of variables.
2103 template <typename T>
2104 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002105public:
2106 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2107#define OPENMP_CLAUSE(Name, Class) \
2108 void Visit##Class(const Class *C);
2109#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002110 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002111 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002112};
2113
Alexey Bataev3392d762016-02-16 11:18:12 +00002114void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2115 const OMPClauseWithPreInit *C) {
2116 Visitor->AddStmt(C->getPreInitStmt());
2117}
2118
Alexey Bataev005248a2016-02-25 05:25:57 +00002119void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2120 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002121 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002122 Visitor->AddStmt(C->getPostUpdateExpr());
2123}
2124
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002125void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002126 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002127 Visitor->AddStmt(C->getCondition());
2128}
2129
Alexey Bataev3778b602014-07-17 07:32:53 +00002130void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2131 Visitor->AddStmt(C->getCondition());
2132}
2133
Alexey Bataev568a8332014-03-06 06:15:19 +00002134void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002135 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002136 Visitor->AddStmt(C->getNumThreads());
2137}
2138
Alexey Bataev62c87d22014-03-21 04:51:18 +00002139void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2140 Visitor->AddStmt(C->getSafelen());
2141}
2142
Alexey Bataev66b15b52015-08-21 11:14:16 +00002143void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2144 Visitor->AddStmt(C->getSimdlen());
2145}
2146
Alexander Musman8bd31e62014-05-27 15:12:19 +00002147void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2148 Visitor->AddStmt(C->getNumForLoops());
2149}
2150
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002151void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002152
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002153void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2154
Alexey Bataev56dafe82014-06-20 07:16:17 +00002155void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002156 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002157 Visitor->AddStmt(C->getChunkSize());
2158}
2159
Alexey Bataev10e775f2015-07-30 11:36:16 +00002160void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2161 Visitor->AddStmt(C->getNumForLoops());
2162}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002163
Alexey Bataev236070f2014-06-20 11:19:47 +00002164void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2165
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002166void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2167
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002168void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2169
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002170void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2171
Alexey Bataevdea47612014-07-23 07:46:59 +00002172void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2173
Alexey Bataev67a4f222014-07-23 10:25:33 +00002174void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2175
Alexey Bataev459dec02014-07-24 06:46:57 +00002176void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2177
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002178void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2179
Alexey Bataev346265e2015-09-25 10:37:12 +00002180void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2181
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002182void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2183
Alexey Bataevb825de12015-12-07 10:51:44 +00002184void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2185
Michael Wonge710d542015-08-07 16:16:36 +00002186void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2187 Visitor->AddStmt(C->getDevice());
2188}
2189
Kelvin Li099bb8c2015-11-24 20:50:12 +00002190void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002191 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002192 Visitor->AddStmt(C->getNumTeams());
2193}
2194
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002195void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002196 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002197 Visitor->AddStmt(C->getThreadLimit());
2198}
2199
Alexey Bataeva0569352015-12-01 10:17:31 +00002200void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2201 Visitor->AddStmt(C->getPriority());
2202}
2203
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002204void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2205 Visitor->AddStmt(C->getGrainsize());
2206}
2207
Alexey Bataev382967a2015-12-08 12:06:20 +00002208void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2209 Visitor->AddStmt(C->getNumTasks());
2210}
2211
Alexey Bataev28c75412015-12-15 08:19:24 +00002212void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2213 Visitor->AddStmt(C->getHint());
2214}
2215
Alexey Bataev756c1962013-09-24 03:17:45 +00002216template<typename T>
2217void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002218 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002219 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002220 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002221}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002222
2223void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002224 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002225 for (const auto *E : C->private_copies()) {
2226 Visitor->AddStmt(E);
2227 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002228}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002229void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2230 const OMPFirstprivateClause *C) {
2231 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002232 VisitOMPClauseWithPreInit(C);
2233 for (const auto *E : C->private_copies()) {
2234 Visitor->AddStmt(E);
2235 }
2236 for (const auto *E : C->inits()) {
2237 Visitor->AddStmt(E);
2238 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002239}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002240void OMPClauseEnqueue::VisitOMPLastprivateClause(
2241 const OMPLastprivateClause *C) {
2242 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002243 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002244 for (auto *E : C->private_copies()) {
2245 Visitor->AddStmt(E);
2246 }
2247 for (auto *E : C->source_exprs()) {
2248 Visitor->AddStmt(E);
2249 }
2250 for (auto *E : C->destination_exprs()) {
2251 Visitor->AddStmt(E);
2252 }
2253 for (auto *E : C->assignment_ops()) {
2254 Visitor->AddStmt(E);
2255 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002256}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002257void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002258 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002259}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002260void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2261 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002262 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002263 for (auto *E : C->privates()) {
2264 Visitor->AddStmt(E);
2265 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002266 for (auto *E : C->lhs_exprs()) {
2267 Visitor->AddStmt(E);
2268 }
2269 for (auto *E : C->rhs_exprs()) {
2270 Visitor->AddStmt(E);
2271 }
2272 for (auto *E : C->reduction_ops()) {
2273 Visitor->AddStmt(E);
2274 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002275}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002276void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2277 const OMPTaskReductionClause *C) {
2278 VisitOMPClauseList(C);
2279 VisitOMPClauseWithPostUpdate(C);
2280 for (auto *E : C->privates()) {
2281 Visitor->AddStmt(E);
2282 }
2283 for (auto *E : C->lhs_exprs()) {
2284 Visitor->AddStmt(E);
2285 }
2286 for (auto *E : C->rhs_exprs()) {
2287 Visitor->AddStmt(E);
2288 }
2289 for (auto *E : C->reduction_ops()) {
2290 Visitor->AddStmt(E);
2291 }
2292}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002293void OMPClauseEnqueue::VisitOMPInReductionClause(
2294 const OMPInReductionClause *C) {
2295 VisitOMPClauseList(C);
2296 VisitOMPClauseWithPostUpdate(C);
2297 for (auto *E : C->privates()) {
2298 Visitor->AddStmt(E);
2299 }
2300 for (auto *E : C->lhs_exprs()) {
2301 Visitor->AddStmt(E);
2302 }
2303 for (auto *E : C->rhs_exprs()) {
2304 Visitor->AddStmt(E);
2305 }
2306 for (auto *E : C->reduction_ops()) {
2307 Visitor->AddStmt(E);
2308 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002309 for (auto *E : C->taskgroup_descriptors())
2310 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002311}
Alexander Musman8dba6642014-04-22 13:09:42 +00002312void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2313 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002314 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002315 for (const auto *E : C->privates()) {
2316 Visitor->AddStmt(E);
2317 }
Alexander Musman3276a272015-03-21 10:12:56 +00002318 for (const auto *E : C->inits()) {
2319 Visitor->AddStmt(E);
2320 }
2321 for (const auto *E : C->updates()) {
2322 Visitor->AddStmt(E);
2323 }
2324 for (const auto *E : C->finals()) {
2325 Visitor->AddStmt(E);
2326 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002327 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002328 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002329}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002330void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2331 VisitOMPClauseList(C);
2332 Visitor->AddStmt(C->getAlignment());
2333}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002334void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2335 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002336 for (auto *E : C->source_exprs()) {
2337 Visitor->AddStmt(E);
2338 }
2339 for (auto *E : C->destination_exprs()) {
2340 Visitor->AddStmt(E);
2341 }
2342 for (auto *E : C->assignment_ops()) {
2343 Visitor->AddStmt(E);
2344 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002345}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002346void
2347OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2348 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002349 for (auto *E : C->source_exprs()) {
2350 Visitor->AddStmt(E);
2351 }
2352 for (auto *E : C->destination_exprs()) {
2353 Visitor->AddStmt(E);
2354 }
2355 for (auto *E : C->assignment_ops()) {
2356 Visitor->AddStmt(E);
2357 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002358}
Alexey Bataev6125da92014-07-21 11:26:11 +00002359void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2360 VisitOMPClauseList(C);
2361}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002362void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2363 VisitOMPClauseList(C);
2364}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002365void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2366 VisitOMPClauseList(C);
2367}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002368void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2369 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002370 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002371 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002372}
Alexey Bataev3392d762016-02-16 11:18:12 +00002373void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2374 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002375void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2376 VisitOMPClauseList(C);
2377}
Samuel Antaoec172c62016-05-26 17:49:04 +00002378void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2379 VisitOMPClauseList(C);
2380}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002381void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2382 VisitOMPClauseList(C);
2383}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002384void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2385 VisitOMPClauseList(C);
2386}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002387}
Alexey Bataev756c1962013-09-24 03:17:45 +00002388
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002389void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2390 unsigned size = WL.size();
2391 OMPClauseEnqueue Visitor(this);
2392 Visitor.Visit(S);
2393 if (size == WL.size())
2394 return;
2395 // Now reverse the entries we just added. This will match the DFS
2396 // ordering performed by the worklist.
2397 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2398 std::reverse(I, E);
2399}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002400void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2402}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002403void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 AddDecl(B->getBlockDecl());
2405}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002406void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 EnqueueChildren(E);
2408 AddTypeLoc(E->getTypeSourceInfo());
2409}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002410void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002411 for (auto &I : llvm::reverse(S->body()))
2412 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002413}
2414void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002415VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 AddStmt(S->getSubStmt());
2417 AddDeclarationNameInfo(S);
2418 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2419 AddNestedNameSpecifierLoc(QualifierLoc);
2420}
2421
2422void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002423VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002424 if (E->hasExplicitTemplateArgs())
2425 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 AddDeclarationNameInfo(E);
2427 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2428 AddNestedNameSpecifierLoc(QualifierLoc);
2429 if (!E->isImplicitAccess())
2430 AddStmt(E->getBase());
2431}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002432void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 // Enqueue the initializer , if any.
2434 AddStmt(E->getInitializer());
2435 // Enqueue the array size, if any.
2436 AddStmt(E->getArraySize());
2437 // Enqueue the allocated type.
2438 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2439 // Enqueue the placement arguments.
2440 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2441 AddStmt(E->getPlacementArg(I-1));
2442}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002443void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2445 AddStmt(CE->getArg(I-1));
2446 AddStmt(CE->getCallee());
2447 AddStmt(CE->getArg(0));
2448}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002449void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2450 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 // Visit the name of the type being destroyed.
2452 AddTypeLoc(E->getDestroyedTypeInfo());
2453 // Visit the scope type that looks disturbingly like the nested-name-specifier
2454 // but isn't.
2455 AddTypeLoc(E->getScopeTypeInfo());
2456 // Visit the nested-name-specifier.
2457 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2458 AddNestedNameSpecifierLoc(QualifierLoc);
2459 // Visit base expression.
2460 AddStmt(E->getBase());
2461}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002462void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2463 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 AddTypeLoc(E->getTypeSourceInfo());
2465}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002466void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2467 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 EnqueueChildren(E);
2469 AddTypeLoc(E->getTypeSourceInfo());
2470}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002471void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 EnqueueChildren(E);
2473 if (E->isTypeOperand())
2474 AddTypeLoc(E->getTypeOperandSourceInfo());
2475}
2476
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002477void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2478 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 EnqueueChildren(E);
2480 AddTypeLoc(E->getTypeSourceInfo());
2481}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002482void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 EnqueueChildren(E);
2484 if (E->isTypeOperand())
2485 AddTypeLoc(E->getTypeOperandSourceInfo());
2486}
2487
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002488void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 EnqueueChildren(S);
2490 AddDecl(S->getExceptionDecl());
2491}
2492
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002493void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002494 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002495 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002496 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002497}
2498
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002499void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002500 if (DR->hasExplicitTemplateArgs())
2501 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 WL.push_back(DeclRefExprParts(DR, Parent));
2503}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002504void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2505 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002506 if (E->hasExplicitTemplateArgs())
2507 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 AddDeclarationNameInfo(E);
2509 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2510}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002511void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 unsigned size = WL.size();
2513 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002514 for (const auto *D : S->decls()) {
2515 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 isFirst = false;
2517 }
2518 if (size == WL.size())
2519 return;
2520 // Now reverse the entries we just added. This will match the DFS
2521 // ordering performed by the worklist.
2522 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2523 std::reverse(I, E);
2524}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002525void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002527 for (const DesignatedInitExpr::Designator &D :
2528 llvm::reverse(E->designators())) {
2529 if (D.isFieldDesignator()) {
2530 if (FieldDecl *Field = D.getField())
2531 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 continue;
2533 }
David Majnemerf7e36092016-06-23 00:15:04 +00002534 if (D.isArrayDesignator()) {
2535 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 continue;
2537 }
David Majnemerf7e36092016-06-23 00:15:04 +00002538 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2539 AddStmt(E->getArrayRangeEnd(D));
2540 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 }
2542}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002543void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 EnqueueChildren(E);
2545 AddTypeLoc(E->getTypeInfoAsWritten());
2546}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002547void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 AddStmt(FS->getBody());
2549 AddStmt(FS->getInc());
2550 AddStmt(FS->getCond());
2551 AddDecl(FS->getConditionVariable());
2552 AddStmt(FS->getInit());
2553}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002554void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2556}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002557void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 AddStmt(If->getElse());
2559 AddStmt(If->getThen());
2560 AddStmt(If->getCond());
2561 AddDecl(If->getConditionVariable());
2562}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002563void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 // We care about the syntactic form of the initializer list, only.
2565 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2566 IE = Syntactic;
2567 EnqueueChildren(IE);
2568}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002569void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 WL.push_back(MemberExprParts(M, Parent));
2571
2572 // If the base of the member access expression is an implicit 'this', don't
2573 // visit it.
2574 // FIXME: If we ever want to show these implicit accesses, this will be
2575 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002576 if (M->isImplicitAccess())
2577 return;
2578
2579 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2580 // real field that that we are interested in.
2581 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2582 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2583 if (FD->isAnonymousStructOrUnion()) {
2584 AddStmt(SubME->getBase());
2585 return;
2586 }
2587 }
2588 }
2589
2590 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002591}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002592void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002593 AddTypeLoc(E->getEncodedTypeSourceInfo());
2594}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002595void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 EnqueueChildren(M);
2597 AddTypeLoc(M->getClassReceiverTypeInfo());
2598}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002599void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 // Visit the components of the offsetof expression.
2601 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 const OffsetOfNode &Node = E->getComponent(I-1);
2603 switch (Node.getKind()) {
2604 case OffsetOfNode::Array:
2605 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2606 break;
2607 case OffsetOfNode::Field:
2608 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2609 break;
2610 case OffsetOfNode::Identifier:
2611 case OffsetOfNode::Base:
2612 continue;
2613 }
2614 }
2615 // Visit the type into which we're computing the offset.
2616 AddTypeLoc(E->getTypeSourceInfo());
2617}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002618void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002619 if (E->hasExplicitTemplateArgs())
2620 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 WL.push_back(OverloadExprParts(E, Parent));
2622}
2623void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002624 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 EnqueueChildren(E);
2626 if (E->isArgumentType())
2627 AddTypeLoc(E->getArgumentTypeInfo());
2628}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002629void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 EnqueueChildren(S);
2631}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002632void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 AddStmt(S->getBody());
2634 AddStmt(S->getCond());
2635 AddDecl(S->getConditionVariable());
2636}
2637
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002638void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 AddStmt(W->getBody());
2640 AddStmt(W->getCond());
2641 AddDecl(W->getConditionVariable());
2642}
2643
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002644void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 for (unsigned I = E->getNumArgs(); I > 0; --I)
2646 AddTypeLoc(E->getArg(I-1));
2647}
2648
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002649void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 AddTypeLoc(E->getQueriedTypeSourceInfo());
2651}
2652
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002653void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 EnqueueChildren(E);
2655}
2656
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002657void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 VisitOverloadExpr(U);
2659 if (!U->isImplicitAccess())
2660 AddStmt(U->getBase());
2661}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002662void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 AddStmt(E->getSubExpr());
2664 AddTypeLoc(E->getWrittenTypeInfo());
2665}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002666void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 WL.push_back(SizeOfPackExprParts(E, Parent));
2668}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002669void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 // If the opaque value has a source expression, just transparently
2671 // visit that. This is useful for (e.g.) pseudo-object expressions.
2672 if (Expr *SourceExpr = E->getSourceExpr())
2673 return Visit(SourceExpr);
2674}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002675void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 AddStmt(E->getBody());
2677 WL.push_back(LambdaExprParts(E, Parent));
2678}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002679void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 // Treat the expression like its syntactic form.
2681 Visit(E->getSyntacticForm());
2682}
2683
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002684void EnqueueVisitor::VisitOMPExecutableDirective(
2685 const OMPExecutableDirective *D) {
2686 EnqueueChildren(D);
2687 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2688 E = D->clauses().end();
2689 I != E; ++I)
2690 EnqueueChildren(*I);
2691}
2692
Alexander Musman3aaab662014-08-19 11:27:13 +00002693void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2694 VisitOMPExecutableDirective(D);
2695}
2696
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002697void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2698 VisitOMPExecutableDirective(D);
2699}
2700
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002701void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002702 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002703}
2704
Alexey Bataevf29276e2014-06-18 04:14:57 +00002705void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002706 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002707}
2708
Alexander Musmanf82886e2014-09-18 05:12:34 +00002709void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2710 VisitOMPLoopDirective(D);
2711}
2712
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002713void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2714 VisitOMPExecutableDirective(D);
2715}
2716
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002717void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2718 VisitOMPExecutableDirective(D);
2719}
2720
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002721void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2722 VisitOMPExecutableDirective(D);
2723}
2724
Alexander Musman80c22892014-07-17 08:54:58 +00002725void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2726 VisitOMPExecutableDirective(D);
2727}
2728
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002729void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2730 VisitOMPExecutableDirective(D);
2731 AddDeclarationNameInfo(D);
2732}
2733
Alexey Bataev4acb8592014-07-07 13:01:15 +00002734void
2735EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002736 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002737}
2738
Alexander Musmane4e893b2014-09-23 09:33:00 +00002739void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2740 const OMPParallelForSimdDirective *D) {
2741 VisitOMPLoopDirective(D);
2742}
2743
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002744void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2745 const OMPParallelSectionsDirective *D) {
2746 VisitOMPExecutableDirective(D);
2747}
2748
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002749void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2750 VisitOMPExecutableDirective(D);
2751}
2752
Alexey Bataev68446b72014-07-18 07:47:19 +00002753void
2754EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2755 VisitOMPExecutableDirective(D);
2756}
2757
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002758void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2759 VisitOMPExecutableDirective(D);
2760}
2761
Alexey Bataev2df347a2014-07-18 10:17:07 +00002762void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2763 VisitOMPExecutableDirective(D);
2764}
2765
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002766void EnqueueVisitor::VisitOMPTaskgroupDirective(
2767 const OMPTaskgroupDirective *D) {
2768 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002769 if (const Expr *E = D->getReductionRef())
2770 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002771}
2772
Alexey Bataev6125da92014-07-21 11:26:11 +00002773void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2774 VisitOMPExecutableDirective(D);
2775}
2776
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002777void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2778 VisitOMPExecutableDirective(D);
2779}
2780
Alexey Bataev0162e452014-07-22 10:10:35 +00002781void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2782 VisitOMPExecutableDirective(D);
2783}
2784
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002785void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2786 VisitOMPExecutableDirective(D);
2787}
2788
Michael Wong65f367f2015-07-21 13:44:28 +00002789void EnqueueVisitor::VisitOMPTargetDataDirective(const
2790 OMPTargetDataDirective *D) {
2791 VisitOMPExecutableDirective(D);
2792}
2793
Samuel Antaodf67fc42016-01-19 19:15:56 +00002794void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2795 const OMPTargetEnterDataDirective *D) {
2796 VisitOMPExecutableDirective(D);
2797}
2798
Samuel Antao72590762016-01-19 20:04:50 +00002799void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2800 const OMPTargetExitDataDirective *D) {
2801 VisitOMPExecutableDirective(D);
2802}
2803
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002804void EnqueueVisitor::VisitOMPTargetParallelDirective(
2805 const OMPTargetParallelDirective *D) {
2806 VisitOMPExecutableDirective(D);
2807}
2808
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002809void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2810 const OMPTargetParallelForDirective *D) {
2811 VisitOMPLoopDirective(D);
2812}
2813
Alexey Bataev13314bf2014-10-09 04:18:56 +00002814void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2815 VisitOMPExecutableDirective(D);
2816}
2817
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002818void EnqueueVisitor::VisitOMPCancellationPointDirective(
2819 const OMPCancellationPointDirective *D) {
2820 VisitOMPExecutableDirective(D);
2821}
2822
Alexey Bataev80909872015-07-02 11:25:17 +00002823void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2824 VisitOMPExecutableDirective(D);
2825}
2826
Alexey Bataev49f6e782015-12-01 04:18:41 +00002827void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2828 VisitOMPLoopDirective(D);
2829}
2830
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002831void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2832 const OMPTaskLoopSimdDirective *D) {
2833 VisitOMPLoopDirective(D);
2834}
2835
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002836void EnqueueVisitor::VisitOMPDistributeDirective(
2837 const OMPDistributeDirective *D) {
2838 VisitOMPLoopDirective(D);
2839}
2840
Carlo Bertolli9925f152016-06-27 14:55:37 +00002841void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2842 const OMPDistributeParallelForDirective *D) {
2843 VisitOMPLoopDirective(D);
2844}
2845
Kelvin Li4a39add2016-07-05 05:00:15 +00002846void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2847 const OMPDistributeParallelForSimdDirective *D) {
2848 VisitOMPLoopDirective(D);
2849}
2850
Kelvin Li787f3fc2016-07-06 04:45:38 +00002851void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2852 const OMPDistributeSimdDirective *D) {
2853 VisitOMPLoopDirective(D);
2854}
2855
Kelvin Lia579b912016-07-14 02:54:56 +00002856void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2857 const OMPTargetParallelForSimdDirective *D) {
2858 VisitOMPLoopDirective(D);
2859}
2860
Kelvin Li986330c2016-07-20 22:57:10 +00002861void EnqueueVisitor::VisitOMPTargetSimdDirective(
2862 const OMPTargetSimdDirective *D) {
2863 VisitOMPLoopDirective(D);
2864}
2865
Kelvin Li02532872016-08-05 14:37:37 +00002866void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2867 const OMPTeamsDistributeDirective *D) {
2868 VisitOMPLoopDirective(D);
2869}
2870
Kelvin Li4e325f72016-10-25 12:50:55 +00002871void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2872 const OMPTeamsDistributeSimdDirective *D) {
2873 VisitOMPLoopDirective(D);
2874}
2875
Kelvin Li579e41c2016-11-30 23:51:03 +00002876void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2877 const OMPTeamsDistributeParallelForSimdDirective *D) {
2878 VisitOMPLoopDirective(D);
2879}
2880
Kelvin Li7ade93f2016-12-09 03:24:30 +00002881void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2882 const OMPTeamsDistributeParallelForDirective *D) {
2883 VisitOMPLoopDirective(D);
2884}
2885
Kelvin Libf594a52016-12-17 05:48:59 +00002886void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2887 const OMPTargetTeamsDirective *D) {
2888 VisitOMPExecutableDirective(D);
2889}
2890
Kelvin Li83c451e2016-12-25 04:52:54 +00002891void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2892 const OMPTargetTeamsDistributeDirective *D) {
2893 VisitOMPLoopDirective(D);
2894}
2895
Kelvin Li80e8f562016-12-29 22:16:30 +00002896void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2897 const OMPTargetTeamsDistributeParallelForDirective *D) {
2898 VisitOMPLoopDirective(D);
2899}
2900
Kelvin Li1851df52017-01-03 05:23:48 +00002901void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2902 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2903 VisitOMPLoopDirective(D);
2904}
2905
Kelvin Lida681182017-01-10 18:08:18 +00002906void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2907 const OMPTargetTeamsDistributeSimdDirective *D) {
2908 VisitOMPLoopDirective(D);
2909}
2910
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002911void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002912 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2913}
2914
2915bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2916 if (RegionOfInterest.isValid()) {
2917 SourceRange Range = getRawCursorExtent(C);
2918 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2919 return false;
2920 }
2921 return true;
2922}
2923
2924bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2925 while (!WL.empty()) {
2926 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002927 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002928
2929 // Set the Parent field, then back to its old value once we're done.
2930 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2931
2932 switch (LI.getKind()) {
2933 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002934 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 if (!D)
2936 continue;
2937
2938 // For now, perform default visitation for Decls.
2939 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2940 cast<DeclVisit>(&LI)->isFirst())))
2941 return true;
2942
2943 continue;
2944 }
2945 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002946 for (const TemplateArgumentLoc &Arg :
2947 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2948 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002949 return true;
2950 }
2951 continue;
2952 }
2953 case VisitorJob::TypeLocVisitKind: {
2954 // Perform default visitation for TypeLocs.
2955 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2956 return true;
2957 continue;
2958 }
2959 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002960 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 if (LabelStmt *stmt = LS->getStmt()) {
2962 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2963 TU))) {
2964 return true;
2965 }
2966 }
2967 continue;
2968 }
2969
2970 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2971 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2972 if (VisitNestedNameSpecifierLoc(V->get()))
2973 return true;
2974 continue;
2975 }
2976
2977 case VisitorJob::DeclarationNameInfoVisitKind: {
2978 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2979 ->get()))
2980 return true;
2981 continue;
2982 }
2983 case VisitorJob::MemberRefVisitKind: {
2984 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2985 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2986 return true;
2987 continue;
2988 }
2989 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002990 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002991 if (!S)
2992 continue;
2993
2994 // Update the current cursor.
2995 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2996 if (!IsInRegionOfInterest(Cursor))
2997 continue;
2998 switch (Visitor(Cursor, Parent, ClientData)) {
2999 case CXChildVisit_Break: return true;
3000 case CXChildVisit_Continue: break;
3001 case CXChildVisit_Recurse:
3002 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003003 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003004 EnqueueWorkList(WL, S);
3005 break;
3006 }
3007 continue;
3008 }
3009 case VisitorJob::MemberExprPartsKind: {
3010 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003011 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003012
3013 // Visit the nested-name-specifier
3014 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3015 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3016 return true;
3017
3018 // Visit the declaration name.
3019 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3020 return true;
3021
3022 // Visit the explicitly-specified template arguments, if any.
3023 if (M->hasExplicitTemplateArgs()) {
3024 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3025 *ArgEnd = Arg + M->getNumTemplateArgs();
3026 Arg != ArgEnd; ++Arg) {
3027 if (VisitTemplateArgumentLoc(*Arg))
3028 return true;
3029 }
3030 }
3031 continue;
3032 }
3033 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003034 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 // Visit nested-name-specifier, if present.
3036 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3037 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3038 return true;
3039 // Visit declaration name.
3040 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3041 return true;
3042 continue;
3043 }
3044 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003045 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 // Visit the nested-name-specifier.
3047 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3048 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3049 return true;
3050 // Visit the declaration name.
3051 if (VisitDeclarationNameInfo(O->getNameInfo()))
3052 return true;
3053 // Visit the overloaded declaration reference.
3054 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3055 return true;
3056 continue;
3057 }
3058 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003059 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 NamedDecl *Pack = E->getPack();
3061 if (isa<TemplateTypeParmDecl>(Pack)) {
3062 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3063 E->getPackLoc(), TU)))
3064 return true;
3065
3066 continue;
3067 }
3068
3069 if (isa<TemplateTemplateParmDecl>(Pack)) {
3070 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3071 E->getPackLoc(), TU)))
3072 return true;
3073
3074 continue;
3075 }
3076
3077 // Non-type template parameter packs and function parameter packs are
3078 // treated like DeclRefExpr cursors.
3079 continue;
3080 }
3081
3082 case VisitorJob::LambdaExprPartsKind: {
3083 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003084 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3086 CEnd = E->explicit_capture_end();
3087 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003088 // FIXME: Lambda init-captures.
3089 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003090 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003091
Guy Benyei11169dd2012-12-18 14:30:41 +00003092 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3093 C->getLocation(),
3094 TU)))
3095 return true;
3096 }
3097
3098 // Visit parameters and return type, if present.
3099 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
3100 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3101 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
3102 // Visit the whole type.
3103 if (Visit(TL))
3104 return true;
David Blaikie6adc78e2013-02-18 22:06:02 +00003105 } else if (FunctionProtoTypeLoc Proto =
3106 TL.getAs<FunctionProtoTypeLoc>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 if (E->hasExplicitParameters()) {
3108 // Visit parameters.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003109 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3110 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 return true;
3112 } else {
3113 // Visit result type.
Alp Toker42a16a62014-01-25 23:51:36 +00003114 if (Visit(Proto.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00003115 return true;
3116 }
3117 }
3118 }
3119 break;
3120 }
3121
3122 case VisitorJob::PostChildrenVisitKind:
3123 if (PostChildrenVisitor(Parent, ClientData))
3124 return true;
3125 break;
3126 }
3127 }
3128 return false;
3129}
3130
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003131bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003132 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 if (!WorkListFreeList.empty()) {
3134 WL = WorkListFreeList.back();
3135 WL->clear();
3136 WorkListFreeList.pop_back();
3137 }
3138 else {
3139 WL = new VisitorWorkList();
3140 WorkListCache.push_back(WL);
3141 }
3142 EnqueueWorkList(*WL, S);
3143 bool result = RunVisitorWorkList(*WL);
3144 WorkListFreeList.push_back(WL);
3145 return result;
3146}
3147
3148namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003149typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003150RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3151 const DeclarationNameInfo &NI, SourceRange QLoc,
3152 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3154 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3155 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3156
3157 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3158
3159 RefNamePieces Pieces;
3160
3161 if (WantQualifier && QLoc.isValid())
3162 Pieces.push_back(QLoc);
3163
3164 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3165 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003166
3167 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3168 Pieces.push_back(*TemplateArgsLoc);
3169
Guy Benyei11169dd2012-12-18 14:30:41 +00003170 if (Kind == DeclarationName::CXXOperatorName) {
3171 Pieces.push_back(SourceLocation::getFromRawEncoding(
3172 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3173 Pieces.push_back(SourceLocation::getFromRawEncoding(
3174 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3175 }
3176
3177 if (WantSinglePiece) {
3178 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3179 Pieces.clear();
3180 Pieces.push_back(R);
3181 }
3182
3183 return Pieces;
3184}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003185}
Guy Benyei11169dd2012-12-18 14:30:41 +00003186
3187//===----------------------------------------------------------------------===//
3188// Misc. API hooks.
3189//===----------------------------------------------------------------------===//
3190
Chad Rosier05c71aa2013-03-27 18:28:23 +00003191static void fatal_error_handler(void *user_data, const std::string& reason,
3192 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 // Write the result out to stderr avoiding errs() because raw_ostreams can
3194 // call report_fatal_error.
3195 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3196 ::abort();
3197}
3198
Chandler Carruth66660742014-06-27 16:37:27 +00003199namespace {
3200struct RegisterFatalErrorHandler {
3201 RegisterFatalErrorHandler() {
3202 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3203 }
3204};
3205}
3206
3207static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3208
Guy Benyei11169dd2012-12-18 14:30:41 +00003209CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3210 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003211 // We use crash recovery to make some of our APIs more reliable, implicitly
3212 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003213 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3214 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003215
Chandler Carruth66660742014-06-27 16:37:27 +00003216 // Look through the managed static to trigger construction of the managed
3217 // static which registers our fatal error handler. This ensures it is only
3218 // registered once.
3219 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003220
Adrian Prantlbc068582015-07-08 01:00:30 +00003221 // Initialize targets for clang module support.
3222 llvm::InitializeAllTargets();
3223 llvm::InitializeAllTargetMCs();
3224 llvm::InitializeAllAsmPrinters();
3225 llvm::InitializeAllAsmParsers();
3226
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003227 CIndexer *CIdxr = new CIndexer();
3228
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 if (excludeDeclarationsFromPCH)
3230 CIdxr->setOnlyLocalDecls();
3231 if (displayDiagnostics)
3232 CIdxr->setDisplayDiagnostics();
3233
3234 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3235 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3236 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3237 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3238 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3239 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3240
3241 return CIdxr;
3242}
3243
3244void clang_disposeIndex(CXIndex CIdx) {
3245 if (CIdx)
3246 delete static_cast<CIndexer *>(CIdx);
3247}
3248
3249void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3250 if (CIdx)
3251 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3252}
3253
3254unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3255 if (CIdx)
3256 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3257 return 0;
3258}
3259
Alex Lorenz08615792017-12-04 21:56:36 +00003260void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3261 const char *Path) {
3262 if (CIdx)
3263 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3264}
3265
Guy Benyei11169dd2012-12-18 14:30:41 +00003266void clang_toggleCrashRecovery(unsigned isEnabled) {
3267 if (isEnabled)
3268 llvm::CrashRecoveryContext::Enable();
3269 else
3270 llvm::CrashRecoveryContext::Disable();
3271}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003272
Guy Benyei11169dd2012-12-18 14:30:41 +00003273CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3274 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003275 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003276 enum CXErrorCode Result =
3277 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003278 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003279 assert((TU && Result == CXError_Success) ||
3280 (!TU && Result != CXError_Success));
3281 return TU;
3282}
3283
3284enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3285 const char *ast_filename,
3286 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003287 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003288 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003289
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003290 if (!CIdx || !ast_filename || !out_TU)
3291 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003292
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003293 LOG_FUNC_SECTION {
3294 *Log << ast_filename;
3295 }
3296
Guy Benyei11169dd2012-12-18 14:30:41 +00003297 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3298 FileSystemOptions FileSystemOpts;
3299
Justin Bognerd512c1e2014-10-15 00:33:06 +00003300 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3301 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003302 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003303 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3304 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003305 FileSystemOpts, /*UseDebugInfo=*/false,
3306 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003307 /*CaptureDiagnostics=*/true,
3308 /*AllowPCHWithCompilerErrors=*/true,
3309 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003310 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003311 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003312}
3313
3314unsigned clang_defaultEditingTranslationUnitOptions() {
3315 return CXTranslationUnit_PrecompiledPreamble |
3316 CXTranslationUnit_CacheCompletionResults;
3317}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003318
Guy Benyei11169dd2012-12-18 14:30:41 +00003319CXTranslationUnit
3320clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3321 const char *source_filename,
3322 int num_command_line_args,
3323 const char * const *command_line_args,
3324 unsigned num_unsaved_files,
3325 struct CXUnsavedFile *unsaved_files) {
3326 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3327 return clang_parseTranslationUnit(CIdx, source_filename,
3328 command_line_args, num_command_line_args,
3329 unsaved_files, num_unsaved_files,
3330 Options);
3331}
3332
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003333static CXErrorCode
3334clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3335 const char *const *command_line_args,
3336 int num_command_line_args,
3337 ArrayRef<CXUnsavedFile> unsaved_files,
3338 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003339 // Set up the initial return values.
3340 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003341 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003342
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003343 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003344 if (!CIdx || !out_TU)
3345 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003346
Guy Benyei11169dd2012-12-18 14:30:41 +00003347 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3348
3349 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3350 setThreadBackgroundPriority();
3351
3352 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003353 bool CreatePreambleOnFirstParse =
3354 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003355 // FIXME: Add a flag for modules.
3356 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003357 = (options & (CXTranslationUnit_Incomplete |
3358 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003359 bool CacheCodeCompletionResults
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 = options & CXTranslationUnit_CacheCompletionResults;
3361 bool IncludeBriefCommentsInCodeCompletion
3362 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3363 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003364 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003365 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3366
3367 // Configure the diagnostics.
3368 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003369 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003370
Manuel Klimek016c0242016-03-01 10:56:19 +00003371 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003372 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003373
Guy Benyei11169dd2012-12-18 14:30:41 +00003374 // Recover resources if we crash before exiting this function.
3375 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3376 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003377 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003378
Ahmed Charlesb8984322014-03-07 20:03:18 +00003379 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3380 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003381
3382 // Recover resources if we crash before exiting this function.
3383 llvm::CrashRecoveryContextCleanupRegistrar<
3384 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3385
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003386 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003387 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003388 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003389 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 }
3391
Ahmed Charlesb8984322014-03-07 20:03:18 +00003392 std::unique_ptr<std::vector<const char *>> Args(
3393 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003394
3395 // Recover resources if we crash before exiting this method.
3396 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3397 ArgsCleanup(Args.get());
3398
3399 // Since the Clang C library is primarily used by batch tools dealing with
3400 // (often very broken) source code, where spell-checking can have a
3401 // significant negative impact on performance (particularly when
3402 // precompiled headers are involved), we disable it by default.
3403 // Only do this if we haven't found a spell-checking-related argument.
3404 bool FoundSpellCheckingArgument = false;
3405 for (int I = 0; I != num_command_line_args; ++I) {
3406 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3407 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3408 FoundSpellCheckingArgument = true;
3409 break;
3410 }
3411 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003412 Args->insert(Args->end(), command_line_args,
3413 command_line_args + num_command_line_args);
3414
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003415 if (!FoundSpellCheckingArgument)
3416 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3417
Guy Benyei11169dd2012-12-18 14:30:41 +00003418 // The 'source_filename' argument is optional. If the caller does not
3419 // specify it then it is assumed that the source file is specified
3420 // in the actual argument list.
3421 // Put the source file after command_line_args otherwise if '-x' flag is
3422 // present it will be unused.
3423 if (source_filename)
3424 Args->push_back(source_filename);
3425
3426 // Do we need the detailed preprocessing record?
3427 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3428 Args->push_back("-Xclang");
3429 Args->push_back("-detailed-preprocessing-record");
3430 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003431
3432 // Suppress any editor placeholder diagnostics.
3433 Args->push_back("-fallow-editor-placeholders");
3434
Guy Benyei11169dd2012-12-18 14:30:41 +00003435 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003436 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003437 // Unless the user specified that they want the preamble on the first parse
3438 // set it up to be created on the first reparse. This makes the first parse
3439 // faster, trading for a slower (first) reparse.
3440 unsigned PrecompilePreambleAfterNParses =
3441 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003442
Alex Lorenz08615792017-12-04 21:56:36 +00003443 LibclangInvocationReporter InvocationReporter(
3444 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003445 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3446 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003447 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003448 Args->data(), Args->data() + Args->size(),
3449 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003450 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3451 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003452 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3453 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003454 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003455 /*UserFilesAreVolatile=*/true, ForSerialization,
3456 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3457 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003458
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003459 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003460 if (!Unit && !ErrUnit)
3461 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003462
Guy Benyei11169dd2012-12-18 14:30:41 +00003463 if (NumErrors != Diags->getClient()->getNumErrors()) {
3464 // Make sure to check that 'Unit' is non-NULL.
3465 if (CXXIdx->getDisplayDiagnostics())
3466 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3467 }
3468
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003469 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3470 return CXError_ASTReadError;
3471
David Blaikieea4395e2017-01-06 19:49:01 +00003472 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003473 if (CXTranslationUnitImpl *TU = *out_TU) {
3474 TU->ParsingOptions = options;
3475 TU->Arguments.reserve(Args->size());
3476 for (const char *Arg : *Args)
3477 TU->Arguments.push_back(Arg);
3478 return CXError_Success;
3479 }
3480 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003481}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003482
3483CXTranslationUnit
3484clang_parseTranslationUnit(CXIndex CIdx,
3485 const char *source_filename,
3486 const char *const *command_line_args,
3487 int num_command_line_args,
3488 struct CXUnsavedFile *unsaved_files,
3489 unsigned num_unsaved_files,
3490 unsigned options) {
3491 CXTranslationUnit TU;
3492 enum CXErrorCode Result = clang_parseTranslationUnit2(
3493 CIdx, source_filename, command_line_args, num_command_line_args,
3494 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003495 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003496 assert((TU && Result == CXError_Success) ||
3497 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003498 return TU;
3499}
3500
3501enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003502 CXIndex CIdx, const char *source_filename,
3503 const char *const *command_line_args, int num_command_line_args,
3504 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3505 unsigned options, CXTranslationUnit *out_TU) {
3506 SmallVector<const char *, 4> Args;
3507 Args.push_back("clang");
3508 Args.append(command_line_args, command_line_args + num_command_line_args);
3509 return clang_parseTranslationUnit2FullArgv(
3510 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3511 num_unsaved_files, options, out_TU);
3512}
3513
3514enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3515 CXIndex CIdx, const char *source_filename,
3516 const char *const *command_line_args, int num_command_line_args,
3517 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3518 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003519 LOG_FUNC_SECTION {
3520 *Log << source_filename << ": ";
3521 for (int i = 0; i != num_command_line_args; ++i)
3522 *Log << command_line_args[i] << " ";
3523 }
3524
Alp Toker9d85b182014-07-07 01:23:14 +00003525 if (num_unsaved_files && !unsaved_files)
3526 return CXError_InvalidArguments;
3527
Alp Toker5c532982014-07-07 22:42:03 +00003528 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003529 auto ParseTranslationUnitImpl = [=, &result] {
3530 result = clang_parseTranslationUnit_Impl(
3531 CIdx, source_filename, command_line_args, num_command_line_args,
3532 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3533 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003534
Guy Benyei11169dd2012-12-18 14:30:41 +00003535 llvm::CrashRecoveryContext CRC;
3536
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003537 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003538 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3539 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3540 fprintf(stderr, " 'command_line_args' : [");
3541 for (int i = 0; i != num_command_line_args; ++i) {
3542 if (i)
3543 fprintf(stderr, ", ");
3544 fprintf(stderr, "'%s'", command_line_args[i]);
3545 }
3546 fprintf(stderr, "],\n");
3547 fprintf(stderr, " 'unsaved_files' : [");
3548 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3549 if (i)
3550 fprintf(stderr, ", ");
3551 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3552 unsaved_files[i].Length);
3553 }
3554 fprintf(stderr, "],\n");
3555 fprintf(stderr, " 'options' : %d,\n", options);
3556 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003557
3558 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003559 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003560 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003561 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003562 }
Alp Toker5c532982014-07-07 22:42:03 +00003563
3564 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003565}
3566
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003567CXString clang_Type_getObjCEncoding(CXType CT) {
3568 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3569 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3570 std::string encoding;
3571 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3572 encoding);
3573
3574 return cxstring::createDup(encoding);
3575}
3576
3577static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3578 if (C.kind == CXCursor_MacroDefinition) {
3579 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3580 return MDR->getName();
3581 } else if (C.kind == CXCursor_MacroExpansion) {
3582 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3583 return ME.getName();
3584 }
3585 return nullptr;
3586}
3587
3588unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3589 const IdentifierInfo *II = getMacroIdentifier(C);
3590 if (!II) {
3591 return false;
3592 }
3593 ASTUnit *ASTU = getCursorASTUnit(C);
3594 Preprocessor &PP = ASTU->getPreprocessor();
3595 if (const MacroInfo *MI = PP.getMacroInfo(II))
3596 return MI->isFunctionLike();
3597 return false;
3598}
3599
3600unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3601 const IdentifierInfo *II = getMacroIdentifier(C);
3602 if (!II) {
3603 return false;
3604 }
3605 ASTUnit *ASTU = getCursorASTUnit(C);
3606 Preprocessor &PP = ASTU->getPreprocessor();
3607 if (const MacroInfo *MI = PP.getMacroInfo(II))
3608 return MI->isBuiltinMacro();
3609 return false;
3610}
3611
3612unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3613 const Decl *D = getCursorDecl(C);
3614 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3615 if (!FD) {
3616 return false;
3617 }
3618 return FD->isInlined();
3619}
3620
3621static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3622 if (callExpr->getNumArgs() != 1) {
3623 return nullptr;
3624 }
3625
3626 StringLiteral *S = nullptr;
3627 auto *arg = callExpr->getArg(0);
3628 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3629 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3630 auto *subExpr = I->getSubExprAsWritten();
3631
3632 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3633 return nullptr;
3634 }
3635
3636 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3637 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3638 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3639 } else {
3640 return nullptr;
3641 }
3642 return S;
3643}
3644
David Blaikie59272572016-04-13 18:23:33 +00003645struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003646 CXEvalResultKind EvalType;
3647 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003648 unsigned long long unsignedVal;
3649 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003650 double floatVal;
3651 char *stringVal;
3652 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003653 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003654 ~ExprEvalResult() {
3655 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3656 EvalType != CXEval_Int) {
3657 delete EvalData.stringVal;
3658 }
3659 }
3660};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003661
3662void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003663 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003664}
3665
3666CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3667 if (!E) {
3668 return CXEval_UnExposed;
3669 }
3670 return ((ExprEvalResult *)E)->EvalType;
3671}
3672
3673int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003674 return clang_EvalResult_getAsLongLong(E);
3675}
3676
3677long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003678 if (!E) {
3679 return 0;
3680 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003681 ExprEvalResult *Result = (ExprEvalResult*)E;
3682 if (Result->IsUnsignedInt)
3683 return Result->EvalData.unsignedVal;
3684 return Result->EvalData.intVal;
3685}
3686
3687unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3688 return ((ExprEvalResult *)E)->IsUnsignedInt;
3689}
3690
3691unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3692 if (!E) {
3693 return 0;
3694 }
3695
3696 ExprEvalResult *Result = (ExprEvalResult*)E;
3697 if (Result->IsUnsignedInt)
3698 return Result->EvalData.unsignedVal;
3699 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003700}
3701
3702double clang_EvalResult_getAsDouble(CXEvalResult E) {
3703 if (!E) {
3704 return 0;
3705 }
3706 return ((ExprEvalResult *)E)->EvalData.floatVal;
3707}
3708
3709const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3710 if (!E) {
3711 return nullptr;
3712 }
3713 return ((ExprEvalResult *)E)->EvalData.stringVal;
3714}
3715
3716static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3717 Expr::EvalResult ER;
3718 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003719 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003720 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003721
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003722 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003723 if (!expr->EvaluateAsRValue(ER, ctx))
3724 return nullptr;
3725
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003726 QualType rettype;
3727 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003728 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003729 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003730 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003731
David Blaikiebbc00882016-04-13 18:36:19 +00003732 if (ER.Val.isInt()) {
3733 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003734
3735 auto& val = ER.Val.getInt();
3736 if (val.isUnsigned()) {
3737 result->IsUnsignedInt = true;
3738 result->EvalData.unsignedVal = val.getZExtValue();
3739 } else {
3740 result->EvalData.intVal = val.getExtValue();
3741 }
3742
David Blaikiebbc00882016-04-13 18:36:19 +00003743 return result.release();
3744 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003745
David Blaikiebbc00882016-04-13 18:36:19 +00003746 if (ER.Val.isFloat()) {
3747 llvm::SmallVector<char, 100> Buffer;
3748 ER.Val.getFloat().toString(Buffer);
3749 std::string floatStr(Buffer.data(), Buffer.size());
3750 result->EvalType = CXEval_Float;
3751 bool ignored;
3752 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003753 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003754 llvm::APFloat::rmNearestTiesToEven, &ignored);
3755 result->EvalData.floatVal = apFloat.convertToDouble();
3756 return result.release();
3757 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003758
David Blaikiebbc00882016-04-13 18:36:19 +00003759 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3760 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3761 auto *subExpr = I->getSubExprAsWritten();
3762 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3763 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003764 const StringLiteral *StrE = nullptr;
3765 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003766 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003767
3768 if (ObjCExpr) {
3769 StrE = ObjCExpr->getString();
3770 result->EvalType = CXEval_ObjCStrLiteral;
3771 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003772 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003773 result->EvalType = CXEval_StrLiteral;
3774 }
3775
3776 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003777 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003778 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3779 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003780 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003781 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003782 }
3783 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3784 expr->getStmtClass() == Stmt::StringLiteralClass) {
3785 const StringLiteral *StrE = nullptr;
3786 const ObjCStringLiteral *ObjCExpr;
3787 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003788
David Blaikiebbc00882016-04-13 18:36:19 +00003789 if (ObjCExpr) {
3790 StrE = ObjCExpr->getString();
3791 result->EvalType = CXEval_ObjCStrLiteral;
3792 } else {
3793 StrE = cast<StringLiteral>(expr);
3794 result->EvalType = CXEval_StrLiteral;
3795 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003796
David Blaikiebbc00882016-04-13 18:36:19 +00003797 std::string strRef(StrE->getString().str());
3798 result->EvalData.stringVal = new char[strRef.size() + 1];
3799 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3800 result->EvalData.stringVal[strRef.size()] = '\0';
3801 return result.release();
3802 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003803
David Blaikiebbc00882016-04-13 18:36:19 +00003804 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3805 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003806
David Blaikiebbc00882016-04-13 18:36:19 +00003807 rettype = CC->getType();
3808 if (rettype.getAsString() == "CFStringRef" &&
3809 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003810
David Blaikiebbc00882016-04-13 18:36:19 +00003811 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3812 StringLiteral *S = getCFSTR_value(callExpr);
3813 if (S) {
3814 std::string strLiteral(S->getString().str());
3815 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003816
David Blaikiebbc00882016-04-13 18:36:19 +00003817 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3818 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3819 strLiteral.size());
3820 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003821 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003822 }
3823 }
3824
David Blaikiebbc00882016-04-13 18:36:19 +00003825 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3826 callExpr = static_cast<CallExpr *>(expr);
3827 rettype = callExpr->getCallReturnType(ctx);
3828
3829 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3830 return nullptr;
3831
3832 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3833 if (callExpr->getNumArgs() == 1 &&
3834 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3835 return nullptr;
3836 } else if (rettype.getAsString() == "CFStringRef") {
3837
3838 StringLiteral *S = getCFSTR_value(callExpr);
3839 if (S) {
3840 std::string strLiteral(S->getString().str());
3841 result->EvalType = CXEval_CFStr;
3842 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3843 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3844 strLiteral.size());
3845 result->EvalData.stringVal[strLiteral.size()] = '\0';
3846 return result.release();
3847 }
3848 }
3849 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3850 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3851 ValueDecl *V = D->getDecl();
3852 if (V->getKind() == Decl::Function) {
3853 std::string strName = V->getNameAsString();
3854 result->EvalType = CXEval_Other;
3855 result->EvalData.stringVal = new char[strName.size() + 1];
3856 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3857 result->EvalData.stringVal[strName.size()] = '\0';
3858 return result.release();
3859 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003860 }
3861
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003862 return nullptr;
3863}
3864
3865CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3866 const Decl *D = getCursorDecl(C);
3867 if (D) {
3868 const Expr *expr = nullptr;
3869 if (auto *Var = dyn_cast<VarDecl>(D)) {
3870 expr = Var->getInit();
3871 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3872 expr = Field->getInClassInitializer();
3873 }
3874 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003875 return const_cast<CXEvalResult>(reinterpret_cast<const void *>(
3876 evaluateExpr(const_cast<Expr *>(expr), C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003877 return nullptr;
3878 }
3879
3880 const CompoundStmt *compoundStmt = dyn_cast_or_null<CompoundStmt>(getCursorStmt(C));
3881 if (compoundStmt) {
3882 Expr *expr = nullptr;
3883 for (auto *bodyIterator : compoundStmt->body()) {
3884 if ((expr = dyn_cast<Expr>(bodyIterator))) {
3885 break;
3886 }
3887 }
3888 if (expr)
Aaron Ballman01dc1572016-01-20 15:25:30 +00003889 return const_cast<CXEvalResult>(
3890 reinterpret_cast<const void *>(evaluateExpr(expr, C)));
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003891 }
3892 return nullptr;
3893}
3894
3895unsigned clang_Cursor_hasAttrs(CXCursor C) {
3896 const Decl *D = getCursorDecl(C);
3897 if (!D) {
3898 return 0;
3899 }
3900
3901 if (D->hasAttrs()) {
3902 return 1;
3903 }
3904
3905 return 0;
3906}
Guy Benyei11169dd2012-12-18 14:30:41 +00003907unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3908 return CXSaveTranslationUnit_None;
3909}
3910
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003911static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3912 const char *FileName,
3913 unsigned options) {
3914 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003915 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3916 setThreadBackgroundPriority();
3917
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003918 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3919 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003920}
3921
3922int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3923 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003924 LOG_FUNC_SECTION {
3925 *Log << TU << ' ' << FileName;
3926 }
3927
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003928 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003929 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003930 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003931 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003932
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003933 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003934 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3935 if (!CXXUnit->hasSema())
3936 return CXSaveError_InvalidTU;
3937
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003938 CXSaveError result;
3939 auto SaveTranslationUnitImpl = [=, &result]() {
3940 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3941 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003942
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003943 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003944 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003945
3946 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3947 PrintLibclangResourceUsage(TU);
3948
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003949 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 }
3951
3952 // We have an AST that has invalid nodes due to compiler errors.
3953 // Use a crash recovery thread for protection.
3954
3955 llvm::CrashRecoveryContext CRC;
3956
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003957 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003958 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3959 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3960 fprintf(stderr, " 'options' : %d,\n", options);
3961 fprintf(stderr, "}\n");
3962
3963 return CXSaveError_Unknown;
3964
3965 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3966 PrintLibclangResourceUsage(TU);
3967 }
3968
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003969 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003970}
3971
3972void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3973 if (CTUnit) {
3974 // If the translation unit has been marked as unsafe to free, just discard
3975 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003976 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3977 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00003978 return;
3979
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003980 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00003981 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00003982 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3983 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00003984 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00003985 delete CTUnit;
3986 }
3987}
3988
Erik Verbruggen346066b2017-05-30 14:25:54 +00003989unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
3990 if (CTUnit) {
3991 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3992
3993 if (Unit && Unit->isUnsafeToFree())
3994 return false;
3995
3996 Unit->ResetForParse();
3997 return true;
3998 }
3999
4000 return false;
4001}
4002
Guy Benyei11169dd2012-12-18 14:30:41 +00004003unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4004 return CXReparse_None;
4005}
4006
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004007static CXErrorCode
4008clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4009 ArrayRef<CXUnsavedFile> unsaved_files,
4010 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004011 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004012 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004013 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004014 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004015 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004016
4017 // Reset the associated diagnostics.
4018 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004019 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004020
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004021 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004022 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4023 setThreadBackgroundPriority();
4024
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004025 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004026 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004027
4028 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4029 new std::vector<ASTUnit::RemappedFile>());
4030
Guy Benyei11169dd2012-12-18 14:30:41 +00004031 // Recover resources if we crash before exiting this function.
4032 llvm::CrashRecoveryContextCleanupRegistrar<
4033 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004034
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004035 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004036 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004037 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004038 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004039 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004040
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004041 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4042 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004043 return CXError_Success;
4044 if (isASTReadError(CXXUnit))
4045 return CXError_ASTReadError;
4046 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004047}
4048
4049int clang_reparseTranslationUnit(CXTranslationUnit TU,
4050 unsigned num_unsaved_files,
4051 struct CXUnsavedFile *unsaved_files,
4052 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004053 LOG_FUNC_SECTION {
4054 *Log << TU;
4055 }
4056
Alp Toker9d85b182014-07-07 01:23:14 +00004057 if (num_unsaved_files && !unsaved_files)
4058 return CXError_InvalidArguments;
4059
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004060 CXErrorCode result;
4061 auto ReparseTranslationUnitImpl = [=, &result]() {
4062 result = clang_reparseTranslationUnit_Impl(
4063 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4064 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004065
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 llvm::CrashRecoveryContext CRC;
4067
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004068 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004069 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004070 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004071 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004072 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4073 PrintLibclangResourceUsage(TU);
4074
Alp Toker5c532982014-07-07 22:42:03 +00004075 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004076}
4077
4078
4079CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004080 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004081 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004082 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004083 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004084
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004085 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004086 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004087}
4088
4089CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004090 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004091 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004092 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004093 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004094
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004095 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4097}
4098
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004099CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4100 if (isNotUsableTU(CTUnit)) {
4101 LOG_BAD_TU(CTUnit);
4102 return nullptr;
4103 }
4104
4105 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4106 impl->TranslationUnit = CTUnit;
4107 return impl;
4108}
4109
4110CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4111 if (!TargetInfo)
4112 return cxstring::createEmpty();
4113
4114 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4115 assert(!isNotUsableTU(CTUnit) &&
4116 "Unexpected unusable translation unit in TargetInfo");
4117
4118 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4119 std::string Triple =
4120 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4121 return cxstring::createDup(Triple);
4122}
4123
4124int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4125 if (!TargetInfo)
4126 return -1;
4127
4128 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4129 assert(!isNotUsableTU(CTUnit) &&
4130 "Unexpected unusable translation unit in TargetInfo");
4131
4132 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4133 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4134}
4135
4136void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4137 if (!TargetInfo)
4138 return;
4139
4140 delete TargetInfo;
4141}
4142
Guy Benyei11169dd2012-12-18 14:30:41 +00004143//===----------------------------------------------------------------------===//
4144// CXFile Operations.
4145//===----------------------------------------------------------------------===//
4146
Guy Benyei11169dd2012-12-18 14:30:41 +00004147CXString clang_getFileName(CXFile SFile) {
4148 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004149 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004150
4151 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004152 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004153}
4154
4155time_t clang_getFileTime(CXFile SFile) {
4156 if (!SFile)
4157 return 0;
4158
4159 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4160 return FEnt->getModificationTime();
4161}
4162
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004163CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004164 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004165 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004166 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004167 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004168
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004169 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004170
4171 FileManager &FMgr = CXXUnit->getFileManager();
4172 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4173}
4174
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004175const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4176 size_t *size) {
4177 if (isNotUsableTU(TU)) {
4178 LOG_BAD_TU(TU);
4179 return nullptr;
4180 }
4181
4182 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4183 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4184 bool Invalid = true;
4185 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4186 if (Invalid) {
4187 if (size)
4188 *size = 0;
4189 return nullptr;
4190 }
4191 if (size)
4192 *size = buf->getBufferSize();
4193 return buf->getBufferStart();
4194}
4195
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004196unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4197 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004198 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004199 LOG_BAD_TU(TU);
4200 return 0;
4201 }
4202
4203 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 return 0;
4205
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004206 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 FileEntry *FEnt = static_cast<FileEntry *>(file);
4208 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4209 .isFileMultipleIncludeGuarded(FEnt);
4210}
4211
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004212int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4213 if (!file || !outID)
4214 return 1;
4215
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004216 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004217 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4218 outID->data[0] = ID.getDevice();
4219 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004220 outID->data[2] = FEnt->getModificationTime();
4221 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004222}
4223
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004224int clang_File_isEqual(CXFile file1, CXFile file2) {
4225 if (file1 == file2)
4226 return true;
4227
4228 if (!file1 || !file2)
4229 return false;
4230
4231 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4232 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4233 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4234}
4235
Guy Benyei11169dd2012-12-18 14:30:41 +00004236//===----------------------------------------------------------------------===//
4237// CXCursor Operations.
4238//===----------------------------------------------------------------------===//
4239
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004240static const Decl *getDeclFromExpr(const Stmt *E) {
4241 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004242 return getDeclFromExpr(CE->getSubExpr());
4243
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004244 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004246 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004247 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004248 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004250 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 if (PRE->isExplicitProperty())
4252 return PRE->getExplicitProperty();
4253 // It could be messaging both getter and setter as in:
4254 // ++myobj.myprop;
4255 // in which case prefer to associate the setter since it is less obvious
4256 // from inspecting the source that the setter is going to get called.
4257 if (PRE->isMessagingSetter())
4258 return PRE->getImplicitPropertySetter();
4259 return PRE->getImplicitPropertyGetter();
4260 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004261 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004262 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004263 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 if (Expr *Src = OVE->getSourceExpr())
4265 return getDeclFromExpr(Src);
4266
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004267 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004269 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004270 if (!CE->isElidable())
4271 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004272 if (const CXXInheritedCtorInitExpr *CE =
4273 dyn_cast<CXXInheritedCtorInitExpr>(E))
4274 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004275 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004276 return OME->getMethodDecl();
4277
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004278 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004280 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004281 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4282 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004283 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004284 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4285 isa<ParmVarDecl>(SizeOfPack->getPack()))
4286 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004287
4288 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004289}
4290
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004291static SourceLocation getLocationFromExpr(const Expr *E) {
4292 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 return getLocationFromExpr(CE->getSubExpr());
4294
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004295 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004297 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004299 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004301 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004302 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004303 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004305 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004306 return PropRef->getLocation();
4307
4308 return E->getLocStart();
4309}
4310
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004311extern "C" {
4312
Guy Benyei11169dd2012-12-18 14:30:41 +00004313unsigned clang_visitChildren(CXCursor parent,
4314 CXCursorVisitor visitor,
4315 CXClientData client_data) {
4316 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4317 /*VisitPreprocessorLast=*/false);
4318 return CursorVis.VisitChildren(parent);
4319}
4320
4321#ifndef __has_feature
4322#define __has_feature(x) 0
4323#endif
4324#if __has_feature(blocks)
4325typedef enum CXChildVisitResult
4326 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4327
4328static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4329 CXClientData client_data) {
4330 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4331 return block(cursor, parent);
4332}
4333#else
4334// If we are compiled with a compiler that doesn't have native blocks support,
4335// define and call the block manually, so the
4336typedef struct _CXChildVisitResult
4337{
4338 void *isa;
4339 int flags;
4340 int reserved;
4341 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4342 CXCursor);
4343} *CXCursorVisitorBlock;
4344
4345static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4346 CXClientData client_data) {
4347 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4348 return block->invoke(block, cursor, parent);
4349}
4350#endif
4351
4352
4353unsigned clang_visitChildrenWithBlock(CXCursor parent,
4354 CXCursorVisitorBlock block) {
4355 return clang_visitChildren(parent, visitWithBlock, block);
4356}
4357
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004358static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004359 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004360 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004361
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004362 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004364 if (const ObjCPropertyImplDecl *PropImpl =
4365 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004367 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004368
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004369 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004371 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004372
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004373 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 }
4375
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004376 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004377 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004378
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004379 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4381 // and returns different names. NamedDecl returns the class name and
4382 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004383 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004384
4385 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004386 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004387
4388 SmallString<1024> S;
4389 llvm::raw_svector_ostream os(S);
4390 ND->printName(os);
4391
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004392 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004393}
4394
4395CXString clang_getCursorSpelling(CXCursor C) {
4396 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004397 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004398
4399 if (clang_isReference(C.kind)) {
4400 switch (C.kind) {
4401 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004402 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004403 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 }
4405 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004406 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004407 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004408 }
4409 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004410 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004412 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004413 }
4414 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004415 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004416 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 }
4418 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004419 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 assert(Type && "Missing type decl");
4421
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004422 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 getAsString());
4424 }
4425 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004426 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 assert(Template && "Missing template decl");
4428
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004429 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 }
4431
4432 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004433 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 assert(NS && "Missing namespace decl");
4435
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004436 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 }
4438
4439 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004440 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 assert(Field && "Missing member decl");
4442
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004443 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 }
4445
4446 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004447 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 assert(Label && "Missing label");
4449
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004450 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 }
4452
4453 case CXCursor_OverloadedDeclRef: {
4454 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004455 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4456 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004457 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004458 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004460 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004461 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 OverloadedTemplateStorage *Ovl
4463 = Storage.get<OverloadedTemplateStorage*>();
4464 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004465 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004466 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 }
4468
4469 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004470 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004471 assert(Var && "Missing variable decl");
4472
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004473 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 }
4475
4476 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004477 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 }
4479 }
4480
4481 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004482 const Expr *E = getCursorExpr(C);
4483
4484 if (C.kind == CXCursor_ObjCStringLiteral ||
4485 C.kind == CXCursor_StringLiteral) {
4486 const StringLiteral *SLit;
4487 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4488 SLit = OSL->getString();
4489 } else {
4490 SLit = cast<StringLiteral>(E);
4491 }
4492 SmallString<256> Buf;
4493 llvm::raw_svector_ostream OS(Buf);
4494 SLit->outputString(OS);
4495 return cxstring::createDup(OS.str());
4496 }
4497
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004498 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 if (D)
4500 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004501 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 }
4503
4504 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004505 const Stmt *S = getCursorStmt(C);
4506 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004507 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004508
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004509 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 }
4511
4512 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004513 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 ->getNameStart());
4515
4516 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004517 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 ->getNameStart());
4519
4520 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004521 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004522
4523 if (clang_isDeclaration(C.kind))
4524 return getDeclSpelling(getCursorDecl(C));
4525
4526 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004527 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004528 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 }
4530
4531 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004532 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004533 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 }
4535
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004536 if (C.kind == CXCursor_PackedAttr) {
4537 return cxstring::createRef("packed");
4538 }
4539
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004540 if (C.kind == CXCursor_VisibilityAttr) {
4541 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4542 switch (AA->getVisibility()) {
4543 case VisibilityAttr::VisibilityType::Default:
4544 return cxstring::createRef("default");
4545 case VisibilityAttr::VisibilityType::Hidden:
4546 return cxstring::createRef("hidden");
4547 case VisibilityAttr::VisibilityType::Protected:
4548 return cxstring::createRef("protected");
4549 }
4550 llvm_unreachable("unknown visibility type");
4551 }
4552
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004553 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004554}
4555
4556CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4557 unsigned pieceIndex,
4558 unsigned options) {
4559 if (clang_Cursor_isNull(C))
4560 return clang_getNullRange();
4561
4562 ASTContext &Ctx = getCursorContext(C);
4563
4564 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004565 const Stmt *S = getCursorStmt(C);
4566 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 if (pieceIndex > 0)
4568 return clang_getNullRange();
4569 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4570 }
4571
4572 return clang_getNullRange();
4573 }
4574
4575 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004576 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4578 if (pieceIndex >= ME->getNumSelectorLocs())
4579 return clang_getNullRange();
4580 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4581 }
4582 }
4583
4584 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4585 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004586 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4588 if (pieceIndex >= MD->getNumSelectorLocs())
4589 return clang_getNullRange();
4590 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4591 }
4592 }
4593
4594 if (C.kind == CXCursor_ObjCCategoryDecl ||
4595 C.kind == CXCursor_ObjCCategoryImplDecl) {
4596 if (pieceIndex > 0)
4597 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004598 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4600 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004601 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4603 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4604 }
4605
4606 if (C.kind == CXCursor_ModuleImportDecl) {
4607 if (pieceIndex > 0)
4608 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004609 if (const ImportDecl *ImportD =
4610 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4612 if (!Locs.empty())
4613 return cxloc::translateSourceRange(Ctx,
4614 SourceRange(Locs.front(), Locs.back()));
4615 }
4616 return clang_getNullRange();
4617 }
4618
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004619 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004620 C.kind == CXCursor_ConversionFunction ||
4621 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004622 if (pieceIndex > 0)
4623 return clang_getNullRange();
4624 if (const FunctionDecl *FD =
4625 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4626 DeclarationNameInfo FunctionName = FD->getNameInfo();
4627 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4628 }
4629 return clang_getNullRange();
4630 }
4631
Guy Benyei11169dd2012-12-18 14:30:41 +00004632 // FIXME: A CXCursor_InclusionDirective should give the location of the
4633 // filename, but we don't keep track of this.
4634
4635 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4636 // but we don't keep track of this.
4637
4638 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4639 // but we don't keep track of this.
4640
4641 // Default handling, give the location of the cursor.
4642
4643 if (pieceIndex > 0)
4644 return clang_getNullRange();
4645
4646 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4647 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4648 return cxloc::translateSourceRange(Ctx, Loc);
4649}
4650
Eli Bendersky44a206f2014-07-31 18:04:56 +00004651CXString clang_Cursor_getMangling(CXCursor C) {
4652 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4653 return cxstring::createEmpty();
4654
Eli Bendersky44a206f2014-07-31 18:04:56 +00004655 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004656 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004657 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4658 return cxstring::createEmpty();
4659
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004660 ASTContext &Ctx = D->getASTContext();
4661 index::CodegenNameGenerator CGNameGen(Ctx);
4662 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004663}
4664
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004665CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4666 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4667 return nullptr;
4668
4669 const Decl *D = getCursorDecl(C);
4670 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4671 return nullptr;
4672
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004673 ASTContext &Ctx = D->getASTContext();
4674 index::CodegenNameGenerator CGNameGen(Ctx);
4675 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004676 return cxstring::createSet(Manglings);
4677}
4678
Dave Lee1a532c92017-09-22 16:58:57 +00004679CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4680 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4681 return nullptr;
4682
4683 const Decl *D = getCursorDecl(C);
4684 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4685 return nullptr;
4686
4687 ASTContext &Ctx = D->getASTContext();
4688 index::CodegenNameGenerator CGNameGen(Ctx);
4689 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4690 return cxstring::createSet(Manglings);
4691}
4692
Guy Benyei11169dd2012-12-18 14:30:41 +00004693CXString clang_getCursorDisplayName(CXCursor C) {
4694 if (!clang_isDeclaration(C.kind))
4695 return clang_getCursorSpelling(C);
4696
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004697 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004699 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004700
4701 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004702 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 D = FunTmpl->getTemplatedDecl();
4704
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004705 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004706 SmallString<64> Str;
4707 llvm::raw_svector_ostream OS(Str);
4708 OS << *Function;
4709 if (Function->getPrimaryTemplate())
4710 OS << "<>";
4711 OS << "(";
4712 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4713 if (I)
4714 OS << ", ";
4715 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4716 }
4717
4718 if (Function->isVariadic()) {
4719 if (Function->getNumParams())
4720 OS << ", ";
4721 OS << "...";
4722 }
4723 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004724 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 }
4726
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004727 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004728 SmallString<64> Str;
4729 llvm::raw_svector_ostream OS(Str);
4730 OS << *ClassTemplate;
4731 OS << "<";
4732 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4733 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4734 if (I)
4735 OS << ", ";
4736
4737 NamedDecl *Param = Params->getParam(I);
4738 if (Param->getIdentifier()) {
4739 OS << Param->getIdentifier()->getName();
4740 continue;
4741 }
4742
4743 // There is no parameter name, which makes this tricky. Try to come up
4744 // with something useful that isn't too long.
4745 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4746 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4747 else if (NonTypeTemplateParmDecl *NTTP
4748 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4749 OS << NTTP->getType().getAsString(Policy);
4750 else
4751 OS << "template<...> class";
4752 }
4753
4754 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004755 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004756 }
4757
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004758 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4760 // If the type was explicitly written, use that.
4761 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004762 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00004763
Benjamin Kramer9170e912013-02-22 15:46:01 +00004764 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 llvm::raw_svector_ostream OS(Str);
4766 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00004767 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
4768 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004769 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004770 }
4771
4772 return clang_getCursorSpelling(C);
4773}
4774
4775CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
4776 switch (Kind) {
4777 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004778 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004780 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004782 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004784 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004786 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004788 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004789 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004790 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004791 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004792 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004794 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004795 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004796 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004797 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004798 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004800 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004802 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004803 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004804 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004806 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004808 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004810 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004812 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004814 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004816 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004818 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004820 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004822 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004824 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004826 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004827 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004828 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004829 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004830 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004832 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004833 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004834 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004836 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004838 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00004839 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004840 return cxstring::createRef("IntegerLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004841 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004842 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004843 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004844 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004846 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004848 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004849 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004850 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004851 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004852 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004853 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004854 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004855 case CXCursor_OMPArraySectionExpr:
4856 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004857 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004858 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004860 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004861 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004862 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00004863 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004864 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004866 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004868 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004869 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004870 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004871 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004872 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004874 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004876 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004877 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004878 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004880 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004881 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004882 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004884 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004886 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004888 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004890 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004891 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004892 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004894 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004895 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004896 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004898 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004899 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004900 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004901 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004902 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004904 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00004905 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004906 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00004907 case CXCursor_ObjCAvailabilityCheckExpr:
4908 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00004909 case CXCursor_ObjCSelfExpr:
4910 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004912 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004914 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004916 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004917 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004918 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004920 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004921 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004922 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004924 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004925 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004926 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004927 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004928 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004929 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004930 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004931 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004932 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004933 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004934 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004936 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00004937 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004938 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004939 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004940 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004941 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004942 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004943 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004944 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004946 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004947 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004948 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004950 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004952 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004953 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004954 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004955 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004956 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004958 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004960 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004962 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004963 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004964 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004965 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004966 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004968 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004969 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004970 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004971 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004972 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004974 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004975 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004976 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004977 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004978 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004979 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004980 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004982 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004983 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004984 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004985 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004986 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004987 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004988 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004989 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004990 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004992 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004993 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004994 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004996 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00004997 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004998 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00004999 case CXCursor_SEHLeaveStmt:
5000 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005002 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005004 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005005 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005006 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005007 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005008 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005010 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005011 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005012 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005014 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005016 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005018 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005019 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005020 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005022 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005024 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005026 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005028 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005029 case CXCursor_PackedAttr:
5030 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005031 case CXCursor_PureAttr:
5032 return cxstring::createRef("attribute(pure)");
5033 case CXCursor_ConstAttr:
5034 return cxstring::createRef("attribute(const)");
5035 case CXCursor_NoDuplicateAttr:
5036 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005037 case CXCursor_CUDAConstantAttr:
5038 return cxstring::createRef("attribute(constant)");
5039 case CXCursor_CUDADeviceAttr:
5040 return cxstring::createRef("attribute(device)");
5041 case CXCursor_CUDAGlobalAttr:
5042 return cxstring::createRef("attribute(global)");
5043 case CXCursor_CUDAHostAttr:
5044 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005045 case CXCursor_CUDASharedAttr:
5046 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005047 case CXCursor_VisibilityAttr:
5048 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005049 case CXCursor_DLLExport:
5050 return cxstring::createRef("attribute(dllexport)");
5051 case CXCursor_DLLImport:
5052 return cxstring::createRef("attribute(dllimport)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005066 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005072 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005078 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005082 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005084 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005088 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005092 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005094 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005096 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005100 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005101 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005102 return cxstring::createRef("OMPParallelDirective");
5103 case CXCursor_OMPSimdDirective:
5104 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005105 case CXCursor_OMPForDirective:
5106 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005107 case CXCursor_OMPForSimdDirective:
5108 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005109 case CXCursor_OMPSectionsDirective:
5110 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005111 case CXCursor_OMPSectionDirective:
5112 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005113 case CXCursor_OMPSingleDirective:
5114 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005115 case CXCursor_OMPMasterDirective:
5116 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005117 case CXCursor_OMPCriticalDirective:
5118 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005119 case CXCursor_OMPParallelForDirective:
5120 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005121 case CXCursor_OMPParallelForSimdDirective:
5122 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005123 case CXCursor_OMPParallelSectionsDirective:
5124 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005125 case CXCursor_OMPTaskDirective:
5126 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005127 case CXCursor_OMPTaskyieldDirective:
5128 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005129 case CXCursor_OMPBarrierDirective:
5130 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005131 case CXCursor_OMPTaskwaitDirective:
5132 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005133 case CXCursor_OMPTaskgroupDirective:
5134 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005135 case CXCursor_OMPFlushDirective:
5136 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005137 case CXCursor_OMPOrderedDirective:
5138 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005139 case CXCursor_OMPAtomicDirective:
5140 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005141 case CXCursor_OMPTargetDirective:
5142 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005143 case CXCursor_OMPTargetDataDirective:
5144 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005145 case CXCursor_OMPTargetEnterDataDirective:
5146 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005147 case CXCursor_OMPTargetExitDataDirective:
5148 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005149 case CXCursor_OMPTargetParallelDirective:
5150 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005151 case CXCursor_OMPTargetParallelForDirective:
5152 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005153 case CXCursor_OMPTargetUpdateDirective:
5154 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005155 case CXCursor_OMPTeamsDirective:
5156 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005157 case CXCursor_OMPCancellationPointDirective:
5158 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005159 case CXCursor_OMPCancelDirective:
5160 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005161 case CXCursor_OMPTaskLoopDirective:
5162 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005163 case CXCursor_OMPTaskLoopSimdDirective:
5164 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005165 case CXCursor_OMPDistributeDirective:
5166 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005167 case CXCursor_OMPDistributeParallelForDirective:
5168 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005169 case CXCursor_OMPDistributeParallelForSimdDirective:
5170 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005171 case CXCursor_OMPDistributeSimdDirective:
5172 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005173 case CXCursor_OMPTargetParallelForSimdDirective:
5174 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005175 case CXCursor_OMPTargetSimdDirective:
5176 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005177 case CXCursor_OMPTeamsDistributeDirective:
5178 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005179 case CXCursor_OMPTeamsDistributeSimdDirective:
5180 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005181 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5182 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005183 case CXCursor_OMPTeamsDistributeParallelForDirective:
5184 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005185 case CXCursor_OMPTargetTeamsDirective:
5186 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005187 case CXCursor_OMPTargetTeamsDistributeDirective:
5188 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005189 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5190 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005191 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5192 return cxstring::createRef(
5193 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005194 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5195 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005196 case CXCursor_OverloadCandidate:
5197 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005198 case CXCursor_TypeAliasTemplateDecl:
5199 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005200 case CXCursor_StaticAssert:
5201 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005202 case CXCursor_FriendDecl:
5203 return cxstring::createRef("FriendDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 }
5205
5206 llvm_unreachable("Unhandled CXCursorKind");
5207}
5208
5209struct GetCursorData {
5210 SourceLocation TokenBeginLoc;
5211 bool PointsAtMacroArgExpansion;
5212 bool VisitedObjCPropertyImplDecl;
5213 SourceLocation VisitedDeclaratorDeclStartLoc;
5214 CXCursor &BestCursor;
5215
5216 GetCursorData(SourceManager &SM,
5217 SourceLocation tokenBegin, CXCursor &outputCursor)
5218 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5219 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5220 VisitedObjCPropertyImplDecl = false;
5221 }
5222};
5223
5224static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5225 CXCursor parent,
5226 CXClientData client_data) {
5227 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5228 CXCursor *BestCursor = &Data->BestCursor;
5229
5230 // If we point inside a macro argument we should provide info of what the
5231 // token is so use the actual cursor, don't replace it with a macro expansion
5232 // cursor.
5233 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5234 return CXChildVisit_Recurse;
5235
5236 if (clang_isDeclaration(cursor.kind)) {
5237 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005238 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5240 if (MD->isImplicit())
5241 return CXChildVisit_Break;
5242
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005243 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5245 // Check that when we have multiple @class references in the same line,
5246 // that later ones do not override the previous ones.
5247 // If we have:
5248 // @class Foo, Bar;
5249 // source ranges for both start at '@', so 'Bar' will end up overriding
5250 // 'Foo' even though the cursor location was at 'Foo'.
5251 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5252 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005253 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5255 if (PrevID != ID &&
5256 !PrevID->isThisDeclarationADefinition() &&
5257 !ID->isThisDeclarationADefinition())
5258 return CXChildVisit_Break;
5259 }
5260
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005261 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5263 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5264 // Check that when we have multiple declarators in the same line,
5265 // that later ones do not override the previous ones.
5266 // If we have:
5267 // int Foo, Bar;
5268 // source ranges for both start at 'int', so 'Bar' will end up overriding
5269 // 'Foo' even though the cursor location was at 'Foo'.
5270 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5271 return CXChildVisit_Break;
5272 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5273
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005274 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005275 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5276 (void)PropImp;
5277 // Check that when we have multiple @synthesize in the same line,
5278 // that later ones do not override the previous ones.
5279 // If we have:
5280 // @synthesize Foo, Bar;
5281 // source ranges for both start at '@', so 'Bar' will end up overriding
5282 // 'Foo' even though the cursor location was at 'Foo'.
5283 if (Data->VisitedObjCPropertyImplDecl)
5284 return CXChildVisit_Break;
5285 Data->VisitedObjCPropertyImplDecl = true;
5286 }
5287 }
5288
5289 if (clang_isExpression(cursor.kind) &&
5290 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005291 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 // Avoid having the cursor of an expression replace the declaration cursor
5293 // when the expression source range overlaps the declaration range.
5294 // This can happen for C++ constructor expressions whose range generally
5295 // include the variable declaration, e.g.:
5296 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5297 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5298 D->getLocation() == Data->TokenBeginLoc)
5299 return CXChildVisit_Break;
5300 }
5301 }
5302
5303 // If our current best cursor is the construction of a temporary object,
5304 // don't replace that cursor with a type reference, because we want
5305 // clang_getCursor() to point at the constructor.
5306 if (clang_isExpression(BestCursor->kind) &&
5307 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5308 cursor.kind == CXCursor_TypeRef) {
5309 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5310 // as having the actual point on the type reference.
5311 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5312 return CXChildVisit_Recurse;
5313 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005314
5315 // If we already have an Objective-C superclass reference, don't
5316 // update it further.
5317 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5318 return CXChildVisit_Break;
5319
Guy Benyei11169dd2012-12-18 14:30:41 +00005320 *BestCursor = cursor;
5321 return CXChildVisit_Recurse;
5322}
5323
5324CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005325 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005326 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005327 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005328 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005329
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005330 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005331 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5332
5333 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5334 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5335
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005336 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 CXFile SearchFile;
5338 unsigned SearchLine, SearchColumn;
5339 CXFile ResultFile;
5340 unsigned ResultLine, ResultColumn;
5341 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5342 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5343 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005344
5345 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5346 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005347 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005348 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 SearchFileName = clang_getFileName(SearchFile);
5350 ResultFileName = clang_getFileName(ResultFile);
5351 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5352 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005353 *Log << llvm::format("(%s:%d:%d) = %s",
5354 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5355 clang_getCString(KindSpelling))
5356 << llvm::format("(%s:%d:%d):%s%s",
5357 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5358 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005359 clang_disposeString(SearchFileName);
5360 clang_disposeString(ResultFileName);
5361 clang_disposeString(KindSpelling);
5362 clang_disposeString(USR);
5363
5364 CXCursor Definition = clang_getCursorDefinition(Result);
5365 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5366 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5367 CXString DefinitionKindSpelling
5368 = clang_getCursorKindSpelling(Definition.kind);
5369 CXFile DefinitionFile;
5370 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005371 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005372 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005374 *Log << llvm::format(" -> %s(%s:%d:%d)",
5375 clang_getCString(DefinitionKindSpelling),
5376 clang_getCString(DefinitionFileName),
5377 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005378 clang_disposeString(DefinitionFileName);
5379 clang_disposeString(DefinitionKindSpelling);
5380 }
5381 }
5382
5383 return Result;
5384}
5385
5386CXCursor clang_getNullCursor(void) {
5387 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5388}
5389
5390unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005391 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5392 // can't set consistently. For example, when visiting a DeclStmt we will set
5393 // it but we don't set it on the result of clang_getCursorDefinition for
5394 // a reference of the same declaration.
5395 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5396 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5397 // to provide that kind of info.
5398 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005399 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005400 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005401 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005402
Guy Benyei11169dd2012-12-18 14:30:41 +00005403 return X == Y;
5404}
5405
5406unsigned clang_hashCursor(CXCursor C) {
5407 unsigned Index = 0;
5408 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5409 Index = 1;
5410
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005411 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005412 std::make_pair(C.kind, C.data[Index]));
5413}
5414
5415unsigned clang_isInvalid(enum CXCursorKind K) {
5416 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5417}
5418
5419unsigned clang_isDeclaration(enum CXCursorKind K) {
5420 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5421 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5422}
5423
5424unsigned clang_isReference(enum CXCursorKind K) {
5425 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5426}
5427
5428unsigned clang_isExpression(enum CXCursorKind K) {
5429 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5430}
5431
5432unsigned clang_isStatement(enum CXCursorKind K) {
5433 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5434}
5435
5436unsigned clang_isAttribute(enum CXCursorKind K) {
5437 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5438}
5439
5440unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5441 return K == CXCursor_TranslationUnit;
5442}
5443
5444unsigned clang_isPreprocessing(enum CXCursorKind K) {
5445 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5446}
5447
5448unsigned clang_isUnexposed(enum CXCursorKind K) {
5449 switch (K) {
5450 case CXCursor_UnexposedDecl:
5451 case CXCursor_UnexposedExpr:
5452 case CXCursor_UnexposedStmt:
5453 case CXCursor_UnexposedAttr:
5454 return true;
5455 default:
5456 return false;
5457 }
5458}
5459
5460CXCursorKind clang_getCursorKind(CXCursor C) {
5461 return C.kind;
5462}
5463
5464CXSourceLocation clang_getCursorLocation(CXCursor C) {
5465 if (clang_isReference(C.kind)) {
5466 switch (C.kind) {
5467 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005468 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005469 = getCursorObjCSuperClassRef(C);
5470 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5471 }
5472
5473 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005474 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005475 = getCursorObjCProtocolRef(C);
5476 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5477 }
5478
5479 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005480 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005481 = getCursorObjCClassRef(C);
5482 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5483 }
5484
5485 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005486 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005487 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5488 }
5489
5490 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005491 std::pair<const TemplateDecl *, SourceLocation> P =
5492 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005493 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5494 }
5495
5496 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005497 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005498 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5499 }
5500
5501 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005502 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005503 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5504 }
5505
5506 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005507 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005508 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5509 }
5510
5511 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005512 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 if (!BaseSpec)
5514 return clang_getNullLocation();
5515
5516 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5517 return cxloc::translateSourceLocation(getCursorContext(C),
5518 TSInfo->getTypeLoc().getBeginLoc());
5519
5520 return cxloc::translateSourceLocation(getCursorContext(C),
5521 BaseSpec->getLocStart());
5522 }
5523
5524 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005525 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005526 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5527 }
5528
5529 case CXCursor_OverloadedDeclRef:
5530 return cxloc::translateSourceLocation(getCursorContext(C),
5531 getCursorOverloadedDeclRef(C).second);
5532
5533 default:
5534 // FIXME: Need a way to enumerate all non-reference cases.
5535 llvm_unreachable("Missed a reference kind");
5536 }
5537 }
5538
5539 if (clang_isExpression(C.kind))
5540 return cxloc::translateSourceLocation(getCursorContext(C),
5541 getLocationFromExpr(getCursorExpr(C)));
5542
5543 if (clang_isStatement(C.kind))
5544 return cxloc::translateSourceLocation(getCursorContext(C),
5545 getCursorStmt(C)->getLocStart());
5546
5547 if (C.kind == CXCursor_PreprocessingDirective) {
5548 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5549 return cxloc::translateSourceLocation(getCursorContext(C), L);
5550 }
5551
5552 if (C.kind == CXCursor_MacroExpansion) {
5553 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005554 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005555 return cxloc::translateSourceLocation(getCursorContext(C), L);
5556 }
5557
5558 if (C.kind == CXCursor_MacroDefinition) {
5559 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5560 return cxloc::translateSourceLocation(getCursorContext(C), L);
5561 }
5562
5563 if (C.kind == CXCursor_InclusionDirective) {
5564 SourceLocation L
5565 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5566 return cxloc::translateSourceLocation(getCursorContext(C), L);
5567 }
5568
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005569 if (clang_isAttribute(C.kind)) {
5570 SourceLocation L
5571 = cxcursor::getCursorAttr(C)->getLocation();
5572 return cxloc::translateSourceLocation(getCursorContext(C), L);
5573 }
5574
Guy Benyei11169dd2012-12-18 14:30:41 +00005575 if (!clang_isDeclaration(C.kind))
5576 return clang_getNullLocation();
5577
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005578 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005579 if (!D)
5580 return clang_getNullLocation();
5581
5582 SourceLocation Loc = D->getLocation();
5583 // FIXME: Multiple variables declared in a single declaration
5584 // currently lack the information needed to correctly determine their
5585 // ranges when accounting for the type-specifier. We use context
5586 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5587 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005588 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005589 if (!cxcursor::isFirstInDeclGroup(C))
5590 Loc = VD->getLocation();
5591 }
5592
5593 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005594 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005595 Loc = MD->getSelectorStartLoc();
5596
5597 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5598}
5599
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005600} // end extern "C"
5601
Guy Benyei11169dd2012-12-18 14:30:41 +00005602CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5603 assert(TU);
5604
5605 // Guard against an invalid SourceLocation, or we may assert in one
5606 // of the following calls.
5607 if (SLoc.isInvalid())
5608 return clang_getNullCursor();
5609
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005610 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005611
5612 // Translate the given source location to make it point at the beginning of
5613 // the token under the cursor.
5614 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5615 CXXUnit->getASTContext().getLangOpts());
5616
5617 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5618 if (SLoc.isValid()) {
5619 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5620 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5621 /*VisitPreprocessorLast=*/true,
5622 /*VisitIncludedEntities=*/false,
5623 SourceLocation(SLoc));
5624 CursorVis.visitFileRegion();
5625 }
5626
5627 return Result;
5628}
5629
5630static SourceRange getRawCursorExtent(CXCursor C) {
5631 if (clang_isReference(C.kind)) {
5632 switch (C.kind) {
5633 case CXCursor_ObjCSuperClassRef:
5634 return getCursorObjCSuperClassRef(C).second;
5635
5636 case CXCursor_ObjCProtocolRef:
5637 return getCursorObjCProtocolRef(C).second;
5638
5639 case CXCursor_ObjCClassRef:
5640 return getCursorObjCClassRef(C).second;
5641
5642 case CXCursor_TypeRef:
5643 return getCursorTypeRef(C).second;
5644
5645 case CXCursor_TemplateRef:
5646 return getCursorTemplateRef(C).second;
5647
5648 case CXCursor_NamespaceRef:
5649 return getCursorNamespaceRef(C).second;
5650
5651 case CXCursor_MemberRef:
5652 return getCursorMemberRef(C).second;
5653
5654 case CXCursor_CXXBaseSpecifier:
5655 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5656
5657 case CXCursor_LabelRef:
5658 return getCursorLabelRef(C).second;
5659
5660 case CXCursor_OverloadedDeclRef:
5661 return getCursorOverloadedDeclRef(C).second;
5662
5663 case CXCursor_VariableRef:
5664 return getCursorVariableRef(C).second;
5665
5666 default:
5667 // FIXME: Need a way to enumerate all non-reference cases.
5668 llvm_unreachable("Missed a reference kind");
5669 }
5670 }
5671
5672 if (clang_isExpression(C.kind))
5673 return getCursorExpr(C)->getSourceRange();
5674
5675 if (clang_isStatement(C.kind))
5676 return getCursorStmt(C)->getSourceRange();
5677
5678 if (clang_isAttribute(C.kind))
5679 return getCursorAttr(C)->getRange();
5680
5681 if (C.kind == CXCursor_PreprocessingDirective)
5682 return cxcursor::getCursorPreprocessingDirective(C);
5683
5684 if (C.kind == CXCursor_MacroExpansion) {
5685 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005686 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005687 return TU->mapRangeFromPreamble(Range);
5688 }
5689
5690 if (C.kind == CXCursor_MacroDefinition) {
5691 ASTUnit *TU = getCursorASTUnit(C);
5692 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5693 return TU->mapRangeFromPreamble(Range);
5694 }
5695
5696 if (C.kind == CXCursor_InclusionDirective) {
5697 ASTUnit *TU = getCursorASTUnit(C);
5698 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5699 return TU->mapRangeFromPreamble(Range);
5700 }
5701
5702 if (C.kind == CXCursor_TranslationUnit) {
5703 ASTUnit *TU = getCursorASTUnit(C);
5704 FileID MainID = TU->getSourceManager().getMainFileID();
5705 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5706 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5707 return SourceRange(Start, End);
5708 }
5709
5710 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005711 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005712 if (!D)
5713 return SourceRange();
5714
5715 SourceRange R = D->getSourceRange();
5716 // FIXME: Multiple variables declared in a single declaration
5717 // currently lack the information needed to correctly determine their
5718 // ranges when accounting for the type-specifier. We use context
5719 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5720 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005721 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005722 if (!cxcursor::isFirstInDeclGroup(C))
5723 R.setBegin(VD->getLocation());
5724 }
5725 return R;
5726 }
5727 return SourceRange();
5728}
5729
5730/// \brief Retrieves the "raw" cursor extent, which is then extended to include
5731/// the decl-specifier-seq for declarations.
5732static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
5733 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005734 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005735 if (!D)
5736 return SourceRange();
5737
5738 SourceRange R = D->getSourceRange();
5739
5740 // Adjust the start of the location for declarations preceded by
5741 // declaration specifiers.
5742 SourceLocation StartLoc;
5743 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5744 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5745 StartLoc = TI->getTypeLoc().getLocStart();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005746 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005747 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5748 StartLoc = TI->getTypeLoc().getLocStart();
5749 }
5750
5751 if (StartLoc.isValid() && R.getBegin().isValid() &&
5752 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
5753 R.setBegin(StartLoc);
5754
5755 // FIXME: Multiple variables declared in a single declaration
5756 // currently lack the information needed to correctly determine their
5757 // ranges when accounting for the type-specifier. We use context
5758 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5759 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005760 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005761 if (!cxcursor::isFirstInDeclGroup(C))
5762 R.setBegin(VD->getLocation());
5763 }
5764
5765 return R;
5766 }
5767
5768 return getRawCursorExtent(C);
5769}
5770
Guy Benyei11169dd2012-12-18 14:30:41 +00005771CXSourceRange clang_getCursorExtent(CXCursor C) {
5772 SourceRange R = getRawCursorExtent(C);
5773 if (R.isInvalid())
5774 return clang_getNullRange();
5775
5776 return cxloc::translateSourceRange(getCursorContext(C), R);
5777}
5778
5779CXCursor clang_getCursorReferenced(CXCursor C) {
5780 if (clang_isInvalid(C.kind))
5781 return clang_getNullCursor();
5782
5783 CXTranslationUnit tu = getCursorTU(C);
5784 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005785 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005786 if (!D)
5787 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005788 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005789 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005790 if (const ObjCPropertyImplDecl *PropImpl =
5791 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005792 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5793 return MakeCXCursor(Property, tu);
5794
5795 return C;
5796 }
5797
5798 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005799 const Expr *E = getCursorExpr(C);
5800 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00005801 if (D) {
5802 CXCursor declCursor = MakeCXCursor(D, tu);
5803 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
5804 declCursor);
5805 return declCursor;
5806 }
5807
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005808 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00005809 return MakeCursorOverloadedDeclRef(Ovl, tu);
5810
5811 return clang_getNullCursor();
5812 }
5813
5814 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00005815 const Stmt *S = getCursorStmt(C);
5816 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00005817 if (LabelDecl *label = Goto->getLabel())
5818 if (LabelStmt *labelS = label->getStmt())
5819 return MakeCXCursor(labelS, getCursorDecl(C), tu);
5820
5821 return clang_getNullCursor();
5822 }
Richard Smith66a81862015-05-04 02:25:31 +00005823
Guy Benyei11169dd2012-12-18 14:30:41 +00005824 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00005825 if (const MacroDefinitionRecord *Def =
5826 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005827 return MakeMacroDefinitionCursor(Def, tu);
5828 }
5829
5830 if (!clang_isReference(C.kind))
5831 return clang_getNullCursor();
5832
5833 switch (C.kind) {
5834 case CXCursor_ObjCSuperClassRef:
5835 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
5836
5837 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005838 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5839 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005840 return MakeCXCursor(Def, tu);
5841
5842 return MakeCXCursor(Prot, tu);
5843 }
5844
5845 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005846 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5847 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00005848 return MakeCXCursor(Def, tu);
5849
5850 return MakeCXCursor(Class, tu);
5851 }
5852
5853 case CXCursor_TypeRef:
5854 return MakeCXCursor(getCursorTypeRef(C).first, tu );
5855
5856 case CXCursor_TemplateRef:
5857 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5858
5859 case CXCursor_NamespaceRef:
5860 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5861
5862 case CXCursor_MemberRef:
5863 return MakeCXCursor(getCursorMemberRef(C).first, tu );
5864
5865 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005866 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005867 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5868 tu ));
5869 }
5870
5871 case CXCursor_LabelRef:
5872 // FIXME: We end up faking the "parent" declaration here because we
5873 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005874 return MakeCXCursor(getCursorLabelRef(C).first,
5875 cxtu::getASTUnit(tu)->getASTContext()
5876 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005877 tu);
5878
5879 case CXCursor_OverloadedDeclRef:
5880 return C;
5881
5882 case CXCursor_VariableRef:
5883 return MakeCXCursor(getCursorVariableRef(C).first, tu);
5884
5885 default:
5886 // We would prefer to enumerate all non-reference cursor kinds here.
5887 llvm_unreachable("Unhandled reference cursor kind");
5888 }
5889}
5890
5891CXCursor clang_getCursorDefinition(CXCursor C) {
5892 if (clang_isInvalid(C.kind))
5893 return clang_getNullCursor();
5894
5895 CXTranslationUnit TU = getCursorTU(C);
5896
5897 bool WasReference = false;
5898 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5899 C = clang_getCursorReferenced(C);
5900 WasReference = true;
5901 }
5902
5903 if (C.kind == CXCursor_MacroExpansion)
5904 return clang_getCursorReferenced(C);
5905
5906 if (!clang_isDeclaration(C.kind))
5907 return clang_getNullCursor();
5908
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005909 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005910 if (!D)
5911 return clang_getNullCursor();
5912
5913 switch (D->getKind()) {
5914 // Declaration kinds that don't really separate the notions of
5915 // declaration and definition.
5916 case Decl::Namespace:
5917 case Decl::Typedef:
5918 case Decl::TypeAlias:
5919 case Decl::TypeAliasTemplate:
5920 case Decl::TemplateTypeParm:
5921 case Decl::EnumConstant:
5922 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00005923 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00005924 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005925 case Decl::IndirectField:
5926 case Decl::ObjCIvar:
5927 case Decl::ObjCAtDefsField:
5928 case Decl::ImplicitParam:
5929 case Decl::ParmVar:
5930 case Decl::NonTypeTemplateParm:
5931 case Decl::TemplateTemplateParm:
5932 case Decl::ObjCCategoryImpl:
5933 case Decl::ObjCImplementation:
5934 case Decl::AccessSpec:
5935 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00005936 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00005937 case Decl::ObjCPropertyImpl:
5938 case Decl::FileScopeAsm:
5939 case Decl::StaticAssert:
5940 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00005941 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00005942 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00005943 case Decl::Label: // FIXME: Is this right??
5944 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00005945 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00005946 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00005947 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005948 case Decl::OMPDeclareReduction:
Douglas Gregor85f3f952015-07-07 03:57:15 +00005949 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00005950 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00005951 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00005952 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00005953 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00005954 return C;
5955
5956 // Declaration kinds that don't make any sense here, but are
5957 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00005958 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00005959 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00005960 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00005961 break;
5962
5963 // Declaration kinds for which the definition is not resolvable.
5964 case Decl::UnresolvedUsingTypename:
5965 case Decl::UnresolvedUsingValue:
5966 break;
5967
5968 case Decl::UsingDirective:
5969 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5970 TU);
5971
5972 case Decl::NamespaceAlias:
5973 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5974
5975 case Decl::Enum:
5976 case Decl::Record:
5977 case Decl::CXXRecord:
5978 case Decl::ClassTemplateSpecialization:
5979 case Decl::ClassTemplatePartialSpecialization:
5980 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5981 return MakeCXCursor(Def, TU);
5982 return clang_getNullCursor();
5983
5984 case Decl::Function:
5985 case Decl::CXXMethod:
5986 case Decl::CXXConstructor:
5987 case Decl::CXXDestructor:
5988 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00005989 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005990 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00005991 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005992 return clang_getNullCursor();
5993 }
5994
Larisse Voufo39a1e502013-08-06 01:03:05 +00005995 case Decl::Var:
5996 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00005997 case Decl::VarTemplatePartialSpecialization:
5998 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005999 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006000 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006001 return MakeCXCursor(Def, TU);
6002 return clang_getNullCursor();
6003 }
6004
6005 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006006 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006007 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6008 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6009 return clang_getNullCursor();
6010 }
6011
6012 case Decl::ClassTemplate: {
6013 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6014 ->getDefinition())
6015 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6016 TU);
6017 return clang_getNullCursor();
6018 }
6019
Larisse Voufo39a1e502013-08-06 01:03:05 +00006020 case Decl::VarTemplate: {
6021 if (VarDecl *Def =
6022 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6023 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6024 return clang_getNullCursor();
6025 }
6026
Guy Benyei11169dd2012-12-18 14:30:41 +00006027 case Decl::Using:
6028 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6029 D->getLocation(), TU);
6030
6031 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006032 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006033 return clang_getCursorDefinition(
6034 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6035 TU));
6036
6037 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006038 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006039 if (Method->isThisDeclarationADefinition())
6040 return C;
6041
6042 // Dig out the method definition in the associated
6043 // @implementation, if we have it.
6044 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006045 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006046 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6047 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6048 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6049 Method->isInstanceMethod()))
6050 if (Def->isThisDeclarationADefinition())
6051 return MakeCXCursor(Def, TU);
6052
6053 return clang_getNullCursor();
6054 }
6055
6056 case Decl::ObjCCategory:
6057 if (ObjCCategoryImplDecl *Impl
6058 = cast<ObjCCategoryDecl>(D)->getImplementation())
6059 return MakeCXCursor(Impl, TU);
6060 return clang_getNullCursor();
6061
6062 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006063 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006064 return MakeCXCursor(Def, TU);
6065 return clang_getNullCursor();
6066
6067 case Decl::ObjCInterface: {
6068 // There are two notions of a "definition" for an Objective-C
6069 // class: the interface and its implementation. When we resolved a
6070 // reference to an Objective-C class, produce the @interface as
6071 // the definition; when we were provided with the interface,
6072 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006073 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006075 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006076 return MakeCXCursor(Def, TU);
6077 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6078 return MakeCXCursor(Impl, TU);
6079 return clang_getNullCursor();
6080 }
6081
6082 case Decl::ObjCProperty:
6083 // FIXME: We don't really know where to find the
6084 // ObjCPropertyImplDecls that implement this property.
6085 return clang_getNullCursor();
6086
6087 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006088 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006089 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006090 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 return MakeCXCursor(Def, TU);
6092
6093 return clang_getNullCursor();
6094
6095 case Decl::Friend:
6096 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6097 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6098 return clang_getNullCursor();
6099
6100 case Decl::FriendTemplate:
6101 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6102 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6103 return clang_getNullCursor();
6104 }
6105
6106 return clang_getNullCursor();
6107}
6108
6109unsigned clang_isCursorDefinition(CXCursor C) {
6110 if (!clang_isDeclaration(C.kind))
6111 return 0;
6112
6113 return clang_getCursorDefinition(C) == C;
6114}
6115
6116CXCursor clang_getCanonicalCursor(CXCursor C) {
6117 if (!clang_isDeclaration(C.kind))
6118 return C;
6119
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006120 if (const Decl *D = getCursorDecl(C)) {
6121 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6123 return MakeCXCursor(CatD, getCursorTU(C));
6124
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006125 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6126 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006127 return MakeCXCursor(IFD, getCursorTU(C));
6128
6129 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6130 }
6131
6132 return C;
6133}
6134
6135int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6136 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6137}
6138
6139unsigned clang_getNumOverloadedDecls(CXCursor C) {
6140 if (C.kind != CXCursor_OverloadedDeclRef)
6141 return 0;
6142
6143 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006144 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 return E->getNumDecls();
6146
6147 if (OverloadedTemplateStorage *S
6148 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6149 return S->size();
6150
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006151 const Decl *D = Storage.get<const Decl *>();
6152 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006153 return Using->shadow_size();
6154
6155 return 0;
6156}
6157
6158CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6159 if (cursor.kind != CXCursor_OverloadedDeclRef)
6160 return clang_getNullCursor();
6161
6162 if (index >= clang_getNumOverloadedDecls(cursor))
6163 return clang_getNullCursor();
6164
6165 CXTranslationUnit TU = getCursorTU(cursor);
6166 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006167 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006168 return MakeCXCursor(E->decls_begin()[index], TU);
6169
6170 if (OverloadedTemplateStorage *S
6171 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6172 return MakeCXCursor(S->begin()[index], TU);
6173
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006174 const Decl *D = Storage.get<const Decl *>();
6175 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006176 // FIXME: This is, unfortunately, linear time.
6177 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6178 std::advance(Pos, index);
6179 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6180 }
6181
6182 return clang_getNullCursor();
6183}
6184
6185void clang_getDefinitionSpellingAndExtent(CXCursor C,
6186 const char **startBuf,
6187 const char **endBuf,
6188 unsigned *startLine,
6189 unsigned *startColumn,
6190 unsigned *endLine,
6191 unsigned *endColumn) {
6192 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006193 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006194 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6195
6196 SourceManager &SM = FD->getASTContext().getSourceManager();
6197 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6198 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6199 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6200 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6201 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6202 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6203}
6204
6205
6206CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6207 unsigned PieceIndex) {
6208 RefNamePieces Pieces;
6209
6210 switch (C.kind) {
6211 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006212 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006213 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6214 E->getQualifierLoc().getSourceRange());
6215 break;
6216
6217 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006218 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6219 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6220 Pieces =
6221 buildPieces(NameFlags, false, E->getNameInfo(),
6222 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6223 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 break;
6225
6226 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006227 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006228 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006229 const Expr *Callee = OCE->getCallee();
6230 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006231 Callee = ICE->getSubExpr();
6232
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006233 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006234 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6235 DRE->getQualifierLoc().getSourceRange());
6236 }
6237 break;
6238
6239 default:
6240 break;
6241 }
6242
6243 if (Pieces.empty()) {
6244 if (PieceIndex == 0)
6245 return clang_getCursorExtent(C);
6246 } else if (PieceIndex < Pieces.size()) {
6247 SourceRange R = Pieces[PieceIndex];
6248 if (R.isValid())
6249 return cxloc::translateSourceRange(getCursorContext(C), R);
6250 }
6251
6252 return clang_getNullRange();
6253}
6254
6255void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006256 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6257 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006258}
6259
6260void clang_executeOnThread(void (*fn)(void*), void *user_data,
6261 unsigned stack_size) {
6262 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6263}
6264
Guy Benyei11169dd2012-12-18 14:30:41 +00006265//===----------------------------------------------------------------------===//
6266// Token-based Operations.
6267//===----------------------------------------------------------------------===//
6268
6269/* CXToken layout:
6270 * int_data[0]: a CXTokenKind
6271 * int_data[1]: starting token location
6272 * int_data[2]: token length
6273 * int_data[3]: reserved
6274 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6275 * otherwise unused.
6276 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006277CXTokenKind clang_getTokenKind(CXToken CXTok) {
6278 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6279}
6280
6281CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6282 switch (clang_getTokenKind(CXTok)) {
6283 case CXToken_Identifier:
6284 case CXToken_Keyword:
6285 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006286 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006287 ->getNameStart());
6288
6289 case CXToken_Literal: {
6290 // We have stashed the starting pointer in the ptr_data field. Use it.
6291 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006292 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006293 }
6294
6295 case CXToken_Punctuation:
6296 case CXToken_Comment:
6297 break;
6298 }
6299
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006300 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006301 LOG_BAD_TU(TU);
6302 return cxstring::createEmpty();
6303 }
6304
Guy Benyei11169dd2012-12-18 14:30:41 +00006305 // We have to find the starting buffer pointer the hard way, by
6306 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006307 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006308 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006309 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006310
6311 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6312 std::pair<FileID, unsigned> LocInfo
6313 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6314 bool Invalid = false;
6315 StringRef Buffer
6316 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6317 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006318 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006319
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006320 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006321}
6322
6323CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006324 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006325 LOG_BAD_TU(TU);
6326 return clang_getNullLocation();
6327 }
6328
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006329 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 if (!CXXUnit)
6331 return clang_getNullLocation();
6332
6333 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6334 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6335}
6336
6337CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006338 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006339 LOG_BAD_TU(TU);
6340 return clang_getNullRange();
6341 }
6342
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006343 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006344 if (!CXXUnit)
6345 return clang_getNullRange();
6346
6347 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6348 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6349}
6350
6351static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6352 SmallVectorImpl<CXToken> &CXTokens) {
6353 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6354 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006355 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006356 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006357 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006358
6359 // Cannot tokenize across files.
6360 if (BeginLocInfo.first != EndLocInfo.first)
6361 return;
6362
6363 // Create a lexer
6364 bool Invalid = false;
6365 StringRef Buffer
6366 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6367 if (Invalid)
6368 return;
6369
6370 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6371 CXXUnit->getASTContext().getLangOpts(),
6372 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6373 Lex.SetCommentRetentionState(true);
6374
6375 // Lex tokens until we hit the end of the range.
6376 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6377 Token Tok;
6378 bool previousWasAt = false;
6379 do {
6380 // Lex the next token
6381 Lex.LexFromRawLexer(Tok);
6382 if (Tok.is(tok::eof))
6383 break;
6384
6385 // Initialize the CXToken.
6386 CXToken CXTok;
6387
6388 // - Common fields
6389 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6390 CXTok.int_data[2] = Tok.getLength();
6391 CXTok.int_data[3] = 0;
6392
6393 // - Kind-specific fields
6394 if (Tok.isLiteral()) {
6395 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006396 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006397 } else if (Tok.is(tok::raw_identifier)) {
6398 // Lookup the identifier to determine whether we have a keyword.
6399 IdentifierInfo *II
6400 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6401
6402 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6403 CXTok.int_data[0] = CXToken_Keyword;
6404 }
6405 else {
6406 CXTok.int_data[0] = Tok.is(tok::identifier)
6407 ? CXToken_Identifier
6408 : CXToken_Keyword;
6409 }
6410 CXTok.ptr_data = II;
6411 } else if (Tok.is(tok::comment)) {
6412 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006413 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006414 } else {
6415 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006416 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006417 }
6418 CXTokens.push_back(CXTok);
6419 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006420 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006421}
6422
6423void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6424 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006425 LOG_FUNC_SECTION {
6426 *Log << TU << ' ' << Range;
6427 }
6428
Guy Benyei11169dd2012-12-18 14:30:41 +00006429 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006430 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006431 if (NumTokens)
6432 *NumTokens = 0;
6433
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006434 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006435 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006436 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006437 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006438
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006439 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006440 if (!CXXUnit || !Tokens || !NumTokens)
6441 return;
6442
6443 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6444
6445 SourceRange R = cxloc::translateCXSourceRange(Range);
6446 if (R.isInvalid())
6447 return;
6448
6449 SmallVector<CXToken, 32> CXTokens;
6450 getTokens(CXXUnit, R, CXTokens);
6451
6452 if (CXTokens.empty())
6453 return;
6454
6455 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
6456 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6457 *NumTokens = CXTokens.size();
6458}
6459
6460void clang_disposeTokens(CXTranslationUnit TU,
6461 CXToken *Tokens, unsigned NumTokens) {
6462 free(Tokens);
6463}
6464
Guy Benyei11169dd2012-12-18 14:30:41 +00006465//===----------------------------------------------------------------------===//
6466// Token annotation APIs.
6467//===----------------------------------------------------------------------===//
6468
Guy Benyei11169dd2012-12-18 14:30:41 +00006469static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6470 CXCursor parent,
6471 CXClientData client_data);
6472static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6473 CXClientData client_data);
6474
6475namespace {
6476class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006477 CXToken *Tokens;
6478 CXCursor *Cursors;
6479 unsigned NumTokens;
6480 unsigned TokIdx;
6481 unsigned PreprocessingTokIdx;
6482 CursorVisitor AnnotateVis;
6483 SourceManager &SrcMgr;
6484 bool HasContextSensitiveKeywords;
6485
6486 struct PostChildrenInfo {
6487 CXCursor Cursor;
6488 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006489 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006490 unsigned BeforeChildrenTokenIdx;
6491 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006492 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006493
6494 CXToken &getTok(unsigned Idx) {
6495 assert(Idx < NumTokens);
6496 return Tokens[Idx];
6497 }
6498 const CXToken &getTok(unsigned Idx) const {
6499 assert(Idx < NumTokens);
6500 return Tokens[Idx];
6501 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 bool MoreTokens() const { return TokIdx < NumTokens; }
6503 unsigned NextToken() const { return TokIdx; }
6504 void AdvanceToken() { ++TokIdx; }
6505 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006506 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006507 }
6508 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006509 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006510 }
6511 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006512 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006513 }
6514
6515 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006516 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006517 SourceRange);
6518
6519public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006520 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006521 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006522 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006523 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006524 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006525 AnnotateTokensVisitor, this,
6526 /*VisitPreprocessorLast=*/true,
6527 /*VisitIncludedEntities=*/false,
6528 RegionOfInterest,
6529 /*VisitDeclsOnly=*/false,
6530 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006531 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006532 HasContextSensitiveKeywords(false) { }
6533
6534 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6535 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6536 bool postVisitChildren(CXCursor cursor);
6537 void AnnotateTokens();
6538
6539 /// \brief Determine whether the annotator saw any cursors that have
6540 /// context-sensitive keywords.
6541 bool hasContextSensitiveKeywords() const {
6542 return HasContextSensitiveKeywords;
6543 }
6544
6545 ~AnnotateTokensWorker() {
6546 assert(PostChildrenInfos.empty());
6547 }
6548};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006549}
Guy Benyei11169dd2012-12-18 14:30:41 +00006550
6551void AnnotateTokensWorker::AnnotateTokens() {
6552 // Walk the AST within the region of interest, annotating tokens
6553 // along the way.
6554 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006555}
Guy Benyei11169dd2012-12-18 14:30:41 +00006556
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006557static inline void updateCursorAnnotation(CXCursor &Cursor,
6558 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006559 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006560 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006561 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006562}
6563
6564/// \brief It annotates and advances tokens with a cursor until the comparison
6565//// between the cursor location and the source range is the same as
6566/// \arg compResult.
6567///
6568/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6569/// Pass RangeOverlap to annotate tokens inside a range.
6570void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6571 RangeComparisonResult compResult,
6572 SourceRange range) {
6573 while (MoreTokens()) {
6574 const unsigned I = NextToken();
6575 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006576 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6577 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006578
6579 SourceLocation TokLoc = GetTokenLoc(I);
6580 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006581 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006582 AdvanceToken();
6583 continue;
6584 }
6585 break;
6586 }
6587}
6588
6589/// \brief Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006590/// \returns true if it advanced beyond all macro tokens, false otherwise.
6591bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 CXCursor updateC,
6593 RangeComparisonResult compResult,
6594 SourceRange range) {
6595 assert(MoreTokens());
6596 assert(isFunctionMacroToken(NextToken()) &&
6597 "Should be called only for macro arg tokens");
6598
6599 // This works differently than annotateAndAdvanceTokens; because expanded
6600 // macro arguments can have arbitrary translation-unit source order, we do not
6601 // advance the token index one by one until a token fails the range test.
6602 // We only advance once past all of the macro arg tokens if all of them
6603 // pass the range test. If one of them fails we keep the token index pointing
6604 // at the start of the macro arg tokens so that the failing token will be
6605 // annotated by a subsequent annotation try.
6606
6607 bool atLeastOneCompFail = false;
6608
6609 unsigned I = NextToken();
6610 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
6611 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
6612 if (TokLoc.isFileID())
6613 continue; // not macro arg token, it's parens or comma.
6614 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6615 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
6616 Cursors[I] = updateC;
6617 } else
6618 atLeastOneCompFail = true;
6619 }
6620
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006621 if (atLeastOneCompFail)
6622 return false;
6623
6624 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
6625 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006626}
6627
6628enum CXChildVisitResult
6629AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006630 SourceRange cursorRange = getRawCursorExtent(cursor);
6631 if (cursorRange.isInvalid())
6632 return CXChildVisit_Recurse;
6633
6634 if (!HasContextSensitiveKeywords) {
6635 // Objective-C properties can have context-sensitive keywords.
6636 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006637 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00006638 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
6639 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
6640 }
6641 // Objective-C methods can have context-sensitive keywords.
6642 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
6643 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006644 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006645 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6646 if (Method->getObjCDeclQualifier())
6647 HasContextSensitiveKeywords = true;
6648 else {
David Majnemer59f77922016-06-24 04:05:48 +00006649 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00006650 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006651 HasContextSensitiveKeywords = true;
6652 break;
6653 }
6654 }
6655 }
6656 }
6657 }
6658 // C++ methods can have context-sensitive keywords.
6659 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006660 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00006661 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
6662 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
6663 HasContextSensitiveKeywords = true;
6664 }
6665 }
6666 // C++ classes can have context-sensitive keywords.
6667 else if (cursor.kind == CXCursor_StructDecl ||
6668 cursor.kind == CXCursor_ClassDecl ||
6669 cursor.kind == CXCursor_ClassTemplate ||
6670 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006671 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00006672 if (D->hasAttr<FinalAttr>())
6673 HasContextSensitiveKeywords = true;
6674 }
6675 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00006676
6677 // Don't override a property annotation with its getter/setter method.
6678 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
6679 parent.kind == CXCursor_ObjCPropertyDecl)
6680 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00006681
6682 if (clang_isPreprocessing(cursor.kind)) {
6683 // Items in the preprocessing record are kept separate from items in
6684 // declarations, so we keep a separate token index.
6685 unsigned SavedTokIdx = TokIdx;
6686 TokIdx = PreprocessingTokIdx;
6687
6688 // Skip tokens up until we catch up to the beginning of the preprocessing
6689 // entry.
6690 while (MoreTokens()) {
6691 const unsigned I = NextToken();
6692 SourceLocation TokLoc = GetTokenLoc(I);
6693 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6694 case RangeBefore:
6695 AdvanceToken();
6696 continue;
6697 case RangeAfter:
6698 case RangeOverlap:
6699 break;
6700 }
6701 break;
6702 }
6703
6704 // Look at all of the tokens within this range.
6705 while (MoreTokens()) {
6706 const unsigned I = NextToken();
6707 SourceLocation TokLoc = GetTokenLoc(I);
6708 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
6709 case RangeBefore:
6710 llvm_unreachable("Infeasible");
6711 case RangeAfter:
6712 break;
6713 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006714 // For macro expansions, just note where the beginning of the macro
6715 // expansion occurs.
6716 if (cursor.kind == CXCursor_MacroExpansion) {
6717 if (TokLoc == cursorRange.getBegin())
6718 Cursors[I] = cursor;
6719 AdvanceToken();
6720 break;
6721 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006722 // We may have already annotated macro names inside macro definitions.
6723 if (Cursors[I].kind != CXCursor_MacroExpansion)
6724 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006726 continue;
6727 }
6728 break;
6729 }
6730
6731 // Save the preprocessing token index; restore the non-preprocessing
6732 // token index.
6733 PreprocessingTokIdx = TokIdx;
6734 TokIdx = SavedTokIdx;
6735 return CXChildVisit_Recurse;
6736 }
6737
6738 if (cursorRange.isInvalid())
6739 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006740
6741 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00006742 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006743 const enum CXCursorKind K = clang_getCursorKind(parent);
6744 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006745 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
6746 // Attributes are annotated out-of-order, skip tokens until we reach it.
6747 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006748 ? clang_getNullCursor() : parent;
6749
6750 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
6751
6752 // Avoid having the cursor of an expression "overwrite" the annotation of the
6753 // variable declaration that it belongs to.
6754 // This can happen for C++ constructor expressions whose range generally
6755 // include the variable declaration, e.g.:
6756 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006757 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006758 const Expr *E = getCursorExpr(cursor);
Dmitri Gribenkoa1691182013-01-26 18:12:08 +00006759 if (const Decl *D = getCursorParentDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006760 const unsigned I = NextToken();
6761 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
6762 E->getLocStart() == D->getLocation() &&
6763 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006764 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006765 AdvanceToken();
6766 }
6767 }
6768 }
6769
6770 // Before recursing into the children keep some state that we are going
6771 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
6772 // extra work after the child nodes are visited.
6773 // Note that we don't call VisitChildren here to avoid traversing statements
6774 // code-recursively which can blow the stack.
6775
6776 PostChildrenInfo Info;
6777 Info.Cursor = cursor;
6778 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006779 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 Info.BeforeChildrenTokenIdx = NextToken();
6781 PostChildrenInfos.push_back(Info);
6782
6783 return CXChildVisit_Recurse;
6784}
6785
6786bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
6787 if (PostChildrenInfos.empty())
6788 return false;
6789 const PostChildrenInfo &Info = PostChildrenInfos.back();
6790 if (!clang_equalCursors(Info.Cursor, cursor))
6791 return false;
6792
6793 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
6794 const unsigned AfterChildren = NextToken();
6795 SourceRange cursorRange = Info.CursorRange;
6796
6797 // Scan the tokens that are at the end of the cursor, but are not captured
6798 // but the child cursors.
6799 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
6800
6801 // Scan the tokens that are at the beginning of the cursor, but are not
6802 // capture by the child cursors.
6803 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
6804 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
6805 break;
6806
6807 Cursors[I] = cursor;
6808 }
6809
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006810 // Attributes are annotated out-of-order, rewind TokIdx to when we first
6811 // encountered the attribute cursor.
6812 if (clang_isAttribute(cursor.kind))
6813 TokIdx = Info.BeforeReachingCursorIdx;
6814
Guy Benyei11169dd2012-12-18 14:30:41 +00006815 PostChildrenInfos.pop_back();
6816 return false;
6817}
6818
6819static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6820 CXCursor parent,
6821 CXClientData client_data) {
6822 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
6823}
6824
6825static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6826 CXClientData client_data) {
6827 return static_cast<AnnotateTokensWorker*>(client_data)->
6828 postVisitChildren(cursor);
6829}
6830
6831namespace {
6832
6833/// \brief Uses the macro expansions in the preprocessing record to find
6834/// and mark tokens that are macro arguments. This info is used by the
6835/// AnnotateTokensWorker.
6836class MarkMacroArgTokensVisitor {
6837 SourceManager &SM;
6838 CXToken *Tokens;
6839 unsigned NumTokens;
6840 unsigned CurIdx;
6841
6842public:
6843 MarkMacroArgTokensVisitor(SourceManager &SM,
6844 CXToken *tokens, unsigned numTokens)
6845 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6846
6847 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6848 if (cursor.kind != CXCursor_MacroExpansion)
6849 return CXChildVisit_Continue;
6850
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006851 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006852 if (macroRange.getBegin() == macroRange.getEnd())
6853 return CXChildVisit_Continue; // it's not a function macro.
6854
6855 for (; CurIdx < NumTokens; ++CurIdx) {
6856 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6857 macroRange.getBegin()))
6858 break;
6859 }
6860
6861 if (CurIdx == NumTokens)
6862 return CXChildVisit_Break;
6863
6864 for (; CurIdx < NumTokens; ++CurIdx) {
6865 SourceLocation tokLoc = getTokenLoc(CurIdx);
6866 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6867 break;
6868
6869 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6870 }
6871
6872 if (CurIdx == NumTokens)
6873 return CXChildVisit_Break;
6874
6875 return CXChildVisit_Continue;
6876 }
6877
6878private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006879 CXToken &getTok(unsigned Idx) {
6880 assert(Idx < NumTokens);
6881 return Tokens[Idx];
6882 }
6883 const CXToken &getTok(unsigned Idx) const {
6884 assert(Idx < NumTokens);
6885 return Tokens[Idx];
6886 }
6887
Guy Benyei11169dd2012-12-18 14:30:41 +00006888 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006889 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006890 }
6891
6892 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6893 // The third field is reserved and currently not used. Use it here
6894 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006895 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00006896 }
6897};
6898
6899} // end anonymous namespace
6900
6901static CXChildVisitResult
6902MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6903 CXClientData client_data) {
6904 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6905 parent);
6906}
6907
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006908/// \brief Used by \c annotatePreprocessorTokens.
6909/// \returns true if lexing was finished, false otherwise.
6910static bool lexNext(Lexer &Lex, Token &Tok,
6911 unsigned &NextIdx, unsigned NumTokens) {
6912 if (NextIdx >= NumTokens)
6913 return true;
6914
6915 ++NextIdx;
6916 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00006917 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006918}
6919
Guy Benyei11169dd2012-12-18 14:30:41 +00006920static void annotatePreprocessorTokens(CXTranslationUnit TU,
6921 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006922 CXCursor *Cursors,
6923 CXToken *Tokens,
6924 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006925 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006926
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006927 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00006928 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6929 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006930 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006931 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006932 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006933
6934 if (BeginLocInfo.first != EndLocInfo.first)
6935 return;
6936
6937 StringRef Buffer;
6938 bool Invalid = false;
6939 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6940 if (Buffer.empty() || Invalid)
6941 return;
6942
6943 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6944 CXXUnit->getASTContext().getLangOpts(),
6945 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6946 Buffer.end());
6947 Lex.SetCommentRetentionState(true);
6948
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006949 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006950 // Lex tokens in raw mode until we hit the end of the range, to avoid
6951 // entering #includes or expanding macros.
6952 while (true) {
6953 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006954 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6955 break;
6956 unsigned TokIdx = NextIdx-1;
6957 assert(Tok.getLocation() ==
6958 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006959
6960 reprocess:
6961 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006962 // We have found a preprocessing directive. Annotate the tokens
6963 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00006964 //
6965 // FIXME: Some simple tests here could identify macro definitions and
6966 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006967
6968 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006969 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6970 break;
6971
Craig Topper69186e72014-06-08 08:38:04 +00006972 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00006973 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006974 if (lexNext(Lex, Tok, NextIdx, NumTokens))
6975 break;
6976
6977 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00006978 IdentifierInfo &II =
6979 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006980 SourceLocation MappedTokLoc =
6981 CXXUnit->mapLocationToPreamble(Tok.getLocation());
6982 MI = getMacroInfo(II, MappedTokLoc, TU);
6983 }
6984 }
6985
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006986 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006987 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006988 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6989 finished = true;
6990 break;
6991 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006992 // If we are in a macro definition, check if the token was ever a
6993 // macro name and annotate it if that's the case.
6994 if (MI) {
6995 SourceLocation SaveLoc = Tok.getLocation();
6996 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00006997 MacroDefinitionRecord *MacroDef =
6998 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00006999 Tok.setLocation(SaveLoc);
7000 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007001 Cursors[NextIdx - 1] =
7002 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007003 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007004 } while (!Tok.isAtStartOfLine());
7005
7006 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7007 assert(TokIdx <= LastIdx);
7008 SourceLocation EndLoc =
7009 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7010 CXCursor Cursor =
7011 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7012
7013 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007014 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007015
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007016 if (finished)
7017 break;
7018 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007019 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007020 }
7021}
7022
7023// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007024static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7025 CXToken *Tokens, unsigned NumTokens,
7026 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007027 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007028 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7029 setThreadBackgroundPriority();
7030
7031 // Determine the region of interest, which contains all of the tokens.
7032 SourceRange RegionOfInterest;
7033 RegionOfInterest.setBegin(
7034 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7035 RegionOfInterest.setEnd(
7036 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7037 Tokens[NumTokens-1])));
7038
Guy Benyei11169dd2012-12-18 14:30:41 +00007039 // Relex the tokens within the source range to look for preprocessing
7040 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007041 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007042
7043 // If begin location points inside a macro argument, set it to the expansion
7044 // location so we can have the full context when annotating semantically.
7045 {
7046 SourceManager &SM = CXXUnit->getSourceManager();
7047 SourceLocation Loc =
7048 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7049 if (Loc.isMacroID())
7050 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7051 }
7052
Guy Benyei11169dd2012-12-18 14:30:41 +00007053 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7054 // Search and mark tokens that are macro argument expansions.
7055 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7056 Tokens, NumTokens);
7057 CursorVisitor MacroArgMarker(TU,
7058 MarkMacroArgTokensVisitorDelegate, &Visitor,
7059 /*VisitPreprocessorLast=*/true,
7060 /*VisitIncludedEntities=*/false,
7061 RegionOfInterest);
7062 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7063 }
7064
7065 // Annotate all of the source locations in the region of interest that map to
7066 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007067 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007068
7069 // FIXME: We use a ridiculous stack size here because the data-recursion
7070 // algorithm uses a large stack frame than the non-data recursive version,
7071 // and AnnotationTokensWorker currently transforms the data-recursion
7072 // algorithm back into a traditional recursion by explicitly calling
7073 // VisitChildren(). We will need to remove this explicit recursive call.
7074 W.AnnotateTokens();
7075
7076 // If we ran into any entities that involve context-sensitive keywords,
7077 // take another pass through the tokens to mark them as such.
7078 if (W.hasContextSensitiveKeywords()) {
7079 for (unsigned I = 0; I != NumTokens; ++I) {
7080 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7081 continue;
7082
7083 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7084 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007085 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007086 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7087 if (Property->getPropertyAttributesAsWritten() != 0 &&
7088 llvm::StringSwitch<bool>(II->getName())
7089 .Case("readonly", true)
7090 .Case("assign", true)
7091 .Case("unsafe_unretained", true)
7092 .Case("readwrite", true)
7093 .Case("retain", true)
7094 .Case("copy", true)
7095 .Case("nonatomic", true)
7096 .Case("atomic", true)
7097 .Case("getter", true)
7098 .Case("setter", true)
7099 .Case("strong", true)
7100 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007101 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007102 .Default(false))
7103 Tokens[I].int_data[0] = CXToken_Keyword;
7104 }
7105 continue;
7106 }
7107
7108 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7109 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7110 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7111 if (llvm::StringSwitch<bool>(II->getName())
7112 .Case("in", true)
7113 .Case("out", true)
7114 .Case("inout", true)
7115 .Case("oneway", true)
7116 .Case("bycopy", true)
7117 .Case("byref", true)
7118 .Default(false))
7119 Tokens[I].int_data[0] = CXToken_Keyword;
7120 continue;
7121 }
7122
7123 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7124 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7125 Tokens[I].int_data[0] = CXToken_Keyword;
7126 continue;
7127 }
7128 }
7129 }
7130}
7131
Guy Benyei11169dd2012-12-18 14:30:41 +00007132void clang_annotateTokens(CXTranslationUnit TU,
7133 CXToken *Tokens, unsigned NumTokens,
7134 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007135 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007136 LOG_BAD_TU(TU);
7137 return;
7138 }
7139 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007140 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007141 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007142 }
7143
7144 LOG_FUNC_SECTION {
7145 *Log << TU << ' ';
7146 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7147 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7148 *Log << clang_getRange(bloc, eloc);
7149 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007150
7151 // Any token we don't specifically annotate will have a NULL cursor.
7152 CXCursor C = clang_getNullCursor();
7153 for (unsigned I = 0; I != NumTokens; ++I)
7154 Cursors[I] = C;
7155
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007156 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007157 if (!CXXUnit)
7158 return;
7159
7160 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007161
7162 auto AnnotateTokensImpl = [=]() {
7163 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7164 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007165 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007166 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007167 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7168 }
7169}
7170
Guy Benyei11169dd2012-12-18 14:30:41 +00007171//===----------------------------------------------------------------------===//
7172// Operations for querying linkage of a cursor.
7173//===----------------------------------------------------------------------===//
7174
Guy Benyei11169dd2012-12-18 14:30:41 +00007175CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7176 if (!clang_isDeclaration(cursor.kind))
7177 return CXLinkage_Invalid;
7178
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007179 const Decl *D = cxcursor::getCursorDecl(cursor);
7180 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007181 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007182 case NoLinkage:
7183 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007184 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007185 case InternalLinkage: return CXLinkage_Internal;
7186 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007187 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007188 case ExternalLinkage: return CXLinkage_External;
7189 };
7190
7191 return CXLinkage_Invalid;
7192}
Guy Benyei11169dd2012-12-18 14:30:41 +00007193
7194//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007195// Operations for querying visibility of a cursor.
7196//===----------------------------------------------------------------------===//
7197
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007198CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7199 if (!clang_isDeclaration(cursor.kind))
7200 return CXVisibility_Invalid;
7201
7202 const Decl *D = cxcursor::getCursorDecl(cursor);
7203 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7204 switch (ND->getVisibility()) {
7205 case HiddenVisibility: return CXVisibility_Hidden;
7206 case ProtectedVisibility: return CXVisibility_Protected;
7207 case DefaultVisibility: return CXVisibility_Default;
7208 };
7209
7210 return CXVisibility_Invalid;
7211}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007212
7213//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007214// Operations for querying language of a cursor.
7215//===----------------------------------------------------------------------===//
7216
7217static CXLanguageKind getDeclLanguage(const Decl *D) {
7218 if (!D)
7219 return CXLanguage_C;
7220
7221 switch (D->getKind()) {
7222 default:
7223 break;
7224 case Decl::ImplicitParam:
7225 case Decl::ObjCAtDefsField:
7226 case Decl::ObjCCategory:
7227 case Decl::ObjCCategoryImpl:
7228 case Decl::ObjCCompatibleAlias:
7229 case Decl::ObjCImplementation:
7230 case Decl::ObjCInterface:
7231 case Decl::ObjCIvar:
7232 case Decl::ObjCMethod:
7233 case Decl::ObjCProperty:
7234 case Decl::ObjCPropertyImpl:
7235 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007236 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007237 return CXLanguage_ObjC;
7238 case Decl::CXXConstructor:
7239 case Decl::CXXConversion:
7240 case Decl::CXXDestructor:
7241 case Decl::CXXMethod:
7242 case Decl::CXXRecord:
7243 case Decl::ClassTemplate:
7244 case Decl::ClassTemplatePartialSpecialization:
7245 case Decl::ClassTemplateSpecialization:
7246 case Decl::Friend:
7247 case Decl::FriendTemplate:
7248 case Decl::FunctionTemplate:
7249 case Decl::LinkageSpec:
7250 case Decl::Namespace:
7251 case Decl::NamespaceAlias:
7252 case Decl::NonTypeTemplateParm:
7253 case Decl::StaticAssert:
7254 case Decl::TemplateTemplateParm:
7255 case Decl::TemplateTypeParm:
7256 case Decl::UnresolvedUsingTypename:
7257 case Decl::UnresolvedUsingValue:
7258 case Decl::Using:
7259 case Decl::UsingDirective:
7260 case Decl::UsingShadow:
7261 return CXLanguage_CPlusPlus;
7262 }
7263
7264 return CXLanguage_C;
7265}
7266
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007267static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7268 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007269 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007270
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007271 switch (D->getAvailability()) {
7272 case AR_Available:
7273 case AR_NotYetIntroduced:
7274 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007275 return getCursorAvailabilityForDecl(
7276 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007277 return CXAvailability_Available;
7278
7279 case AR_Deprecated:
7280 return CXAvailability_Deprecated;
7281
7282 case AR_Unavailable:
7283 return CXAvailability_NotAvailable;
7284 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007285
7286 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007287}
7288
Guy Benyei11169dd2012-12-18 14:30:41 +00007289enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7290 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007291 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7292 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007293
7294 return CXAvailability_Available;
7295}
7296
7297static CXVersion convertVersion(VersionTuple In) {
7298 CXVersion Out = { -1, -1, -1 };
7299 if (In.empty())
7300 return Out;
7301
7302 Out.Major = In.getMajor();
7303
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007304 Optional<unsigned> Minor = In.getMinor();
7305 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007306 Out.Minor = *Minor;
7307 else
7308 return Out;
7309
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007310 Optional<unsigned> Subminor = In.getSubminor();
7311 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007312 Out.Subminor = *Subminor;
7313
7314 return Out;
7315}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007316
Alex Lorenz1345ea22017-06-12 19:06:30 +00007317static void getCursorPlatformAvailabilityForDecl(
7318 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7319 int *always_unavailable, CXString *unavailable_message,
7320 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007321 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007322 for (auto A : D->attrs()) {
7323 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007324 HadAvailAttr = true;
7325 if (always_deprecated)
7326 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007327 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007328 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007329 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007330 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007331 continue;
7332 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007333
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007334 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007335 HadAvailAttr = true;
7336 if (always_unavailable)
7337 *always_unavailable = 1;
7338 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007339 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007340 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7341 }
7342 continue;
7343 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007344
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007345 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007346 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007347 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007348 }
7349 }
7350
7351 if (!HadAvailAttr)
7352 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7353 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007354 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7355 deprecated_message, always_unavailable, unavailable_message,
7356 AvailabilityAttrs);
7357
7358 if (AvailabilityAttrs.empty())
7359 return;
7360
7361 std::sort(AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7362 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
Reid Klecknere6cde142017-08-04 21:52:25 +00007363 return LHS->getPlatform()->getName() <
7364 RHS->getPlatform()->getName();
Alex Lorenz1345ea22017-06-12 19:06:30 +00007365 });
7366 ASTContext &Ctx = D->getASTContext();
7367 auto It = std::unique(
7368 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7369 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7370 if (LHS->getPlatform() != RHS->getPlatform())
7371 return false;
7372
7373 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7374 LHS->getDeprecated() == RHS->getDeprecated() &&
7375 LHS->getObsoleted() == RHS->getObsoleted() &&
7376 LHS->getMessage() == RHS->getMessage() &&
7377 LHS->getReplacement() == RHS->getReplacement())
7378 return true;
7379
7380 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7381 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7382 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7383 return false;
7384
7385 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7386 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7387
7388 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7389 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7390 if (LHS->getMessage().empty())
7391 LHS->setMessage(Ctx, RHS->getMessage());
7392 if (LHS->getReplacement().empty())
7393 LHS->setReplacement(Ctx, RHS->getReplacement());
7394 }
7395
7396 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7397 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7398 if (LHS->getMessage().empty())
7399 LHS->setMessage(Ctx, RHS->getMessage());
7400 if (LHS->getReplacement().empty())
7401 LHS->setReplacement(Ctx, RHS->getReplacement());
7402 }
7403
7404 return true;
7405 });
7406 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007407}
7408
Alex Lorenz1345ea22017-06-12 19:06:30 +00007409int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007410 CXString *deprecated_message,
7411 int *always_unavailable,
7412 CXString *unavailable_message,
7413 CXPlatformAvailability *availability,
7414 int availability_size) {
7415 if (always_deprecated)
7416 *always_deprecated = 0;
7417 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007418 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007419 if (always_unavailable)
7420 *always_unavailable = 0;
7421 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007422 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007423
Guy Benyei11169dd2012-12-18 14:30:41 +00007424 if (!clang_isDeclaration(cursor.kind))
7425 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007426
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007427 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007428 if (!D)
7429 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007430
Alex Lorenz1345ea22017-06-12 19:06:30 +00007431 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7432 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7433 always_unavailable, unavailable_message,
7434 AvailabilityAttrs);
7435 for (const auto &Avail :
7436 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7437 .take_front(availability_size))) {
7438 availability[Avail.index()].Platform =
7439 cxstring::createDup(Avail.value()->getPlatform()->getName());
7440 availability[Avail.index()].Introduced =
7441 convertVersion(Avail.value()->getIntroduced());
7442 availability[Avail.index()].Deprecated =
7443 convertVersion(Avail.value()->getDeprecated());
7444 availability[Avail.index()].Obsoleted =
7445 convertVersion(Avail.value()->getObsoleted());
7446 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7447 availability[Avail.index()].Message =
7448 cxstring::createDup(Avail.value()->getMessage());
7449 }
7450
7451 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007452}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007453
Guy Benyei11169dd2012-12-18 14:30:41 +00007454void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7455 clang_disposeString(availability->Platform);
7456 clang_disposeString(availability->Message);
7457}
7458
7459CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7460 if (clang_isDeclaration(cursor.kind))
7461 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7462
7463 return CXLanguage_Invalid;
7464}
7465
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007466CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7467 const Decl *D = cxcursor::getCursorDecl(cursor);
7468 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7469 switch (VD->getTLSKind()) {
7470 case VarDecl::TLS_None:
7471 return CXTLS_None;
7472 case VarDecl::TLS_Dynamic:
7473 return CXTLS_Dynamic;
7474 case VarDecl::TLS_Static:
7475 return CXTLS_Static;
7476 }
7477 }
7478
7479 return CXTLS_None;
7480}
7481
Guy Benyei11169dd2012-12-18 14:30:41 +00007482 /// \brief If the given cursor is the "templated" declaration
7483 /// descibing a class or function template, return the class or
7484 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007485static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007486 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007487 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007488
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007489 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007490 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7491 return FunTmpl;
7492
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007493 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007494 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7495 return ClassTmpl;
7496
7497 return D;
7498}
7499
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007500
7501enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7502 StorageClass sc = SC_None;
7503 const Decl *D = getCursorDecl(C);
7504 if (D) {
7505 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7506 sc = FD->getStorageClass();
7507 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7508 sc = VD->getStorageClass();
7509 } else {
7510 return CX_SC_Invalid;
7511 }
7512 } else {
7513 return CX_SC_Invalid;
7514 }
7515 switch (sc) {
7516 case SC_None:
7517 return CX_SC_None;
7518 case SC_Extern:
7519 return CX_SC_Extern;
7520 case SC_Static:
7521 return CX_SC_Static;
7522 case SC_PrivateExtern:
7523 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007524 case SC_Auto:
7525 return CX_SC_Auto;
7526 case SC_Register:
7527 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007528 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007529 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007530}
7531
Guy Benyei11169dd2012-12-18 14:30:41 +00007532CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7533 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007534 if (const Decl *D = getCursorDecl(cursor)) {
7535 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007536 if (!DC)
7537 return clang_getNullCursor();
7538
7539 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7540 getCursorTU(cursor));
7541 }
7542 }
7543
7544 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007545 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007546 return MakeCXCursor(D, getCursorTU(cursor));
7547 }
7548
7549 return clang_getNullCursor();
7550}
7551
7552CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
7553 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007554 if (const Decl *D = getCursorDecl(cursor)) {
7555 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007556 if (!DC)
7557 return clang_getNullCursor();
7558
7559 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7560 getCursorTU(cursor));
7561 }
7562 }
7563
7564 // FIXME: Note that we can't easily compute the lexical context of a
7565 // statement or expression, so we return nothing.
7566 return clang_getNullCursor();
7567}
7568
7569CXFile clang_getIncludedFile(CXCursor cursor) {
7570 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00007571 return nullptr;
7572
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00007573 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00007574 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00007575}
7576
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007577unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
7578 if (C.kind != CXCursor_ObjCPropertyDecl)
7579 return CXObjCPropertyAttr_noattr;
7580
7581 unsigned Result = CXObjCPropertyAttr_noattr;
7582 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
7583 ObjCPropertyDecl::PropertyAttributeKind Attr =
7584 PD->getPropertyAttributesAsWritten();
7585
7586#define SET_CXOBJCPROP_ATTR(A) \
7587 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
7588 Result |= CXObjCPropertyAttr_##A
7589 SET_CXOBJCPROP_ATTR(readonly);
7590 SET_CXOBJCPROP_ATTR(getter);
7591 SET_CXOBJCPROP_ATTR(assign);
7592 SET_CXOBJCPROP_ATTR(readwrite);
7593 SET_CXOBJCPROP_ATTR(retain);
7594 SET_CXOBJCPROP_ATTR(copy);
7595 SET_CXOBJCPROP_ATTR(nonatomic);
7596 SET_CXOBJCPROP_ATTR(setter);
7597 SET_CXOBJCPROP_ATTR(atomic);
7598 SET_CXOBJCPROP_ATTR(weak);
7599 SET_CXOBJCPROP_ATTR(strong);
7600 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00007601 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00007602#undef SET_CXOBJCPROP_ATTR
7603
7604 return Result;
7605}
7606
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00007607unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
7608 if (!clang_isDeclaration(C.kind))
7609 return CXObjCDeclQualifier_None;
7610
7611 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
7612 const Decl *D = getCursorDecl(C);
7613 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7614 QT = MD->getObjCDeclQualifier();
7615 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
7616 QT = PD->getObjCDeclQualifier();
7617 if (QT == Decl::OBJC_TQ_None)
7618 return CXObjCDeclQualifier_None;
7619
7620 unsigned Result = CXObjCDeclQualifier_None;
7621 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
7622 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
7623 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
7624 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
7625 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
7626 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
7627
7628 return Result;
7629}
7630
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00007631unsigned clang_Cursor_isObjCOptional(CXCursor C) {
7632 if (!clang_isDeclaration(C.kind))
7633 return 0;
7634
7635 const Decl *D = getCursorDecl(C);
7636 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
7637 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
7638 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7639 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
7640
7641 return 0;
7642}
7643
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00007644unsigned clang_Cursor_isVariadic(CXCursor C) {
7645 if (!clang_isDeclaration(C.kind))
7646 return 0;
7647
7648 const Decl *D = getCursorDecl(C);
7649 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7650 return FD->isVariadic();
7651 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
7652 return MD->isVariadic();
7653
7654 return 0;
7655}
7656
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007657unsigned clang_Cursor_isExternalSymbol(CXCursor C,
7658 CXString *language, CXString *definedIn,
7659 unsigned *isGenerated) {
7660 if (!clang_isDeclaration(C.kind))
7661 return 0;
7662
7663 const Decl *D = getCursorDecl(C);
7664
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00007665 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00007666 if (language)
7667 *language = cxstring::createDup(attr->getLanguage());
7668 if (definedIn)
7669 *definedIn = cxstring::createDup(attr->getDefinedIn());
7670 if (isGenerated)
7671 *isGenerated = attr->getGeneratedDeclaration();
7672 return 1;
7673 }
7674 return 0;
7675}
7676
Guy Benyei11169dd2012-12-18 14:30:41 +00007677CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
7678 if (!clang_isDeclaration(C.kind))
7679 return clang_getNullRange();
7680
7681 const Decl *D = getCursorDecl(C);
7682 ASTContext &Context = getCursorContext(C);
7683 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7684 if (!RC)
7685 return clang_getNullRange();
7686
7687 return cxloc::translateSourceRange(Context, RC->getSourceRange());
7688}
7689
7690CXString clang_Cursor_getRawCommentText(CXCursor C) {
7691 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007692 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007693
7694 const Decl *D = getCursorDecl(C);
7695 ASTContext &Context = getCursorContext(C);
7696 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7697 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
7698 StringRef();
7699
7700 // Don't duplicate the string because RawText points directly into source
7701 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007702 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007703}
7704
7705CXString clang_Cursor_getBriefCommentText(CXCursor C) {
7706 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007707 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007708
7709 const Decl *D = getCursorDecl(C);
7710 const ASTContext &Context = getCursorContext(C);
7711 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
7712
7713 if (RC) {
7714 StringRef BriefText = RC->getBriefText(Context);
7715
7716 // Don't duplicate the string because RawComment ensures that this memory
7717 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007718 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00007719 }
7720
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00007721 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00007722}
7723
Guy Benyei11169dd2012-12-18 14:30:41 +00007724CXModule clang_Cursor_getModule(CXCursor C) {
7725 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007726 if (const ImportDecl *ImportD =
7727 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00007728 return ImportD->getImportedModule();
7729 }
7730
Craig Topper69186e72014-06-08 08:38:04 +00007731 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007732}
7733
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007734CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
7735 if (isNotUsableTU(TU)) {
7736 LOG_BAD_TU(TU);
7737 return nullptr;
7738 }
7739 if (!File)
7740 return nullptr;
7741 FileEntry *FE = static_cast<FileEntry *>(File);
7742
7743 ASTUnit &Unit = *cxtu::getASTUnit(TU);
7744 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
7745 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
7746
Richard Smithfeb54b62014-10-23 02:01:19 +00007747 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00007748}
7749
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007750CXFile clang_Module_getASTFile(CXModule CXMod) {
7751 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007752 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00007753 Module *Mod = static_cast<Module*>(CXMod);
7754 return const_cast<FileEntry *>(Mod->getASTFile());
7755}
7756
Guy Benyei11169dd2012-12-18 14:30:41 +00007757CXModule clang_Module_getParent(CXModule CXMod) {
7758 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007759 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007760 Module *Mod = static_cast<Module*>(CXMod);
7761 return Mod->Parent;
7762}
7763
7764CXString clang_Module_getName(CXModule CXMod) {
7765 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007766 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007767 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007768 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00007769}
7770
7771CXString clang_Module_getFullName(CXModule CXMod) {
7772 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007773 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007774 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00007775 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007776}
7777
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00007778int clang_Module_isSystem(CXModule CXMod) {
7779 if (!CXMod)
7780 return 0;
7781 Module *Mod = static_cast<Module*>(CXMod);
7782 return Mod->IsSystem;
7783}
7784
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007785unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
7786 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007787 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007788 LOG_BAD_TU(TU);
7789 return 0;
7790 }
7791 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00007792 return 0;
7793 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007794 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
7795 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7796 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007797}
7798
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007799CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
7800 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007801 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007802 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00007803 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007804 }
7805 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00007806 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007807 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007808 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00007809
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00007810 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
7811 if (Index < TopHeaders.size())
7812 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007813
Craig Topper69186e72014-06-08 08:38:04 +00007814 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007815}
7816
Guy Benyei11169dd2012-12-18 14:30:41 +00007817//===----------------------------------------------------------------------===//
7818// C++ AST instrospection.
7819//===----------------------------------------------------------------------===//
7820
Jonathan Coe29565352016-04-27 12:48:25 +00007821unsigned clang_CXXConstructor_isDefaultConstructor(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->isDefaultConstructor()) ? 1 : 0;
7829}
7830
7831unsigned clang_CXXConstructor_isCopyConstructor(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->isCopyConstructor()) ? 1 : 0;
7839}
7840
7841unsigned clang_CXXConstructor_isMoveConstructor(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 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
7849}
7850
7851unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
7852 if (!clang_isDeclaration(C.kind))
7853 return 0;
7854
7855 const Decl *D = cxcursor::getCursorDecl(C);
7856 const CXXConstructorDecl *Constructor =
7857 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
7858 // Passing 'false' excludes constructors marked 'explicit'.
7859 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
7860}
7861
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00007862unsigned clang_CXXField_isMutable(CXCursor C) {
7863 if (!clang_isDeclaration(C.kind))
7864 return 0;
7865
7866 if (const auto D = cxcursor::getCursorDecl(C))
7867 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
7868 return FD->isMutable() ? 1 : 0;
7869 return 0;
7870}
7871
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007872unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
7873 if (!clang_isDeclaration(C.kind))
7874 return 0;
7875
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007876 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007877 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007878 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00007879 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
7880}
7881
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007882unsigned clang_CXXMethod_isConst(CXCursor C) {
7883 if (!clang_isDeclaration(C.kind))
7884 return 0;
7885
7886 const Decl *D = cxcursor::getCursorDecl(C);
7887 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007888 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00007889 return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
7890}
7891
Jonathan Coe29565352016-04-27 12:48:25 +00007892unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
7893 if (!clang_isDeclaration(C.kind))
7894 return 0;
7895
7896 const Decl *D = cxcursor::getCursorDecl(C);
7897 const CXXMethodDecl *Method =
7898 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
7899 return (Method && Method->isDefaulted()) ? 1 : 0;
7900}
7901
Guy Benyei11169dd2012-12-18 14:30:41 +00007902unsigned clang_CXXMethod_isStatic(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->isStatic()) ? 1 : 0;
7910}
7911
7912unsigned clang_CXXMethod_isVirtual(CXCursor C) {
7913 if (!clang_isDeclaration(C.kind))
7914 return 0;
7915
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007916 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00007917 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00007918 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007919 return (Method && Method->isVirtual()) ? 1 : 0;
7920}
Guy Benyei11169dd2012-12-18 14:30:41 +00007921
Alex Lorenz34ccadc2017-12-14 22:01:50 +00007922unsigned clang_CXXRecord_isAbstract(CXCursor C) {
7923 if (!clang_isDeclaration(C.kind))
7924 return 0;
7925
7926 const auto *D = cxcursor::getCursorDecl(C);
7927 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
7928 if (RD)
7929 RD = RD->getDefinition();
7930 return (RD && RD->isAbstract()) ? 1 : 0;
7931}
7932
Alex Lorenzff7f42e2017-07-12 11:35:11 +00007933unsigned clang_EnumDecl_isScoped(CXCursor C) {
7934 if (!clang_isDeclaration(C.kind))
7935 return 0;
7936
7937 const Decl *D = cxcursor::getCursorDecl(C);
7938 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
7939 return (Enum && Enum->isScoped()) ? 1 : 0;
7940}
7941
Guy Benyei11169dd2012-12-18 14:30:41 +00007942//===----------------------------------------------------------------------===//
7943// Attribute introspection.
7944//===----------------------------------------------------------------------===//
7945
Guy Benyei11169dd2012-12-18 14:30:41 +00007946CXType clang_getIBOutletCollectionType(CXCursor C) {
7947 if (C.kind != CXCursor_IBOutletCollectionAttr)
7948 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
7949
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00007950 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00007951 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
7952
7953 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
7954}
Guy Benyei11169dd2012-12-18 14:30:41 +00007955
7956//===----------------------------------------------------------------------===//
7957// Inspecting memory usage.
7958//===----------------------------------------------------------------------===//
7959
7960typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
7961
7962static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
7963 enum CXTUResourceUsageKind k,
7964 unsigned long amount) {
7965 CXTUResourceUsageEntry entry = { k, amount };
7966 entries.push_back(entry);
7967}
7968
Guy Benyei11169dd2012-12-18 14:30:41 +00007969const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
7970 const char *str = "";
7971 switch (kind) {
7972 case CXTUResourceUsage_AST:
7973 str = "ASTContext: expressions, declarations, and types";
7974 break;
7975 case CXTUResourceUsage_Identifiers:
7976 str = "ASTContext: identifiers";
7977 break;
7978 case CXTUResourceUsage_Selectors:
7979 str = "ASTContext: selectors";
7980 break;
7981 case CXTUResourceUsage_GlobalCompletionResults:
7982 str = "Code completion: cached global results";
7983 break;
7984 case CXTUResourceUsage_SourceManagerContentCache:
7985 str = "SourceManager: content cache allocator";
7986 break;
7987 case CXTUResourceUsage_AST_SideTables:
7988 str = "ASTContext: side tables";
7989 break;
7990 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
7991 str = "SourceManager: malloc'ed memory buffers";
7992 break;
7993 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
7994 str = "SourceManager: mmap'ed memory buffers";
7995 break;
7996 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
7997 str = "ExternalASTSource: malloc'ed memory buffers";
7998 break;
7999 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8000 str = "ExternalASTSource: mmap'ed memory buffers";
8001 break;
8002 case CXTUResourceUsage_Preprocessor:
8003 str = "Preprocessor: malloc'ed memory";
8004 break;
8005 case CXTUResourceUsage_PreprocessingRecord:
8006 str = "Preprocessor: PreprocessingRecord";
8007 break;
8008 case CXTUResourceUsage_SourceManager_DataStructures:
8009 str = "SourceManager: data structures and tables";
8010 break;
8011 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8012 str = "Preprocessor: header search tables";
8013 break;
8014 }
8015 return str;
8016}
8017
8018CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008019 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008020 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008021 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008022 return usage;
8023 }
8024
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008025 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008026 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008027 ASTContext &astContext = astUnit->getASTContext();
8028
8029 // How much memory is used by AST nodes and types?
8030 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8031 (unsigned long) astContext.getASTAllocatedMemory());
8032
8033 // How much memory is used by identifiers?
8034 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8035 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8036
8037 // How much memory is used for selectors?
8038 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8039 (unsigned long) astContext.Selectors.getTotalMemory());
8040
8041 // How much memory is used by ASTContext's side tables?
8042 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8043 (unsigned long) astContext.getSideTableAllocatedMemory());
8044
8045 // How much memory is used for caching global code completion results?
8046 unsigned long completionBytes = 0;
8047 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008048 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008049 completionBytes = completionAllocator->getTotalMemory();
8050 }
8051 createCXTUResourceUsageEntry(*entries,
8052 CXTUResourceUsage_GlobalCompletionResults,
8053 completionBytes);
8054
8055 // How much memory is being used by SourceManager's content cache?
8056 createCXTUResourceUsageEntry(*entries,
8057 CXTUResourceUsage_SourceManagerContentCache,
8058 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8059
8060 // How much memory is being used by the MemoryBuffer's in SourceManager?
8061 const SourceManager::MemoryBufferSizes &srcBufs =
8062 astUnit->getSourceManager().getMemoryBufferSizes();
8063
8064 createCXTUResourceUsageEntry(*entries,
8065 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8066 (unsigned long) srcBufs.malloc_bytes);
8067 createCXTUResourceUsageEntry(*entries,
8068 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8069 (unsigned long) srcBufs.mmap_bytes);
8070 createCXTUResourceUsageEntry(*entries,
8071 CXTUResourceUsage_SourceManager_DataStructures,
8072 (unsigned long) astContext.getSourceManager()
8073 .getDataStructureSizes());
8074
8075 // How much memory is being used by the ExternalASTSource?
8076 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8077 const ExternalASTSource::MemoryBufferSizes &sizes =
8078 esrc->getMemoryBufferSizes();
8079
8080 createCXTUResourceUsageEntry(*entries,
8081 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8082 (unsigned long) sizes.malloc_bytes);
8083 createCXTUResourceUsageEntry(*entries,
8084 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8085 (unsigned long) sizes.mmap_bytes);
8086 }
8087
8088 // How much memory is being used by the Preprocessor?
8089 Preprocessor &pp = astUnit->getPreprocessor();
8090 createCXTUResourceUsageEntry(*entries,
8091 CXTUResourceUsage_Preprocessor,
8092 pp.getTotalMemory());
8093
8094 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8095 createCXTUResourceUsageEntry(*entries,
8096 CXTUResourceUsage_PreprocessingRecord,
8097 pRec->getTotalMemory());
8098 }
8099
8100 createCXTUResourceUsageEntry(*entries,
8101 CXTUResourceUsage_Preprocessor_HeaderSearch,
8102 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008103
Guy Benyei11169dd2012-12-18 14:30:41 +00008104 CXTUResourceUsage usage = { (void*) entries.get(),
8105 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008106 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008107 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008108 return usage;
8109}
8110
8111void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8112 if (usage.data)
8113 delete (MemUsageEntries*) usage.data;
8114}
8115
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008116CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8117 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008118 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008119 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008120
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008121 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008122 LOG_BAD_TU(TU);
8123 return skipped;
8124 }
8125
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008126 if (!file)
8127 return skipped;
8128
8129 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8130 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8131 if (!ppRec)
8132 return skipped;
8133
8134 ASTContext &Ctx = astUnit->getASTContext();
8135 SourceManager &sm = Ctx.getSourceManager();
8136 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8137 FileID wantedFileID = sm.translateFile(fileEntry);
8138
8139 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8140 std::vector<SourceRange> wantedRanges;
8141 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8142 i != ei; ++i) {
8143 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8144 wantedRanges.push_back(*i);
8145 }
8146
8147 skipped->count = wantedRanges.size();
8148 skipped->ranges = new CXSourceRange[skipped->count];
8149 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8150 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8151
8152 return skipped;
8153}
8154
Cameron Desrochersd8091282016-08-18 15:43:55 +00008155CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8156 CXSourceRangeList *skipped = new CXSourceRangeList;
8157 skipped->count = 0;
8158 skipped->ranges = nullptr;
8159
8160 if (isNotUsableTU(TU)) {
8161 LOG_BAD_TU(TU);
8162 return skipped;
8163 }
8164
8165 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8166 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8167 if (!ppRec)
8168 return skipped;
8169
8170 ASTContext &Ctx = astUnit->getASTContext();
8171
8172 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8173
8174 skipped->count = SkippedRanges.size();
8175 skipped->ranges = new CXSourceRange[skipped->count];
8176 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8177 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8178
8179 return skipped;
8180}
8181
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008182void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8183 if (ranges) {
8184 delete[] ranges->ranges;
8185 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008186 }
8187}
8188
Guy Benyei11169dd2012-12-18 14:30:41 +00008189void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8190 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8191 for (unsigned I = 0; I != Usage.numEntries; ++I)
8192 fprintf(stderr, " %s: %lu\n",
8193 clang_getTUResourceUsageName(Usage.entries[I].kind),
8194 Usage.entries[I].amount);
8195
8196 clang_disposeCXTUResourceUsage(Usage);
8197}
8198
8199//===----------------------------------------------------------------------===//
8200// Misc. utility functions.
8201//===----------------------------------------------------------------------===//
8202
8203/// Default to using an 8 MB stack size on "safety" threads.
8204static unsigned SafetyStackThreadSize = 8 << 20;
8205
8206namespace clang {
8207
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008208bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008209 unsigned Size) {
8210 if (!Size)
8211 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008212 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008213 return CRC.RunSafelyOnThread(Fn, Size);
8214 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008215}
8216
8217unsigned GetSafetyThreadStackSize() {
8218 return SafetyStackThreadSize;
8219}
8220
8221void SetSafetyThreadStackSize(unsigned Value) {
8222 SafetyStackThreadSize = Value;
8223}
8224
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008225}
Guy Benyei11169dd2012-12-18 14:30:41 +00008226
8227void clang::setThreadBackgroundPriority() {
8228 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8229 return;
8230
Alp Toker1a86ad22014-07-06 06:24:00 +00008231#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008232 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8233#endif
8234}
8235
8236void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8237 if (!Unit)
8238 return;
8239
8240 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8241 DEnd = Unit->stored_diag_end();
8242 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008243 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008244 CXString Msg = clang_formatDiagnostic(&Diag,
8245 clang_defaultDiagnosticDisplayOptions());
8246 fprintf(stderr, "%s\n", clang_getCString(Msg));
8247 clang_disposeString(Msg);
8248 }
8249#ifdef LLVM_ON_WIN32
8250 // On Windows, force a flush, since there may be multiple copies of
8251 // stderr and stdout in the file system, all with different buffers
8252 // but writing to the same device.
8253 fflush(stderr);
8254#endif
8255}
8256
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008257MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8258 SourceLocation MacroDefLoc,
8259 CXTranslationUnit TU){
8260 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008261 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008262 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008263 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008264
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008265 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008266 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008267 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008268 if (MD) {
8269 for (MacroDirective::DefInfo
8270 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8271 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8272 return Def.getMacroInfo();
8273 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008274 }
8275
Craig Topper69186e72014-06-08 08:38:04 +00008276 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008277}
8278
Richard Smith66a81862015-05-04 02:25:31 +00008279const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008280 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008281 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008282 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008283 const IdentifierInfo *II = MacroDef->getName();
8284 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008285 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008286
8287 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8288}
8289
Richard Smith66a81862015-05-04 02:25:31 +00008290MacroDefinitionRecord *
8291cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8292 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008293 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008294 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008295 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008296 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008297
8298 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008299 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008300 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8301 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008302 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008303
8304 // Check that the token is inside the definition and not its argument list.
8305 SourceManager &SM = Unit->getSourceManager();
8306 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008307 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008308 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008309 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008310
8311 Preprocessor &PP = Unit->getPreprocessor();
8312 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8313 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008314 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008315
Alp Toker2d57cea2014-05-17 04:53:25 +00008316 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008317 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008318 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008319
8320 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008321 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008322 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008323
Richard Smith20e883e2015-04-29 23:20:19 +00008324 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008325 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008326 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008327
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008328 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008329}
8330
Richard Smith66a81862015-05-04 02:25:31 +00008331MacroDefinitionRecord *
8332cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8333 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008334 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008335 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008336
8337 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008338 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008339 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008340 Preprocessor &PP = Unit->getPreprocessor();
8341 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008342 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008343 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8344 Token Tok;
8345 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008346 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008347
8348 return checkForMacroInMacroDefinition(MI, Tok, TU);
8349}
8350
Guy Benyei11169dd2012-12-18 14:30:41 +00008351CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008352 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008353}
8354
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008355Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8356 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008357 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008358 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008359 if (Unit->isMainFileAST())
8360 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008361 return *this;
8362 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008363 } else {
8364 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008365 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008366 return *this;
8367}
8368
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008369Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8370 *this << FE->getName();
8371 return *this;
8372}
8373
8374Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8375 CXString cursorName = clang_getCursorDisplayName(cursor);
8376 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8377 clang_disposeString(cursorName);
8378 return *this;
8379}
8380
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008381Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8382 CXFile File;
8383 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008384 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008385 CXString FileName = clang_getFileName(File);
8386 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8387 clang_disposeString(FileName);
8388 return *this;
8389}
8390
8391Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8392 CXSourceLocation BLoc = clang_getRangeStart(range);
8393 CXSourceLocation ELoc = clang_getRangeEnd(range);
8394
8395 CXFile BFile;
8396 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008397 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008398
8399 CXFile EFile;
8400 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008401 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008402
8403 CXString BFileName = clang_getFileName(BFile);
8404 if (BFile == EFile) {
8405 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8406 BLine, BColumn, ELine, EColumn);
8407 } else {
8408 CXString EFileName = clang_getFileName(EFile);
8409 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8410 BLine, BColumn)
8411 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8412 ELine, EColumn);
8413 clang_disposeString(EFileName);
8414 }
8415 clang_disposeString(BFileName);
8416 return *this;
8417}
8418
8419Logger &cxindex::Logger::operator<<(CXString Str) {
8420 *this << clang_getCString(Str);
8421 return *this;
8422}
8423
8424Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8425 LogOS << Fmt;
8426 return *this;
8427}
8428
Chandler Carruth37ad2582014-06-27 15:14:39 +00008429static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8430
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008431cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008432 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008433
8434 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8435
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008436 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008437 OS << "[libclang:" << Name << ':';
8438
Alp Toker1a86ad22014-07-06 06:24:00 +00008439#ifdef USE_DARWIN_THREADS
8440 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008441 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8442 OS << tid << ':';
8443#endif
8444
8445 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8446 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008447 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008448
8449 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008450 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008451 OS << "--------------------------------------------------\n";
8452 }
8453}
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008454
8455#ifdef CLANG_TOOL_EXTRA_BUILD
8456// This anchor is used to force the linker to link the clang-tidy plugin.
8457extern volatile int ClangTidyPluginAnchorSource;
8458static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8459 ClangTidyPluginAnchorSource;
Benjamin Kramer9eba7352016-11-17 15:22:36 +00008460
8461// This anchor is used to force the linker to link the clang-include-fixer
8462// plugin.
8463extern volatile int ClangIncludeFixerPluginAnchorSource;
8464static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8465 ClangIncludeFixerPluginAnchorSource;
Benjamin Kramerc1ffdab2016-03-03 08:58:18 +00008466#endif