CIndex.cpp revision 9482a185d34d8b0f6d788c44e2c128991622c0ad
1//===- 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
15#include "CIndexer.h"
16#include "CXCursor.h"
17#include "CXTranslationUnit.h"
18#include "CXString.h"
19#include "CXType.h"
20#include "CXSourceLocation.h"
21#include "CIndexDiagnostic.h"
22#include "CursorVisitor.h"
23
24#include "clang/Basic/Version.h"
25
26#include "clang/AST/StmtVisitor.h"
27#include "clang/Basic/Diagnostic.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
30#include "clang/Frontend/FrontendDiagnostic.h"
31#include "clang/Lex/Lexer.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/PreprocessingRecord.h"
34#include "clang/Lex/Preprocessor.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/Optional.h"
37#include "llvm/ADT/StringSwitch.h"
38#include "llvm/Support/SaveAndRestore.h"
39#include "llvm/Support/CrashRecoveryContext.h"
40#include "llvm/Support/PrettyStackTrace.h"
41#include "llvm/Support/MemoryBuffer.h"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/Support/Timer.h"
44#include "llvm/Support/Mutex.h"
45#include "llvm/Support/Program.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/Threading.h"
48#include "llvm/Support/Compiler.h"
49
50using namespace clang;
51using namespace clang::cxcursor;
52using namespace clang::cxstring;
53using namespace clang::cxtu;
54using namespace clang::cxindex;
55
56CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *TU) {
57  if (!TU)
58    return 0;
59  CXTranslationUnit D = new CXTranslationUnitImpl();
60  D->CIdx = CIdx;
61  D->TUData = TU;
62  D->StringPool = createCXStringPool();
63  D->Diagnostics = 0;
64  return D;
65}
66
67cxtu::CXTUOwner::~CXTUOwner() {
68  if (TU)
69    clang_disposeTranslationUnit(TU);
70}
71
72/// \brief Compare two source ranges to determine their relative position in
73/// the translation unit.
74static RangeComparisonResult RangeCompare(SourceManager &SM,
75                                          SourceRange R1,
76                                          SourceRange R2) {
77  assert(R1.isValid() && "First range is invalid?");
78  assert(R2.isValid() && "Second range is invalid?");
79  if (R1.getEnd() != R2.getBegin() &&
80      SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
81    return RangeBefore;
82  if (R2.getEnd() != R1.getBegin() &&
83      SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
84    return RangeAfter;
85  return RangeOverlap;
86}
87
88/// \brief Determine if a source location falls within, before, or after a
89///   a given source range.
90static RangeComparisonResult LocationCompare(SourceManager &SM,
91                                             SourceLocation L, SourceRange R) {
92  assert(R.isValid() && "First range is invalid?");
93  assert(L.isValid() && "Second range is invalid?");
94  if (L == R.getBegin() || L == R.getEnd())
95    return RangeOverlap;
96  if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
97    return RangeBefore;
98  if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
99    return RangeAfter;
100  return RangeOverlap;
101}
102
103/// \brief Translate a Clang source range into a CIndex source range.
104///
105/// Clang internally represents ranges where the end location points to the
106/// start of the token at the end. However, for external clients it is more
107/// useful to have a CXSourceRange be a proper half-open interval. This routine
108/// does the appropriate translation.
109CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
110                                          const LangOptions &LangOpts,
111                                          const CharSourceRange &R) {
112  // We want the last character in this location, so we will adjust the
113  // location accordingly.
114  SourceLocation EndLoc = R.getEnd();
115  if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
116    EndLoc = SM.getExpansionRange(EndLoc).second;
117  if (R.isTokenRange() && !EndLoc.isInvalid()) {
118    unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
119                                                SM, LangOpts);
120    EndLoc = EndLoc.getLocWithOffset(Length);
121  }
122
123  CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
124                           R.getBegin().getRawEncoding(),
125                           EndLoc.getRawEncoding() };
126  return Result;
127}
128
129//===----------------------------------------------------------------------===//
130// Cursor visitor.
131//===----------------------------------------------------------------------===//
132
133static SourceRange getRawCursorExtent(CXCursor C);
134static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
135
136
137RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
138  return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
139}
140
141/// \brief Visit the given cursor and, if requested by the visitor,
142/// its children.
143///
144/// \param Cursor the cursor to visit.
145///
146/// \param CheckRegionOfInterest if true, then the caller already checked that
147/// this cursor is within the region of interest.
148///
149/// \returns true if the visitation should be aborted, false if it
150/// should continue.
151bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
152  if (clang_isInvalid(Cursor.kind))
153    return false;
154
155  if (clang_isDeclaration(Cursor.kind)) {
156    Decl *D = getCursorDecl(Cursor);
157    if (!D) {
158      assert(0 && "Invalid declaration cursor");
159      return true; // abort.
160    }
161
162    // Ignore implicit declarations, unless it's an objc method because
163    // currently we should report implicit methods for properties when indexing.
164    if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
165      return false;
166  }
167
168  // If we have a range of interest, and this cursor doesn't intersect with it,
169  // we're done.
170  if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
171    SourceRange Range = getRawCursorExtent(Cursor);
172    if (Range.isInvalid() || CompareRegionOfInterest(Range))
173      return false;
174  }
175
176  switch (Visitor(Cursor, Parent, ClientData)) {
177  case CXChildVisit_Break:
178    return true;
179
180  case CXChildVisit_Continue:
181    return false;
182
183  case CXChildVisit_Recurse:
184    return VisitChildren(Cursor);
185  }
186
187  llvm_unreachable("Invalid CXChildVisitResult!");
188}
189
190static bool visitPreprocessedEntitiesInRange(SourceRange R,
191                                             PreprocessingRecord &PPRec,
192                                             CursorVisitor &Visitor) {
193  SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
194  FileID FID;
195
196  if (!Visitor.shouldVisitIncludedEntities()) {
197    // If the begin/end of the range lie in the same FileID, do the optimization
198    // where we skip preprocessed entities that do not come from the same FileID.
199    FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
200    if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
201      FID = FileID();
202  }
203
204  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
205    Entities = PPRec.getPreprocessedEntitiesInRange(R);
206  return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
207                                           PPRec, FID);
208}
209
210void CursorVisitor::visitFileRegion() {
211  if (RegionOfInterest.isInvalid())
212    return;
213
214  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
215  SourceManager &SM = Unit->getSourceManager();
216
217  std::pair<FileID, unsigned>
218    Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
219    End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
220
221  if (End.first != Begin.first) {
222    // If the end does not reside in the same file, try to recover by
223    // picking the end of the file of begin location.
224    End.first = Begin.first;
225    End.second = SM.getFileIDSize(Begin.first);
226  }
227
228  assert(Begin.first == End.first);
229  if (Begin.second > End.second)
230    return;
231
232  FileID File = Begin.first;
233  unsigned Offset = Begin.second;
234  unsigned Length = End.second - Begin.second;
235
236  if (!VisitDeclsOnly && !VisitPreprocessorLast)
237    if (visitPreprocessedEntitiesInRegion())
238      return; // visitation break.
239
240  visitDeclsFromFileRegion(File, Offset, Length);
241
242  if (!VisitDeclsOnly && VisitPreprocessorLast)
243    visitPreprocessedEntitiesInRegion();
244}
245
246static bool isInLexicalContext(Decl *D, DeclContext *DC) {
247  if (!DC)
248    return false;
249
250  for (DeclContext *DeclDC = D->getLexicalDeclContext();
251         DeclDC; DeclDC = DeclDC->getLexicalParent()) {
252    if (DeclDC == DC)
253      return true;
254  }
255  return false;
256}
257
258void CursorVisitor::visitDeclsFromFileRegion(FileID File,
259                                             unsigned Offset, unsigned Length) {
260  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
261  SourceManager &SM = Unit->getSourceManager();
262  SourceRange Range = RegionOfInterest;
263
264  SmallVector<Decl *, 16> Decls;
265  Unit->findFileRegionDecls(File, Offset, Length, Decls);
266
267  // If we didn't find any file level decls for the file, try looking at the
268  // file that it was included from.
269  while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
270    bool Invalid = false;
271    const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
272    if (Invalid)
273      return;
274
275    SourceLocation Outer;
276    if (SLEntry.isFile())
277      Outer = SLEntry.getFile().getIncludeLoc();
278    else
279      Outer = SLEntry.getExpansion().getExpansionLocStart();
280    if (Outer.isInvalid())
281      return;
282
283    llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
284    Length = 0;
285    Unit->findFileRegionDecls(File, Offset, Length, Decls);
286  }
287
288  assert(!Decls.empty());
289
290  bool VisitedAtLeastOnce = false;
291  DeclContext *CurDC = 0;
292  SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
293  for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
294    Decl *D = *DIt;
295    if (D->getSourceRange().isInvalid())
296      continue;
297
298    if (isInLexicalContext(D, CurDC))
299      continue;
300
301    CurDC = dyn_cast<DeclContext>(D);
302
303    if (TagDecl *TD = dyn_cast<TagDecl>(D))
304      if (!TD->isFreeStanding())
305        continue;
306
307    RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
308    if (CompRes == RangeBefore)
309      continue;
310    if (CompRes == RangeAfter)
311      break;
312
313    assert(CompRes == RangeOverlap);
314    VisitedAtLeastOnce = true;
315
316    if (isa<ObjCContainerDecl>(D)) {
317      FileDI_current = &DIt;
318      FileDE_current = DE;
319    } else {
320      FileDI_current = 0;
321    }
322
323    if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
324      break;
325  }
326
327  if (VisitedAtLeastOnce)
328    return;
329
330  // No Decls overlapped with the range. Move up the lexical context until there
331  // is a context that contains the range or we reach the translation unit
332  // level.
333  DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
334                                         : (*(DIt-1))->getLexicalDeclContext();
335
336  while (DC && !DC->isTranslationUnit()) {
337    Decl *D = cast<Decl>(DC);
338    SourceRange CurDeclRange = D->getSourceRange();
339    if (CurDeclRange.isInvalid())
340      break;
341
342    if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
343      Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
344      break;
345    }
346
347    DC = D->getLexicalDeclContext();
348  }
349}
350
351bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
352  if (!AU->getPreprocessor().getPreprocessingRecord())
353    return false;
354
355  PreprocessingRecord &PPRec
356    = *AU->getPreprocessor().getPreprocessingRecord();
357  SourceManager &SM = AU->getSourceManager();
358
359  if (RegionOfInterest.isValid()) {
360    SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
361    SourceLocation B = MappedRange.getBegin();
362    SourceLocation E = MappedRange.getEnd();
363
364    if (AU->isInPreambleFileID(B)) {
365      if (SM.isLoadedSourceLocation(E))
366        return visitPreprocessedEntitiesInRange(SourceRange(B, E),
367                                                 PPRec, *this);
368
369      // Beginning of range lies in the preamble but it also extends beyond
370      // it into the main file. Split the range into 2 parts, one covering
371      // the preamble and another covering the main file. This allows subsequent
372      // calls to visitPreprocessedEntitiesInRange to accept a source range that
373      // lies in the same FileID, allowing it to skip preprocessed entities that
374      // do not come from the same FileID.
375      bool breaked =
376        visitPreprocessedEntitiesInRange(
377                                   SourceRange(B, AU->getEndOfPreambleFileID()),
378                                          PPRec, *this);
379      if (breaked) return true;
380      return visitPreprocessedEntitiesInRange(
381                                    SourceRange(AU->getStartOfMainFileID(), E),
382                                        PPRec, *this);
383    }
384
385    return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
386  }
387
388  bool OnlyLocalDecls
389    = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
390
391  if (OnlyLocalDecls)
392    return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
393                                     PPRec);
394
395  return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
396}
397
398template<typename InputIterator>
399bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
400                                              InputIterator Last,
401                                              PreprocessingRecord &PPRec,
402                                              FileID FID) {
403  for (; First != Last; ++First) {
404    if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
405      continue;
406
407    PreprocessedEntity *PPE = *First;
408    if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
409      if (Visit(MakeMacroExpansionCursor(ME, TU)))
410        return true;
411
412      continue;
413    }
414
415    if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
416      if (Visit(MakeMacroDefinitionCursor(MD, TU)))
417        return true;
418
419      continue;
420    }
421
422    if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
423      if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
424        return true;
425
426      continue;
427    }
428  }
429
430  return false;
431}
432
433/// \brief Visit the children of the given cursor.
434///
435/// \returns true if the visitation should be aborted, false if it
436/// should continue.
437bool CursorVisitor::VisitChildren(CXCursor Cursor) {
438  if (clang_isReference(Cursor.kind) &&
439      Cursor.kind != CXCursor_CXXBaseSpecifier) {
440    // By definition, references have no children.
441    return false;
442  }
443
444  // Set the Parent field to Cursor, then back to its old value once we're
445  // done.
446  SetParentRAII SetParent(Parent, StmtParent, Cursor);
447
448  if (clang_isDeclaration(Cursor.kind)) {
449    Decl *D = getCursorDecl(Cursor);
450    if (!D)
451      return false;
452
453    return VisitAttributes(D) || Visit(D);
454  }
455
456  if (clang_isStatement(Cursor.kind)) {
457    if (Stmt *S = getCursorStmt(Cursor))
458      return Visit(S);
459
460    return false;
461  }
462
463  if (clang_isExpression(Cursor.kind)) {
464    if (Expr *E = getCursorExpr(Cursor))
465      return Visit(E);
466
467    return false;
468  }
469
470  if (clang_isTranslationUnit(Cursor.kind)) {
471    CXTranslationUnit tu = getCursorTU(Cursor);
472    ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
473
474    int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
475    for (unsigned I = 0; I != 2; ++I) {
476      if (VisitOrder[I]) {
477        if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
478            RegionOfInterest.isInvalid()) {
479          for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
480                                        TLEnd = CXXUnit->top_level_end();
481               TL != TLEnd; ++TL) {
482            if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
483              return true;
484          }
485        } else if (VisitDeclContext(
486                                CXXUnit->getASTContext().getTranslationUnitDecl()))
487          return true;
488        continue;
489      }
490
491      // Walk the preprocessing record.
492      if (CXXUnit->getPreprocessor().getPreprocessingRecord())
493        visitPreprocessedEntitiesInRegion();
494    }
495
496    return false;
497  }
498
499  if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
500    if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
501      if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
502        return Visit(BaseTSInfo->getTypeLoc());
503      }
504    }
505  }
506
507  if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
508    IBOutletCollectionAttr *A =
509      cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
510    if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
511      return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
512                                                    A->getInterfaceLoc(), TU));
513  }
514
515  // Nothing to visit at the moment.
516  return false;
517}
518
519bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
520  if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
521    if (Visit(TSInfo->getTypeLoc()))
522        return true;
523
524  if (Stmt *Body = B->getBody())
525    return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
526
527  return false;
528}
529
530llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
531  if (RegionOfInterest.isValid()) {
532    SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
533    if (Range.isInvalid())
534      return llvm::Optional<bool>();
535
536    switch (CompareRegionOfInterest(Range)) {
537    case RangeBefore:
538      // This declaration comes before the region of interest; skip it.
539      return llvm::Optional<bool>();
540
541    case RangeAfter:
542      // This declaration comes after the region of interest; we're done.
543      return false;
544
545    case RangeOverlap:
546      // This declaration overlaps the region of interest; visit it.
547      break;
548    }
549  }
550  return true;
551}
552
553bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
554  DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
555
556  // FIXME: Eventually remove.  This part of a hack to support proper
557  // iteration over all Decls contained lexically within an ObjC container.
558  SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
559  SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
560
561  for ( ; I != E; ++I) {
562    Decl *D = *I;
563    if (D->getLexicalDeclContext() != DC)
564      continue;
565    CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
566
567    // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
568    // declarations is a mismatch with the compiler semantics.
569    if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
570      ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
571      if (!ID->isThisDeclarationADefinition())
572        Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
573
574    } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
575      ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
576      if (!PD->isThisDeclarationADefinition())
577        Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
578    }
579
580    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
581    if (!V.hasValue())
582      continue;
583    if (!V.getValue())
584      return false;
585    if (Visit(Cursor, true))
586      return true;
587  }
588  return false;
589}
590
591bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
592  llvm_unreachable("Translation units are visited directly by Visit()");
593}
594
595bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
596  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
597    return Visit(TSInfo->getTypeLoc());
598
599  return false;
600}
601
602bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
603  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
604    return Visit(TSInfo->getTypeLoc());
605
606  return false;
607}
608
609bool CursorVisitor::VisitTagDecl(TagDecl *D) {
610  return VisitDeclContext(D);
611}
612
613bool CursorVisitor::VisitClassTemplateSpecializationDecl(
614                                          ClassTemplateSpecializationDecl *D) {
615  bool ShouldVisitBody = false;
616  switch (D->getSpecializationKind()) {
617  case TSK_Undeclared:
618  case TSK_ImplicitInstantiation:
619    // Nothing to visit
620    return false;
621
622  case TSK_ExplicitInstantiationDeclaration:
623  case TSK_ExplicitInstantiationDefinition:
624    break;
625
626  case TSK_ExplicitSpecialization:
627    ShouldVisitBody = true;
628    break;
629  }
630
631  // Visit the template arguments used in the specialization.
632  if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
633    TypeLoc TL = SpecType->getTypeLoc();
634    if (TemplateSpecializationTypeLoc *TSTLoc
635          = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
636      for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
637        if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
638          return true;
639    }
640  }
641
642  if (ShouldVisitBody && VisitCXXRecordDecl(D))
643    return true;
644
645  return false;
646}
647
648bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
649                                   ClassTemplatePartialSpecializationDecl *D) {
650  // FIXME: Visit the "outer" template parameter lists on the TagDecl
651  // before visiting these template parameters.
652  if (VisitTemplateParameters(D->getTemplateParameters()))
653    return true;
654
655  // Visit the partial specialization arguments.
656  const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
657  for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
658    if (VisitTemplateArgumentLoc(TemplateArgs[I]))
659      return true;
660
661  return VisitCXXRecordDecl(D);
662}
663
664bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
665  // Visit the default argument.
666  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
667    if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
668      if (Visit(DefArg->getTypeLoc()))
669        return true;
670
671  return false;
672}
673
674bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
675  if (Expr *Init = D->getInitExpr())
676    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
677  return false;
678}
679
680bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
681  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
682    if (Visit(TSInfo->getTypeLoc()))
683      return true;
684
685  // Visit the nested-name-specifier, if present.
686  if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
687    if (VisitNestedNameSpecifierLoc(QualifierLoc))
688      return true;
689
690  return false;
691}
692
693/// \brief Compare two base or member initializers based on their source order.
694static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
695  CXXCtorInitializer const * const *X
696    = static_cast<CXXCtorInitializer const * const *>(Xp);
697  CXXCtorInitializer const * const *Y
698    = static_cast<CXXCtorInitializer const * const *>(Yp);
699
700  if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
701    return -1;
702  else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
703    return 1;
704  else
705    return 0;
706}
707
708bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
709  if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
710    // Visit the function declaration's syntactic components in the order
711    // written. This requires a bit of work.
712    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
713    FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
714
715    // If we have a function declared directly (without the use of a typedef),
716    // visit just the return type. Otherwise, just visit the function's type
717    // now.
718    if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
719        (!FTL && Visit(TL)))
720      return true;
721
722    // Visit the nested-name-specifier, if present.
723    if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
724      if (VisitNestedNameSpecifierLoc(QualifierLoc))
725        return true;
726
727    // Visit the declaration name.
728    if (VisitDeclarationNameInfo(ND->getNameInfo()))
729      return true;
730
731    // FIXME: Visit explicitly-specified template arguments!
732
733    // Visit the function parameters, if we have a function type.
734    if (FTL && VisitFunctionTypeLoc(*FTL, true))
735      return true;
736
737    // FIXME: Attributes?
738  }
739
740  if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
741    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
742      // Find the initializers that were written in the source.
743      SmallVector<CXXCtorInitializer *, 4> WrittenInits;
744      for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
745                                          IEnd = Constructor->init_end();
746           I != IEnd; ++I) {
747        if (!(*I)->isWritten())
748          continue;
749
750        WrittenInits.push_back(*I);
751      }
752
753      // Sort the initializers in source order
754      llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
755                           &CompareCXXCtorInitializers);
756
757      // Visit the initializers in source order
758      for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
759        CXXCtorInitializer *Init = WrittenInits[I];
760        if (Init->isAnyMemberInitializer()) {
761          if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
762                                        Init->getMemberLocation(), TU)))
763            return true;
764        } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
765          if (Visit(TInfo->getTypeLoc()))
766            return true;
767        }
768
769        // Visit the initializer value.
770        if (Expr *Initializer = Init->getInit())
771          if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
772            return true;
773      }
774    }
775
776    if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
777      return true;
778  }
779
780  return false;
781}
782
783bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
784  if (VisitDeclaratorDecl(D))
785    return true;
786
787  if (Expr *BitWidth = D->getBitWidth())
788    return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
789
790  return false;
791}
792
793bool CursorVisitor::VisitVarDecl(VarDecl *D) {
794  if (VisitDeclaratorDecl(D))
795    return true;
796
797  if (Expr *Init = D->getInit())
798    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
799
800  return false;
801}
802
803bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
804  if (VisitDeclaratorDecl(D))
805    return true;
806
807  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
808    if (Expr *DefArg = D->getDefaultArgument())
809      return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
810
811  return false;
812}
813
814bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
815  // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
816  // before visiting these template parameters.
817  if (VisitTemplateParameters(D->getTemplateParameters()))
818    return true;
819
820  return VisitFunctionDecl(D->getTemplatedDecl());
821}
822
823bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
824  // FIXME: Visit the "outer" template parameter lists on the TagDecl
825  // before visiting these template parameters.
826  if (VisitTemplateParameters(D->getTemplateParameters()))
827    return true;
828
829  return VisitCXXRecordDecl(D->getTemplatedDecl());
830}
831
832bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
833  if (VisitTemplateParameters(D->getTemplateParameters()))
834    return true;
835
836  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
837      VisitTemplateArgumentLoc(D->getDefaultArgument()))
838    return true;
839
840  return false;
841}
842
843bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
844  if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
845    if (Visit(TSInfo->getTypeLoc()))
846      return true;
847
848  for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
849       PEnd = ND->param_end();
850       P != PEnd; ++P) {
851    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
852      return true;
853  }
854
855  if (ND->isThisDeclarationADefinition() &&
856      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
857    return true;
858
859  return false;
860}
861
862template <typename DeclIt>
863static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
864                                      SourceManager &SM, SourceLocation EndLoc,
865                                      SmallVectorImpl<Decl *> &Decls) {
866  DeclIt next = *DI_current;
867  while (++next != DE_current) {
868    Decl *D_next = *next;
869    if (!D_next)
870      break;
871    SourceLocation L = D_next->getLocStart();
872    if (!L.isValid())
873      break;
874    if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
875      *DI_current = next;
876      Decls.push_back(D_next);
877      continue;
878    }
879    break;
880  }
881}
882
883namespace {
884  struct ContainerDeclsSort {
885    SourceManager &SM;
886    ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
887    bool operator()(Decl *A, Decl *B) {
888      SourceLocation L_A = A->getLocStart();
889      SourceLocation L_B = B->getLocStart();
890      assert(L_A.isValid() && L_B.isValid());
891      return SM.isBeforeInTranslationUnit(L_A, L_B);
892    }
893  };
894}
895
896bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
897  // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
898  // an @implementation can lexically contain Decls that are not properly
899  // nested in the AST.  When we identify such cases, we need to retrofit
900  // this nesting here.
901  if (!DI_current && !FileDI_current)
902    return VisitDeclContext(D);
903
904  // Scan the Decls that immediately come after the container
905  // in the current DeclContext.  If any fall within the
906  // container's lexical region, stash them into a vector
907  // for later processing.
908  SmallVector<Decl *, 24> DeclsInContainer;
909  SourceLocation EndLoc = D->getSourceRange().getEnd();
910  SourceManager &SM = AU->getSourceManager();
911  if (EndLoc.isValid()) {
912    if (DI_current) {
913      addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
914                                DeclsInContainer);
915    } else {
916      addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
917                                DeclsInContainer);
918    }
919  }
920
921  // The common case.
922  if (DeclsInContainer.empty())
923    return VisitDeclContext(D);
924
925  // Get all the Decls in the DeclContext, and sort them with the
926  // additional ones we've collected.  Then visit them.
927  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
928       I!=E; ++I) {
929    Decl *subDecl = *I;
930    if (!subDecl || subDecl->getLexicalDeclContext() != D ||
931        subDecl->getLocStart().isInvalid())
932      continue;
933    DeclsInContainer.push_back(subDecl);
934  }
935
936  // Now sort the Decls so that they appear in lexical order.
937  std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
938            ContainerDeclsSort(SM));
939
940  // Now visit the decls.
941  for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
942         E = DeclsInContainer.end(); I != E; ++I) {
943    CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
944    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
945    if (!V.hasValue())
946      continue;
947    if (!V.getValue())
948      return false;
949    if (Visit(Cursor, true))
950      return true;
951  }
952  return false;
953}
954
955bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
956  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
957                                   TU)))
958    return true;
959
960  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
961  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
962         E = ND->protocol_end(); I != E; ++I, ++PL)
963    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
964      return true;
965
966  return VisitObjCContainerDecl(ND);
967}
968
969bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
970  if (!PID->isThisDeclarationADefinition())
971    return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
972
973  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
974  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
975       E = PID->protocol_end(); I != E; ++I, ++PL)
976    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
977      return true;
978
979  return VisitObjCContainerDecl(PID);
980}
981
982bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
983  if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
984    return true;
985
986  // FIXME: This implements a workaround with @property declarations also being
987  // installed in the DeclContext for the @interface.  Eventually this code
988  // should be removed.
989  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
990  if (!CDecl || !CDecl->IsClassExtension())
991    return false;
992
993  ObjCInterfaceDecl *ID = CDecl->getClassInterface();
994  if (!ID)
995    return false;
996
997  IdentifierInfo *PropertyId = PD->getIdentifier();
998  ObjCPropertyDecl *prevDecl =
999    ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1000
1001  if (!prevDecl)
1002    return false;
1003
1004  // Visit synthesized methods since they will be skipped when visiting
1005  // the @interface.
1006  if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1007    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
1008      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1009        return true;
1010
1011  if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1012    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
1013      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1014        return true;
1015
1016  return false;
1017}
1018
1019bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1020  if (!D->isThisDeclarationADefinition()) {
1021    // Forward declaration is treated like a reference.
1022    return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1023  }
1024
1025  // Issue callbacks for super class.
1026  if (D->getSuperClass() &&
1027      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1028                                        D->getSuperClassLoc(),
1029                                        TU)))
1030    return true;
1031
1032  ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1033  for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1034         E = D->protocol_end(); I != E; ++I, ++PL)
1035    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1036      return true;
1037
1038  return VisitObjCContainerDecl(D);
1039}
1040
1041bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1042  return VisitObjCContainerDecl(D);
1043}
1044
1045bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1046  // 'ID' could be null when dealing with invalid code.
1047  if (ObjCInterfaceDecl *ID = D->getClassInterface())
1048    if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1049      return true;
1050
1051  return VisitObjCImplDecl(D);
1052}
1053
1054bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1055#if 0
1056  // Issue callbacks for super class.
1057  // FIXME: No source location information!
1058  if (D->getSuperClass() &&
1059      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1060                                        D->getSuperClassLoc(),
1061                                        TU)))
1062    return true;
1063#endif
1064
1065  return VisitObjCImplDecl(D);
1066}
1067
1068bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1069  if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1070    return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1071
1072  return false;
1073}
1074
1075bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1076  return VisitDeclContext(D);
1077}
1078
1079bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1080  // Visit nested-name-specifier.
1081  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1082    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1083      return true;
1084
1085  return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1086                                      D->getTargetNameLoc(), TU));
1087}
1088
1089bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1090  // Visit nested-name-specifier.
1091  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1092    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1093      return true;
1094  }
1095
1096  if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1097    return true;
1098
1099  return VisitDeclarationNameInfo(D->getNameInfo());
1100}
1101
1102bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1103  // Visit nested-name-specifier.
1104  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1105    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1106      return true;
1107
1108  return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1109                                      D->getIdentLocation(), TU));
1110}
1111
1112bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1113  // Visit nested-name-specifier.
1114  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1115    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1116      return true;
1117  }
1118
1119  return VisitDeclarationNameInfo(D->getNameInfo());
1120}
1121
1122bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1123                                               UnresolvedUsingTypenameDecl *D) {
1124  // Visit nested-name-specifier.
1125  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1126    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1127      return true;
1128
1129  return false;
1130}
1131
1132bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1133  switch (Name.getName().getNameKind()) {
1134  case clang::DeclarationName::Identifier:
1135  case clang::DeclarationName::CXXLiteralOperatorName:
1136  case clang::DeclarationName::CXXOperatorName:
1137  case clang::DeclarationName::CXXUsingDirective:
1138    return false;
1139
1140  case clang::DeclarationName::CXXConstructorName:
1141  case clang::DeclarationName::CXXDestructorName:
1142  case clang::DeclarationName::CXXConversionFunctionName:
1143    if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1144      return Visit(TSInfo->getTypeLoc());
1145    return false;
1146
1147  case clang::DeclarationName::ObjCZeroArgSelector:
1148  case clang::DeclarationName::ObjCOneArgSelector:
1149  case clang::DeclarationName::ObjCMultiArgSelector:
1150    // FIXME: Per-identifier location info?
1151    return false;
1152  }
1153
1154  llvm_unreachable("Invalid DeclarationName::Kind!");
1155}
1156
1157bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1158                                             SourceRange Range) {
1159  // FIXME: This whole routine is a hack to work around the lack of proper
1160  // source information in nested-name-specifiers (PR5791). Since we do have
1161  // a beginning source location, we can visit the first component of the
1162  // nested-name-specifier, if it's a single-token component.
1163  if (!NNS)
1164    return false;
1165
1166  // Get the first component in the nested-name-specifier.
1167  while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1168    NNS = Prefix;
1169
1170  switch (NNS->getKind()) {
1171  case NestedNameSpecifier::Namespace:
1172    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1173                                        TU));
1174
1175  case NestedNameSpecifier::NamespaceAlias:
1176    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1177                                        Range.getBegin(), TU));
1178
1179  case NestedNameSpecifier::TypeSpec: {
1180    // If the type has a form where we know that the beginning of the source
1181    // range matches up with a reference cursor. Visit the appropriate reference
1182    // cursor.
1183    const Type *T = NNS->getAsType();
1184    if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1185      return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1186    if (const TagType *Tag = dyn_cast<TagType>(T))
1187      return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1188    if (const TemplateSpecializationType *TST
1189                                      = dyn_cast<TemplateSpecializationType>(T))
1190      return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1191    break;
1192  }
1193
1194  case NestedNameSpecifier::TypeSpecWithTemplate:
1195  case NestedNameSpecifier::Global:
1196  case NestedNameSpecifier::Identifier:
1197    break;
1198  }
1199
1200  return false;
1201}
1202
1203bool
1204CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1205  SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1206  for (; Qualifier; Qualifier = Qualifier.getPrefix())
1207    Qualifiers.push_back(Qualifier);
1208
1209  while (!Qualifiers.empty()) {
1210    NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1211    NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1212    switch (NNS->getKind()) {
1213    case NestedNameSpecifier::Namespace:
1214      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1215                                       Q.getLocalBeginLoc(),
1216                                       TU)))
1217        return true;
1218
1219      break;
1220
1221    case NestedNameSpecifier::NamespaceAlias:
1222      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1223                                       Q.getLocalBeginLoc(),
1224                                       TU)))
1225        return true;
1226
1227      break;
1228
1229    case NestedNameSpecifier::TypeSpec:
1230    case NestedNameSpecifier::TypeSpecWithTemplate:
1231      if (Visit(Q.getTypeLoc()))
1232        return true;
1233
1234      break;
1235
1236    case NestedNameSpecifier::Global:
1237    case NestedNameSpecifier::Identifier:
1238      break;
1239    }
1240  }
1241
1242  return false;
1243}
1244
1245bool CursorVisitor::VisitTemplateParameters(
1246                                          const TemplateParameterList *Params) {
1247  if (!Params)
1248    return false;
1249
1250  for (TemplateParameterList::const_iterator P = Params->begin(),
1251                                          PEnd = Params->end();
1252       P != PEnd; ++P) {
1253    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1254      return true;
1255  }
1256
1257  return false;
1258}
1259
1260bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1261  switch (Name.getKind()) {
1262  case TemplateName::Template:
1263    return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1264
1265  case TemplateName::OverloadedTemplate:
1266    // Visit the overloaded template set.
1267    if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1268      return true;
1269
1270    return false;
1271
1272  case TemplateName::DependentTemplate:
1273    // FIXME: Visit nested-name-specifier.
1274    return false;
1275
1276  case TemplateName::QualifiedTemplate:
1277    // FIXME: Visit nested-name-specifier.
1278    return Visit(MakeCursorTemplateRef(
1279                                  Name.getAsQualifiedTemplateName()->getDecl(),
1280                                       Loc, TU));
1281
1282  case TemplateName::SubstTemplateTemplateParm:
1283    return Visit(MakeCursorTemplateRef(
1284                         Name.getAsSubstTemplateTemplateParm()->getParameter(),
1285                                       Loc, TU));
1286
1287  case TemplateName::SubstTemplateTemplateParmPack:
1288    return Visit(MakeCursorTemplateRef(
1289                  Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1290                                       Loc, TU));
1291  }
1292
1293  llvm_unreachable("Invalid TemplateName::Kind!");
1294}
1295
1296bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1297  switch (TAL.getArgument().getKind()) {
1298  case TemplateArgument::Null:
1299  case TemplateArgument::Integral:
1300  case TemplateArgument::Pack:
1301    return false;
1302
1303  case TemplateArgument::Type:
1304    if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1305      return Visit(TSInfo->getTypeLoc());
1306    return false;
1307
1308  case TemplateArgument::Declaration:
1309    if (Expr *E = TAL.getSourceDeclExpression())
1310      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1311    return false;
1312
1313  case TemplateArgument::Expression:
1314    if (Expr *E = TAL.getSourceExpression())
1315      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1316    return false;
1317
1318  case TemplateArgument::Template:
1319  case TemplateArgument::TemplateExpansion:
1320    if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1321      return true;
1322
1323    return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1324                             TAL.getTemplateNameLoc());
1325  }
1326
1327  llvm_unreachable("Invalid TemplateArgument::Kind!");
1328}
1329
1330bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1331  return VisitDeclContext(D);
1332}
1333
1334bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1335  return Visit(TL.getUnqualifiedLoc());
1336}
1337
1338bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1339  ASTContext &Context = AU->getASTContext();
1340
1341  // Some builtin types (such as Objective-C's "id", "sel", and
1342  // "Class") have associated declarations. Create cursors for those.
1343  QualType VisitType;
1344  switch (TL.getTypePtr()->getKind()) {
1345
1346  case BuiltinType::Void:
1347  case BuiltinType::NullPtr:
1348  case BuiltinType::Dependent:
1349#define BUILTIN_TYPE(Id, SingletonId)
1350#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1351#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1352#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1353#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1354#include "clang/AST/BuiltinTypes.def"
1355    break;
1356
1357  case BuiltinType::ObjCId:
1358    VisitType = Context.getObjCIdType();
1359    break;
1360
1361  case BuiltinType::ObjCClass:
1362    VisitType = Context.getObjCClassType();
1363    break;
1364
1365  case BuiltinType::ObjCSel:
1366    VisitType = Context.getObjCSelType();
1367    break;
1368  }
1369
1370  if (!VisitType.isNull()) {
1371    if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1372      return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1373                                     TU));
1374  }
1375
1376  return false;
1377}
1378
1379bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1380  return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1381}
1382
1383bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1384  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1385}
1386
1387bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1388  if (TL.isDefinition())
1389    return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1390
1391  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1392}
1393
1394bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1395  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1396}
1397
1398bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1399  if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1400    return true;
1401
1402  return false;
1403}
1404
1405bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1406  if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1407    return true;
1408
1409  for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1410    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1411                                        TU)))
1412      return true;
1413  }
1414
1415  return false;
1416}
1417
1418bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1419  return Visit(TL.getPointeeLoc());
1420}
1421
1422bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1423  return Visit(TL.getInnerLoc());
1424}
1425
1426bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1427  return Visit(TL.getPointeeLoc());
1428}
1429
1430bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1431  return Visit(TL.getPointeeLoc());
1432}
1433
1434bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1435  return Visit(TL.getPointeeLoc());
1436}
1437
1438bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1439  return Visit(TL.getPointeeLoc());
1440}
1441
1442bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1443  return Visit(TL.getPointeeLoc());
1444}
1445
1446bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1447  return Visit(TL.getModifiedLoc());
1448}
1449
1450bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1451                                         bool SkipResultType) {
1452  if (!SkipResultType && Visit(TL.getResultLoc()))
1453    return true;
1454
1455  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1456    if (Decl *D = TL.getArg(I))
1457      if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1458        return true;
1459
1460  return false;
1461}
1462
1463bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1464  if (Visit(TL.getElementLoc()))
1465    return true;
1466
1467  if (Expr *Size = TL.getSizeExpr())
1468    return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1469
1470  return false;
1471}
1472
1473bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1474                                             TemplateSpecializationTypeLoc TL) {
1475  // Visit the template name.
1476  if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1477                        TL.getTemplateNameLoc()))
1478    return true;
1479
1480  // Visit the template arguments.
1481  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1482    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1483      return true;
1484
1485  return false;
1486}
1487
1488bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1489  return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1490}
1491
1492bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1493  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1494    return Visit(TSInfo->getTypeLoc());
1495
1496  return false;
1497}
1498
1499bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1500  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1501    return Visit(TSInfo->getTypeLoc());
1502
1503  return false;
1504}
1505
1506bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1507  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1508    return true;
1509
1510  return false;
1511}
1512
1513bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1514                                    DependentTemplateSpecializationTypeLoc TL) {
1515  // Visit the nested-name-specifier, if there is one.
1516  if (TL.getQualifierLoc() &&
1517      VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1518    return true;
1519
1520  // Visit the template arguments.
1521  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1522    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1523      return true;
1524
1525  return false;
1526}
1527
1528bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1529  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1530    return true;
1531
1532  return Visit(TL.getNamedTypeLoc());
1533}
1534
1535bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1536  return Visit(TL.getPatternLoc());
1537}
1538
1539bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1540  if (Expr *E = TL.getUnderlyingExpr())
1541    return Visit(MakeCXCursor(E, StmtParent, TU));
1542
1543  return false;
1544}
1545
1546bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1547  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1548}
1549
1550bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1551  return Visit(TL.getValueLoc());
1552}
1553
1554#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1555bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1556  return Visit##PARENT##Loc(TL); \
1557}
1558
1559DEFAULT_TYPELOC_IMPL(Complex, Type)
1560DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1561DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1562DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1563DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1564DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1565DEFAULT_TYPELOC_IMPL(Vector, Type)
1566DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1567DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1568DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1569DEFAULT_TYPELOC_IMPL(Record, TagType)
1570DEFAULT_TYPELOC_IMPL(Enum, TagType)
1571DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1572DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1573DEFAULT_TYPELOC_IMPL(Auto, Type)
1574
1575bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1576  // Visit the nested-name-specifier, if present.
1577  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1578    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1579      return true;
1580
1581  if (D->isCompleteDefinition()) {
1582    for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1583         E = D->bases_end(); I != E; ++I) {
1584      if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1585        return true;
1586    }
1587  }
1588
1589  return VisitTagDecl(D);
1590}
1591
1592bool CursorVisitor::VisitAttributes(Decl *D) {
1593  for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1594       i != e; ++i)
1595    if (Visit(MakeCXCursor(*i, D, TU)))
1596        return true;
1597
1598  return false;
1599}
1600
1601//===----------------------------------------------------------------------===//
1602// Data-recursive visitor methods.
1603//===----------------------------------------------------------------------===//
1604
1605namespace {
1606#define DEF_JOB(NAME, DATA, KIND)\
1607class NAME : public VisitorJob {\
1608public:\
1609  NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1610  static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1611  DATA *get() const { return static_cast<DATA*>(data[0]); }\
1612};
1613
1614DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1615DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1616DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1617DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1618DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
1619        ExplicitTemplateArgsVisitKind)
1620DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1621DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1622#undef DEF_JOB
1623
1624class DeclVisit : public VisitorJob {
1625public:
1626  DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1627    VisitorJob(parent, VisitorJob::DeclVisitKind,
1628               d, isFirst ? (void*) 1 : (void*) 0) {}
1629  static bool classof(const VisitorJob *VJ) {
1630    return VJ->getKind() == DeclVisitKind;
1631  }
1632  Decl *get() const { return static_cast<Decl*>(data[0]); }
1633  bool isFirst() const { return data[1] ? true : false; }
1634};
1635class TypeLocVisit : public VisitorJob {
1636public:
1637  TypeLocVisit(TypeLoc tl, CXCursor parent) :
1638    VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1639               tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1640
1641  static bool classof(const VisitorJob *VJ) {
1642    return VJ->getKind() == TypeLocVisitKind;
1643  }
1644
1645  TypeLoc get() const {
1646    QualType T = QualType::getFromOpaquePtr(data[0]);
1647    return TypeLoc(T, data[1]);
1648  }
1649};
1650
1651class LabelRefVisit : public VisitorJob {
1652public:
1653  LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1654    : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1655                 labelLoc.getPtrEncoding()) {}
1656
1657  static bool classof(const VisitorJob *VJ) {
1658    return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1659  }
1660  LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
1661  SourceLocation getLoc() const {
1662    return SourceLocation::getFromPtrEncoding(data[1]); }
1663};
1664
1665class NestedNameSpecifierLocVisit : public VisitorJob {
1666public:
1667  NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1668    : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1669                 Qualifier.getNestedNameSpecifier(),
1670                 Qualifier.getOpaqueData()) { }
1671
1672  static bool classof(const VisitorJob *VJ) {
1673    return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1674  }
1675
1676  NestedNameSpecifierLoc get() const {
1677    return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1678                                  data[1]);
1679  }
1680};
1681
1682class DeclarationNameInfoVisit : public VisitorJob {
1683public:
1684  DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1685    : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1686  static bool classof(const VisitorJob *VJ) {
1687    return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1688  }
1689  DeclarationNameInfo get() const {
1690    Stmt *S = static_cast<Stmt*>(data[0]);
1691    switch (S->getStmtClass()) {
1692    default:
1693      llvm_unreachable("Unhandled Stmt");
1694    case clang::Stmt::MSDependentExistsStmtClass:
1695      return cast<MSDependentExistsStmt>(S)->getNameInfo();
1696    case Stmt::CXXDependentScopeMemberExprClass:
1697      return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1698    case Stmt::DependentScopeDeclRefExprClass:
1699      return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1700    }
1701  }
1702};
1703class MemberRefVisit : public VisitorJob {
1704public:
1705  MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1706    : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1707                 L.getPtrEncoding()) {}
1708  static bool classof(const VisitorJob *VJ) {
1709    return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1710  }
1711  FieldDecl *get() const {
1712    return static_cast<FieldDecl*>(data[0]);
1713  }
1714  SourceLocation getLoc() const {
1715    return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1716  }
1717};
1718class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1719  VisitorWorkList &WL;
1720  CXCursor Parent;
1721public:
1722  EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1723    : WL(wl), Parent(parent) {}
1724
1725  void VisitAddrLabelExpr(AddrLabelExpr *E);
1726  void VisitBlockExpr(BlockExpr *B);
1727  void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1728  void VisitCompoundStmt(CompoundStmt *S);
1729  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1730  void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
1731  void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
1732  void VisitCXXNewExpr(CXXNewExpr *E);
1733  void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1734  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1735  void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
1736  void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
1737  void VisitCXXTypeidExpr(CXXTypeidExpr *E);
1738  void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
1739  void VisitCXXUuidofExpr(CXXUuidofExpr *E);
1740  void VisitCXXCatchStmt(CXXCatchStmt *S);
1741  void VisitDeclRefExpr(DeclRefExpr *D);
1742  void VisitDeclStmt(DeclStmt *S);
1743  void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
1744  void VisitDesignatedInitExpr(DesignatedInitExpr *E);
1745  void VisitExplicitCastExpr(ExplicitCastExpr *E);
1746  void VisitForStmt(ForStmt *FS);
1747  void VisitGotoStmt(GotoStmt *GS);
1748  void VisitIfStmt(IfStmt *If);
1749  void VisitInitListExpr(InitListExpr *IE);
1750  void VisitMemberExpr(MemberExpr *M);
1751  void VisitOffsetOfExpr(OffsetOfExpr *E);
1752  void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
1753  void VisitObjCMessageExpr(ObjCMessageExpr *M);
1754  void VisitOverloadExpr(OverloadExpr *E);
1755  void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
1756  void VisitStmt(Stmt *S);
1757  void VisitSwitchStmt(SwitchStmt *S);
1758  void VisitWhileStmt(WhileStmt *W);
1759  void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
1760  void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
1761  void VisitTypeTraitExpr(TypeTraitExpr *E);
1762  void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
1763  void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
1764  void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1765  void VisitVAArgExpr(VAArgExpr *E);
1766  void VisitSizeOfPackExpr(SizeOfPackExpr *E);
1767  void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1768  void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1769  void VisitLambdaExpr(LambdaExpr *E);
1770
1771private:
1772  void AddDeclarationNameInfo(Stmt *S);
1773  void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1774  void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1775  void AddMemberRef(FieldDecl *D, SourceLocation L);
1776  void AddStmt(Stmt *S);
1777  void AddDecl(Decl *D, bool isFirst = true);
1778  void AddTypeLoc(TypeSourceInfo *TI);
1779  void EnqueueChildren(Stmt *S);
1780};
1781} // end anonyous namespace
1782
1783void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1784  // 'S' should always be non-null, since it comes from the
1785  // statement we are visiting.
1786  WL.push_back(DeclarationNameInfoVisit(S, Parent));
1787}
1788
1789void
1790EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1791  if (Qualifier)
1792    WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1793}
1794
1795void EnqueueVisitor::AddStmt(Stmt *S) {
1796  if (S)
1797    WL.push_back(StmtVisit(S, Parent));
1798}
1799void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
1800  if (D)
1801    WL.push_back(DeclVisit(D, Parent, isFirst));
1802}
1803void EnqueueVisitor::
1804  AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1805  if (A)
1806    WL.push_back(ExplicitTemplateArgsVisit(
1807                        const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
1808}
1809void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1810  if (D)
1811    WL.push_back(MemberRefVisit(D, L, Parent));
1812}
1813void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1814  if (TI)
1815    WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1816 }
1817void EnqueueVisitor::EnqueueChildren(Stmt *S) {
1818  unsigned size = WL.size();
1819  for (Stmt::child_range Child = S->children(); Child; ++Child) {
1820    AddStmt(*Child);
1821  }
1822  if (size == WL.size())
1823    return;
1824  // Now reverse the entries we just added.  This will match the DFS
1825  // ordering performed by the worklist.
1826  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1827  std::reverse(I, E);
1828}
1829void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1830  WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1831}
1832void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1833  AddDecl(B->getBlockDecl());
1834}
1835void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1836  EnqueueChildren(E);
1837  AddTypeLoc(E->getTypeSourceInfo());
1838}
1839void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1840  for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1841        E = S->body_rend(); I != E; ++I) {
1842    AddStmt(*I);
1843  }
1844}
1845void EnqueueVisitor::
1846VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1847  AddStmt(S->getSubStmt());
1848  AddDeclarationNameInfo(S);
1849  if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1850    AddNestedNameSpecifierLoc(QualifierLoc);
1851}
1852
1853void EnqueueVisitor::
1854VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1855  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1856  AddDeclarationNameInfo(E);
1857  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1858    AddNestedNameSpecifierLoc(QualifierLoc);
1859  if (!E->isImplicitAccess())
1860    AddStmt(E->getBase());
1861}
1862void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1863  // Enqueue the initializer , if any.
1864  AddStmt(E->getInitializer());
1865  // Enqueue the array size, if any.
1866  AddStmt(E->getArraySize());
1867  // Enqueue the allocated type.
1868  AddTypeLoc(E->getAllocatedTypeSourceInfo());
1869  // Enqueue the placement arguments.
1870  for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1871    AddStmt(E->getPlacementArg(I-1));
1872}
1873void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1874  for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1875    AddStmt(CE->getArg(I-1));
1876  AddStmt(CE->getCallee());
1877  AddStmt(CE->getArg(0));
1878}
1879void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1880  // Visit the name of the type being destroyed.
1881  AddTypeLoc(E->getDestroyedTypeInfo());
1882  // Visit the scope type that looks disturbingly like the nested-name-specifier
1883  // but isn't.
1884  AddTypeLoc(E->getScopeTypeInfo());
1885  // Visit the nested-name-specifier.
1886  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1887    AddNestedNameSpecifierLoc(QualifierLoc);
1888  // Visit base expression.
1889  AddStmt(E->getBase());
1890}
1891void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1892  AddTypeLoc(E->getTypeSourceInfo());
1893}
1894void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1895  EnqueueChildren(E);
1896  AddTypeLoc(E->getTypeSourceInfo());
1897}
1898void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1899  EnqueueChildren(E);
1900  if (E->isTypeOperand())
1901    AddTypeLoc(E->getTypeOperandSourceInfo());
1902}
1903
1904void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1905                                                     *E) {
1906  EnqueueChildren(E);
1907  AddTypeLoc(E->getTypeSourceInfo());
1908}
1909void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1910  EnqueueChildren(E);
1911  if (E->isTypeOperand())
1912    AddTypeLoc(E->getTypeOperandSourceInfo());
1913}
1914
1915void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1916  EnqueueChildren(S);
1917  AddDecl(S->getExceptionDecl());
1918}
1919
1920void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1921  if (DR->hasExplicitTemplateArgs()) {
1922    AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1923  }
1924  WL.push_back(DeclRefExprParts(DR, Parent));
1925}
1926void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1927  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1928  AddDeclarationNameInfo(E);
1929  AddNestedNameSpecifierLoc(E->getQualifierLoc());
1930}
1931void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1932  unsigned size = WL.size();
1933  bool isFirst = true;
1934  for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1935       D != DEnd; ++D) {
1936    AddDecl(*D, isFirst);
1937    isFirst = false;
1938  }
1939  if (size == WL.size())
1940    return;
1941  // Now reverse the entries we just added.  This will match the DFS
1942  // ordering performed by the worklist.
1943  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1944  std::reverse(I, E);
1945}
1946void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1947  AddStmt(E->getInit());
1948  typedef DesignatedInitExpr::Designator Designator;
1949  for (DesignatedInitExpr::reverse_designators_iterator
1950         D = E->designators_rbegin(), DEnd = E->designators_rend();
1951         D != DEnd; ++D) {
1952    if (D->isFieldDesignator()) {
1953      if (FieldDecl *Field = D->getField())
1954        AddMemberRef(Field, D->getFieldLoc());
1955      continue;
1956    }
1957    if (D->isArrayDesignator()) {
1958      AddStmt(E->getArrayIndex(*D));
1959      continue;
1960    }
1961    assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1962    AddStmt(E->getArrayRangeEnd(*D));
1963    AddStmt(E->getArrayRangeStart(*D));
1964  }
1965}
1966void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1967  EnqueueChildren(E);
1968  AddTypeLoc(E->getTypeInfoAsWritten());
1969}
1970void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1971  AddStmt(FS->getBody());
1972  AddStmt(FS->getInc());
1973  AddStmt(FS->getCond());
1974  AddDecl(FS->getConditionVariable());
1975  AddStmt(FS->getInit());
1976}
1977void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1978  WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1979}
1980void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1981  AddStmt(If->getElse());
1982  AddStmt(If->getThen());
1983  AddStmt(If->getCond());
1984  AddDecl(If->getConditionVariable());
1985}
1986void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1987  // We care about the syntactic form of the initializer list, only.
1988  if (InitListExpr *Syntactic = IE->getSyntacticForm())
1989    IE = Syntactic;
1990  EnqueueChildren(IE);
1991}
1992void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1993  WL.push_back(MemberExprParts(M, Parent));
1994
1995  // If the base of the member access expression is an implicit 'this', don't
1996  // visit it.
1997  // FIXME: If we ever want to show these implicit accesses, this will be
1998  // unfortunate. However, clang_getCursor() relies on this behavior.
1999  if (!M->isImplicitAccess())
2000    AddStmt(M->getBase());
2001}
2002void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2003  AddTypeLoc(E->getEncodedTypeSourceInfo());
2004}
2005void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2006  EnqueueChildren(M);
2007  AddTypeLoc(M->getClassReceiverTypeInfo());
2008}
2009void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2010  // Visit the components of the offsetof expression.
2011  for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2012    typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2013    const OffsetOfNode &Node = E->getComponent(I-1);
2014    switch (Node.getKind()) {
2015    case OffsetOfNode::Array:
2016      AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2017      break;
2018    case OffsetOfNode::Field:
2019      AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2020      break;
2021    case OffsetOfNode::Identifier:
2022    case OffsetOfNode::Base:
2023      continue;
2024    }
2025  }
2026  // Visit the type into which we're computing the offset.
2027  AddTypeLoc(E->getTypeSourceInfo());
2028}
2029void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
2030  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2031  WL.push_back(OverloadExprParts(E, Parent));
2032}
2033void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2034                                              UnaryExprOrTypeTraitExpr *E) {
2035  EnqueueChildren(E);
2036  if (E->isArgumentType())
2037    AddTypeLoc(E->getArgumentTypeInfo());
2038}
2039void EnqueueVisitor::VisitStmt(Stmt *S) {
2040  EnqueueChildren(S);
2041}
2042void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2043  AddStmt(S->getBody());
2044  AddStmt(S->getCond());
2045  AddDecl(S->getConditionVariable());
2046}
2047
2048void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2049  AddStmt(W->getBody());
2050  AddStmt(W->getCond());
2051  AddDecl(W->getConditionVariable());
2052}
2053
2054void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2055  AddTypeLoc(E->getQueriedTypeSourceInfo());
2056}
2057
2058void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
2059  AddTypeLoc(E->getRhsTypeSourceInfo());
2060  AddTypeLoc(E->getLhsTypeSourceInfo());
2061}
2062
2063void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2064  for (unsigned I = E->getNumArgs(); I > 0; --I)
2065    AddTypeLoc(E->getArg(I-1));
2066}
2067
2068void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2069  AddTypeLoc(E->getQueriedTypeSourceInfo());
2070}
2071
2072void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2073  EnqueueChildren(E);
2074}
2075
2076void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2077  VisitOverloadExpr(U);
2078  if (!U->isImplicitAccess())
2079    AddStmt(U->getBase());
2080}
2081void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2082  AddStmt(E->getSubExpr());
2083  AddTypeLoc(E->getWrittenTypeInfo());
2084}
2085void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2086  WL.push_back(SizeOfPackExprParts(E, Parent));
2087}
2088void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2089  // If the opaque value has a source expression, just transparently
2090  // visit that.  This is useful for (e.g.) pseudo-object expressions.
2091  if (Expr *SourceExpr = E->getSourceExpr())
2092    return Visit(SourceExpr);
2093}
2094void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2095  AddStmt(E->getBody());
2096  WL.push_back(LambdaExprParts(E, Parent));
2097}
2098void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2099  // Treat the expression like its syntactic form.
2100  Visit(E->getSyntacticForm());
2101}
2102
2103void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
2104  EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2105}
2106
2107bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2108  if (RegionOfInterest.isValid()) {
2109    SourceRange Range = getRawCursorExtent(C);
2110    if (Range.isInvalid() || CompareRegionOfInterest(Range))
2111      return false;
2112  }
2113  return true;
2114}
2115
2116bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2117  while (!WL.empty()) {
2118    // Dequeue the worklist item.
2119    VisitorJob LI = WL.back();
2120    WL.pop_back();
2121
2122    // Set the Parent field, then back to its old value once we're done.
2123    SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2124
2125    switch (LI.getKind()) {
2126      case VisitorJob::DeclVisitKind: {
2127        Decl *D = cast<DeclVisit>(&LI)->get();
2128        if (!D)
2129          continue;
2130
2131        // For now, perform default visitation for Decls.
2132        if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2133                               cast<DeclVisit>(&LI)->isFirst())))
2134            return true;
2135
2136        continue;
2137      }
2138      case VisitorJob::ExplicitTemplateArgsVisitKind: {
2139        const ASTTemplateArgumentListInfo *ArgList =
2140          cast<ExplicitTemplateArgsVisit>(&LI)->get();
2141        for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2142               *ArgEnd = Arg + ArgList->NumTemplateArgs;
2143               Arg != ArgEnd; ++Arg) {
2144          if (VisitTemplateArgumentLoc(*Arg))
2145            return true;
2146        }
2147        continue;
2148      }
2149      case VisitorJob::TypeLocVisitKind: {
2150        // Perform default visitation for TypeLocs.
2151        if (Visit(cast<TypeLocVisit>(&LI)->get()))
2152          return true;
2153        continue;
2154      }
2155      case VisitorJob::LabelRefVisitKind: {
2156        LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2157        if (LabelStmt *stmt = LS->getStmt()) {
2158          if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2159                                       TU))) {
2160            return true;
2161          }
2162        }
2163        continue;
2164      }
2165
2166      case VisitorJob::NestedNameSpecifierLocVisitKind: {
2167        NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2168        if (VisitNestedNameSpecifierLoc(V->get()))
2169          return true;
2170        continue;
2171      }
2172
2173      case VisitorJob::DeclarationNameInfoVisitKind: {
2174        if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2175                                     ->get()))
2176          return true;
2177        continue;
2178      }
2179      case VisitorJob::MemberRefVisitKind: {
2180        MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2181        if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2182          return true;
2183        continue;
2184      }
2185      case VisitorJob::StmtVisitKind: {
2186        Stmt *S = cast<StmtVisit>(&LI)->get();
2187        if (!S)
2188          continue;
2189
2190        // Update the current cursor.
2191        CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2192        if (!IsInRegionOfInterest(Cursor))
2193          continue;
2194        switch (Visitor(Cursor, Parent, ClientData)) {
2195          case CXChildVisit_Break: return true;
2196          case CXChildVisit_Continue: break;
2197          case CXChildVisit_Recurse:
2198            EnqueueWorkList(WL, S);
2199            break;
2200        }
2201        continue;
2202      }
2203      case VisitorJob::MemberExprPartsKind: {
2204        // Handle the other pieces in the MemberExpr besides the base.
2205        MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2206
2207        // Visit the nested-name-specifier
2208        if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2209          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2210            return true;
2211
2212        // Visit the declaration name.
2213        if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2214          return true;
2215
2216        // Visit the explicitly-specified template arguments, if any.
2217        if (M->hasExplicitTemplateArgs()) {
2218          for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2219               *ArgEnd = Arg + M->getNumTemplateArgs();
2220               Arg != ArgEnd; ++Arg) {
2221            if (VisitTemplateArgumentLoc(*Arg))
2222              return true;
2223          }
2224        }
2225        continue;
2226      }
2227      case VisitorJob::DeclRefExprPartsKind: {
2228        DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2229        // Visit nested-name-specifier, if present.
2230        if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2231          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2232            return true;
2233        // Visit declaration name.
2234        if (VisitDeclarationNameInfo(DR->getNameInfo()))
2235          return true;
2236        continue;
2237      }
2238      case VisitorJob::OverloadExprPartsKind: {
2239        OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2240        // Visit the nested-name-specifier.
2241        if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2242          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2243            return true;
2244        // Visit the declaration name.
2245        if (VisitDeclarationNameInfo(O->getNameInfo()))
2246          return true;
2247        // Visit the overloaded declaration reference.
2248        if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2249          return true;
2250        continue;
2251      }
2252      case VisitorJob::SizeOfPackExprPartsKind: {
2253        SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2254        NamedDecl *Pack = E->getPack();
2255        if (isa<TemplateTypeParmDecl>(Pack)) {
2256          if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2257                                      E->getPackLoc(), TU)))
2258            return true;
2259
2260          continue;
2261        }
2262
2263        if (isa<TemplateTemplateParmDecl>(Pack)) {
2264          if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2265                                          E->getPackLoc(), TU)))
2266            return true;
2267
2268          continue;
2269        }
2270
2271        // Non-type template parameter packs and function parameter packs are
2272        // treated like DeclRefExpr cursors.
2273        continue;
2274      }
2275
2276      case VisitorJob::LambdaExprPartsKind: {
2277        // Visit captures.
2278        LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2279        for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2280                                       CEnd = E->explicit_capture_end();
2281             C != CEnd; ++C) {
2282          if (C->capturesThis())
2283            continue;
2284
2285          if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2286                                          C->getLocation(),
2287                                          TU)))
2288            return true;
2289        }
2290
2291        // Visit parameters and return type, if present.
2292        if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2293          TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2294          if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2295            // Visit the whole type.
2296            if (Visit(TL))
2297              return true;
2298          } else if (isa<FunctionProtoTypeLoc>(TL)) {
2299            FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2300            if (E->hasExplicitParameters()) {
2301              // Visit parameters.
2302              for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2303                if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2304                  return true;
2305            } else {
2306              // Visit result type.
2307              if (Visit(Proto.getResultLoc()))
2308                return true;
2309            }
2310          }
2311        }
2312        break;
2313      }
2314    }
2315  }
2316  return false;
2317}
2318
2319bool CursorVisitor::Visit(Stmt *S) {
2320  VisitorWorkList *WL = 0;
2321  if (!WorkListFreeList.empty()) {
2322    WL = WorkListFreeList.back();
2323    WL->clear();
2324    WorkListFreeList.pop_back();
2325  }
2326  else {
2327    WL = new VisitorWorkList();
2328    WorkListCache.push_back(WL);
2329  }
2330  EnqueueWorkList(*WL, S);
2331  bool result = RunVisitorWorkList(*WL);
2332  WorkListFreeList.push_back(WL);
2333  return result;
2334}
2335
2336namespace {
2337typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2338RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2339                          const DeclarationNameInfo &NI,
2340                          const SourceRange &QLoc,
2341                          const ASTTemplateArgumentListInfo *TemplateArgs = 0){
2342  const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2343  const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2344  const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2345
2346  const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2347
2348  RefNamePieces Pieces;
2349
2350  if (WantQualifier && QLoc.isValid())
2351    Pieces.push_back(QLoc);
2352
2353  if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2354    Pieces.push_back(NI.getLoc());
2355
2356  if (WantTemplateArgs && TemplateArgs)
2357    Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2358                                 TemplateArgs->RAngleLoc));
2359
2360  if (Kind == DeclarationName::CXXOperatorName) {
2361    Pieces.push_back(SourceLocation::getFromRawEncoding(
2362                       NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2363    Pieces.push_back(SourceLocation::getFromRawEncoding(
2364                       NI.getInfo().CXXOperatorName.EndOpNameLoc));
2365  }
2366
2367  if (WantSinglePiece) {
2368    SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2369    Pieces.clear();
2370    Pieces.push_back(R);
2371  }
2372
2373  return Pieces;
2374}
2375}
2376
2377//===----------------------------------------------------------------------===//
2378// Misc. API hooks.
2379//===----------------------------------------------------------------------===//
2380
2381static llvm::sys::Mutex EnableMultithreadingMutex;
2382static bool EnabledMultithreading;
2383
2384static void fatal_error_handler(void *user_data, const std::string& reason) {
2385  // Write the result out to stderr avoiding errs() because raw_ostreams can
2386  // call report_fatal_error.
2387  fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2388  ::abort();
2389}
2390
2391extern "C" {
2392CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2393                          int displayDiagnostics) {
2394  // Disable pretty stack trace functionality, which will otherwise be a very
2395  // poor citizen of the world and set up all sorts of signal handlers.
2396  llvm::DisablePrettyStackTrace = true;
2397
2398  // We use crash recovery to make some of our APIs more reliable, implicitly
2399  // enable it.
2400  llvm::CrashRecoveryContext::Enable();
2401
2402  // Enable support for multithreading in LLVM.
2403  {
2404    llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2405    if (!EnabledMultithreading) {
2406      llvm::install_fatal_error_handler(fatal_error_handler, 0);
2407      llvm::llvm_start_multithreaded();
2408      EnabledMultithreading = true;
2409    }
2410  }
2411
2412  CIndexer *CIdxr = new CIndexer();
2413  if (excludeDeclarationsFromPCH)
2414    CIdxr->setOnlyLocalDecls();
2415  if (displayDiagnostics)
2416    CIdxr->setDisplayDiagnostics();
2417
2418  if (getenv("LIBCLANG_BGPRIO_INDEX"))
2419    CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2420                               CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2421  if (getenv("LIBCLANG_BGPRIO_EDIT"))
2422    CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2423                               CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2424
2425  return CIdxr;
2426}
2427
2428void clang_disposeIndex(CXIndex CIdx) {
2429  if (CIdx)
2430    delete static_cast<CIndexer *>(CIdx);
2431}
2432
2433void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2434  if (CIdx)
2435    static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2436}
2437
2438unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2439  if (CIdx)
2440    return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2441  return 0;
2442}
2443
2444void clang_toggleCrashRecovery(unsigned isEnabled) {
2445  if (isEnabled)
2446    llvm::CrashRecoveryContext::Enable();
2447  else
2448    llvm::CrashRecoveryContext::Disable();
2449}
2450
2451CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2452                                              const char *ast_filename) {
2453  if (!CIdx)
2454    return 0;
2455
2456  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2457  FileSystemOptions FileSystemOpts;
2458  FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
2459
2460  IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
2461  ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
2462                                  CXXIdx->getOnlyLocalDecls(),
2463                                  0, 0,
2464                                  /*CaptureDiagnostics=*/true,
2465                                  /*AllowPCHWithCompilerErrors=*/true);
2466  return MakeCXTranslationUnit(CXXIdx, TU);
2467}
2468
2469unsigned clang_defaultEditingTranslationUnitOptions() {
2470  return CXTranslationUnit_PrecompiledPreamble |
2471         CXTranslationUnit_CacheCompletionResults;
2472}
2473
2474CXTranslationUnit
2475clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2476                                          const char *source_filename,
2477                                          int num_command_line_args,
2478                                          const char * const *command_line_args,
2479                                          unsigned num_unsaved_files,
2480                                          struct CXUnsavedFile *unsaved_files) {
2481  unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
2482  return clang_parseTranslationUnit(CIdx, source_filename,
2483                                    command_line_args, num_command_line_args,
2484                                    unsaved_files, num_unsaved_files,
2485                                    Options);
2486}
2487
2488struct ParseTranslationUnitInfo {
2489  CXIndex CIdx;
2490  const char *source_filename;
2491  const char *const *command_line_args;
2492  int num_command_line_args;
2493  struct CXUnsavedFile *unsaved_files;
2494  unsigned num_unsaved_files;
2495  unsigned options;
2496  CXTranslationUnit result;
2497};
2498static void clang_parseTranslationUnit_Impl(void *UserData) {
2499  ParseTranslationUnitInfo *PTUI =
2500    static_cast<ParseTranslationUnitInfo*>(UserData);
2501  CXIndex CIdx = PTUI->CIdx;
2502  const char *source_filename = PTUI->source_filename;
2503  const char * const *command_line_args = PTUI->command_line_args;
2504  int num_command_line_args = PTUI->num_command_line_args;
2505  struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2506  unsigned num_unsaved_files = PTUI->num_unsaved_files;
2507  unsigned options = PTUI->options;
2508  PTUI->result = 0;
2509
2510  if (!CIdx)
2511    return;
2512
2513  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2514
2515  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
2516    setThreadBackgroundPriority();
2517
2518  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2519  // FIXME: Add a flag for modules.
2520  TranslationUnitKind TUKind
2521    = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
2522  bool CacheCodeCompetionResults
2523    = options & CXTranslationUnit_CacheCompletionResults;
2524  bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
2525
2526  // Configure the diagnostics.
2527  DiagnosticOptions DiagOpts;
2528  IntrusiveRefCntPtr<DiagnosticsEngine>
2529    Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2530                                                command_line_args));
2531
2532  // Recover resources if we crash before exiting this function.
2533  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2534    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
2535    DiagCleanup(Diags.getPtr());
2536
2537  OwningPtr<std::vector<ASTUnit::RemappedFile> >
2538    RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2539
2540  // Recover resources if we crash before exiting this function.
2541  llvm::CrashRecoveryContextCleanupRegistrar<
2542    std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2543
2544  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2545    StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2546    const llvm::MemoryBuffer *Buffer
2547      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2548    RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2549                                            Buffer));
2550  }
2551
2552  OwningPtr<std::vector<const char *> >
2553    Args(new std::vector<const char*>());
2554
2555  // Recover resources if we crash before exiting this method.
2556  llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2557    ArgsCleanup(Args.get());
2558
2559  // Since the Clang C library is primarily used by batch tools dealing with
2560  // (often very broken) source code, where spell-checking can have a
2561  // significant negative impact on performance (particularly when
2562  // precompiled headers are involved), we disable it by default.
2563  // Only do this if we haven't found a spell-checking-related argument.
2564  bool FoundSpellCheckingArgument = false;
2565  for (int I = 0; I != num_command_line_args; ++I) {
2566    if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2567        strcmp(command_line_args[I], "-fspell-checking") == 0) {
2568      FoundSpellCheckingArgument = true;
2569      break;
2570    }
2571  }
2572  if (!FoundSpellCheckingArgument)
2573    Args->push_back("-fno-spell-checking");
2574
2575  Args->insert(Args->end(), command_line_args,
2576               command_line_args + num_command_line_args);
2577
2578  // The 'source_filename' argument is optional.  If the caller does not
2579  // specify it then it is assumed that the source file is specified
2580  // in the actual argument list.
2581  // Put the source file after command_line_args otherwise if '-x' flag is
2582  // present it will be unused.
2583  if (source_filename)
2584    Args->push_back(source_filename);
2585
2586  // Do we need the detailed preprocessing record?
2587  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2588    Args->push_back("-Xclang");
2589    Args->push_back("-detailed-preprocessing-record");
2590  }
2591
2592  unsigned NumErrors = Diags->getClient()->getNumErrors();
2593  OwningPtr<ASTUnit> ErrUnit;
2594  OwningPtr<ASTUnit> Unit(
2595    ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2596                                 /* vector::data() not portable */,
2597                                 Args->size() ? (&(*Args)[0] + Args->size()) :0,
2598                                 Diags,
2599                                 CXXIdx->getClangResourcesPath(),
2600                                 CXXIdx->getOnlyLocalDecls(),
2601                                 /*CaptureDiagnostics=*/true,
2602                                 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
2603                                 RemappedFiles->size(),
2604                                 /*RemappedFilesKeepOriginalName=*/true,
2605                                 PrecompilePreamble,
2606                                 TUKind,
2607                                 CacheCodeCompetionResults,
2608                                 /*AllowPCHWithCompilerErrors=*/true,
2609                                 SkipFunctionBodies,
2610                                 &ErrUnit));
2611
2612  if (NumErrors != Diags->getClient()->getNumErrors()) {
2613    // Make sure to check that 'Unit' is non-NULL.
2614    if (CXXIdx->getDisplayDiagnostics())
2615      printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
2616  }
2617
2618  PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
2619}
2620CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2621                                             const char *source_filename,
2622                                         const char * const *command_line_args,
2623                                             int num_command_line_args,
2624                                            struct CXUnsavedFile *unsaved_files,
2625                                             unsigned num_unsaved_files,
2626                                             unsigned options) {
2627  ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2628                                    num_command_line_args, unsaved_files,
2629                                    num_unsaved_files, options, 0 };
2630  llvm::CrashRecoveryContext CRC;
2631
2632  if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
2633    fprintf(stderr, "libclang: crash detected during parsing: {\n");
2634    fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
2635    fprintf(stderr, "  'command_line_args' : [");
2636    for (int i = 0; i != num_command_line_args; ++i) {
2637      if (i)
2638        fprintf(stderr, ", ");
2639      fprintf(stderr, "'%s'", command_line_args[i]);
2640    }
2641    fprintf(stderr, "],\n");
2642    fprintf(stderr, "  'unsaved_files' : [");
2643    for (unsigned i = 0; i != num_unsaved_files; ++i) {
2644      if (i)
2645        fprintf(stderr, ", ");
2646      fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2647              unsaved_files[i].Length);
2648    }
2649    fprintf(stderr, "],\n");
2650    fprintf(stderr, "  'options' : %d,\n", options);
2651    fprintf(stderr, "}\n");
2652
2653    return 0;
2654  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2655    PrintLibclangResourceUsage(PTUI.result);
2656  }
2657
2658  return PTUI.result;
2659}
2660
2661unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2662  return CXSaveTranslationUnit_None;
2663}
2664
2665namespace {
2666
2667struct SaveTranslationUnitInfo {
2668  CXTranslationUnit TU;
2669  const char *FileName;
2670  unsigned options;
2671  CXSaveError result;
2672};
2673
2674}
2675
2676static void clang_saveTranslationUnit_Impl(void *UserData) {
2677  SaveTranslationUnitInfo *STUI =
2678    static_cast<SaveTranslationUnitInfo*>(UserData);
2679
2680  CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2681  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
2682    setThreadBackgroundPriority();
2683
2684  STUI->result = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2685}
2686
2687int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2688                              unsigned options) {
2689  if (!TU)
2690    return CXSaveError_InvalidTU;
2691
2692  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2693  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2694
2695  SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2696
2697  if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2698      getenv("LIBCLANG_NOTHREADS")) {
2699    clang_saveTranslationUnit_Impl(&STUI);
2700
2701    if (getenv("LIBCLANG_RESOURCE_USAGE"))
2702      PrintLibclangResourceUsage(TU);
2703
2704    return STUI.result;
2705  }
2706
2707  // We have an AST that has invalid nodes due to compiler errors.
2708  // Use a crash recovery thread for protection.
2709
2710  llvm::CrashRecoveryContext CRC;
2711
2712  if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2713    fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2714    fprintf(stderr, "  'filename' : '%s'\n", FileName);
2715    fprintf(stderr, "  'options' : %d,\n", options);
2716    fprintf(stderr, "}\n");
2717
2718    return CXSaveError_Unknown;
2719
2720  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2721    PrintLibclangResourceUsage(TU);
2722  }
2723
2724  return STUI.result;
2725}
2726
2727void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2728  if (CTUnit) {
2729    // If the translation unit has been marked as unsafe to free, just discard
2730    // it.
2731    if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
2732      return;
2733
2734    delete static_cast<ASTUnit *>(CTUnit->TUData);
2735    disposeCXStringPool(CTUnit->StringPool);
2736    delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
2737    delete CTUnit;
2738  }
2739}
2740
2741unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2742  return CXReparse_None;
2743}
2744
2745struct ReparseTranslationUnitInfo {
2746  CXTranslationUnit TU;
2747  unsigned num_unsaved_files;
2748  struct CXUnsavedFile *unsaved_files;
2749  unsigned options;
2750  int result;
2751};
2752
2753static void clang_reparseTranslationUnit_Impl(void *UserData) {
2754  ReparseTranslationUnitInfo *RTUI =
2755    static_cast<ReparseTranslationUnitInfo*>(UserData);
2756  CXTranslationUnit TU = RTUI->TU;
2757
2758  // Reset the associated diagnostics.
2759  delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2760  TU->Diagnostics = 0;
2761
2762  unsigned num_unsaved_files = RTUI->num_unsaved_files;
2763  struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2764  unsigned options = RTUI->options;
2765  (void) options;
2766  RTUI->result = 1;
2767
2768  if (!TU)
2769    return;
2770
2771  CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2772  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
2773    setThreadBackgroundPriority();
2774
2775  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2776  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2777
2778  OwningPtr<std::vector<ASTUnit::RemappedFile> >
2779    RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2780
2781  // Recover resources if we crash before exiting this function.
2782  llvm::CrashRecoveryContextCleanupRegistrar<
2783    std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2784
2785  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2786    StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2787    const llvm::MemoryBuffer *Buffer
2788      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2789    RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2790                                            Buffer));
2791  }
2792
2793  if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2794                        RemappedFiles->size()))
2795    RTUI->result = 0;
2796}
2797
2798int clang_reparseTranslationUnit(CXTranslationUnit TU,
2799                                 unsigned num_unsaved_files,
2800                                 struct CXUnsavedFile *unsaved_files,
2801                                 unsigned options) {
2802  ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2803                                      options, 0 };
2804
2805  if (getenv("LIBCLANG_NOTHREADS")) {
2806    clang_reparseTranslationUnit_Impl(&RTUI);
2807    return RTUI.result;
2808  }
2809
2810  llvm::CrashRecoveryContext CRC;
2811
2812  if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
2813    fprintf(stderr, "libclang: crash detected during reparsing\n");
2814    static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
2815    return 1;
2816  } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2817    PrintLibclangResourceUsage(TU);
2818
2819  return RTUI.result;
2820}
2821
2822
2823CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2824  if (!CTUnit)
2825    return createCXString("");
2826
2827  ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
2828  return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2829}
2830
2831CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2832  CXCursor Result = { CXCursor_TranslationUnit, 0, { 0, 0, TU } };
2833  return Result;
2834}
2835
2836} // end: extern "C"
2837
2838//===----------------------------------------------------------------------===//
2839// CXFile Operations.
2840//===----------------------------------------------------------------------===//
2841
2842extern "C" {
2843CXString clang_getFileName(CXFile SFile) {
2844  if (!SFile)
2845    return createCXString((const char*)NULL);
2846
2847  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2848  return createCXString(FEnt->getName());
2849}
2850
2851time_t clang_getFileTime(CXFile SFile) {
2852  if (!SFile)
2853    return 0;
2854
2855  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2856  return FEnt->getModificationTime();
2857}
2858
2859CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2860  if (!tu)
2861    return 0;
2862
2863  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2864
2865  FileManager &FMgr = CXXUnit->getFileManager();
2866  return const_cast<FileEntry *>(FMgr.getFile(file_name));
2867}
2868
2869unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2870  if (!tu || !file)
2871    return 0;
2872
2873  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2874  FileEntry *FEnt = static_cast<FileEntry *>(file);
2875  return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2876                                          .isFileMultipleIncludeGuarded(FEnt);
2877}
2878
2879} // end: extern "C"
2880
2881//===----------------------------------------------------------------------===//
2882// CXCursor Operations.
2883//===----------------------------------------------------------------------===//
2884
2885static Decl *getDeclFromExpr(Stmt *E) {
2886  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2887    return getDeclFromExpr(CE->getSubExpr());
2888
2889  if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2890    return RefExpr->getDecl();
2891  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2892    return ME->getMemberDecl();
2893  if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2894    return RE->getDecl();
2895  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2896    if (PRE->isExplicitProperty())
2897      return PRE->getExplicitProperty();
2898    // It could be messaging both getter and setter as in:
2899    // ++myobj.myprop;
2900    // in which case prefer to associate the setter since it is less obvious
2901    // from inspecting the source that the setter is going to get called.
2902    if (PRE->isMessagingSetter())
2903      return PRE->getImplicitPropertySetter();
2904    return PRE->getImplicitPropertyGetter();
2905  }
2906  if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2907    return getDeclFromExpr(POE->getSyntacticForm());
2908  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2909    if (Expr *Src = OVE->getSourceExpr())
2910      return getDeclFromExpr(Src);
2911
2912  if (CallExpr *CE = dyn_cast<CallExpr>(E))
2913    return getDeclFromExpr(CE->getCallee());
2914  if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
2915    if (!CE->isElidable())
2916    return CE->getConstructor();
2917  if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2918    return OME->getMethodDecl();
2919
2920  if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2921    return PE->getProtocol();
2922  if (SubstNonTypeTemplateParmPackExpr *NTTP
2923                              = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2924    return NTTP->getParameterPack();
2925  if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2926    if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2927        isa<ParmVarDecl>(SizeOfPack->getPack()))
2928      return SizeOfPack->getPack();
2929
2930  return 0;
2931}
2932
2933static SourceLocation getLocationFromExpr(Expr *E) {
2934  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2935    return getLocationFromExpr(CE->getSubExpr());
2936
2937  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2938    return /*FIXME:*/Msg->getLeftLoc();
2939  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2940    return DRE->getLocation();
2941  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2942    return Member->getMemberLoc();
2943  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2944    return Ivar->getLocation();
2945  if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2946    return SizeOfPack->getPackLoc();
2947  if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2948    return PropRef->getLocation();
2949
2950  return E->getLocStart();
2951}
2952
2953extern "C" {
2954
2955unsigned clang_visitChildren(CXCursor parent,
2956                             CXCursorVisitor visitor,
2957                             CXClientData client_data) {
2958  CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2959                          /*VisitPreprocessorLast=*/false);
2960  return CursorVis.VisitChildren(parent);
2961}
2962
2963#ifndef __has_feature
2964#define __has_feature(x) 0
2965#endif
2966#if __has_feature(blocks)
2967typedef enum CXChildVisitResult
2968     (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2969
2970static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2971    CXClientData client_data) {
2972  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2973  return block(cursor, parent);
2974}
2975#else
2976// If we are compiled with a compiler that doesn't have native blocks support,
2977// define and call the block manually, so the
2978typedef struct _CXChildVisitResult
2979{
2980	void *isa;
2981	int flags;
2982	int reserved;
2983	enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2984                                         CXCursor);
2985} *CXCursorVisitorBlock;
2986
2987static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2988    CXClientData client_data) {
2989  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2990  return block->invoke(block, cursor, parent);
2991}
2992#endif
2993
2994
2995unsigned clang_visitChildrenWithBlock(CXCursor parent,
2996                                      CXCursorVisitorBlock block) {
2997  return clang_visitChildren(parent, visitWithBlock, block);
2998}
2999
3000static CXString getDeclSpelling(Decl *D) {
3001  if (!D)
3002    return createCXString("");
3003
3004  NamedDecl *ND = dyn_cast<NamedDecl>(D);
3005  if (!ND) {
3006    if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
3007      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3008        return createCXString(Property->getIdentifier()->getName());
3009
3010    return createCXString("");
3011  }
3012
3013  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3014    return createCXString(OMD->getSelector().getAsString());
3015
3016  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3017    // No, this isn't the same as the code below. getIdentifier() is non-virtual
3018    // and returns different names. NamedDecl returns the class name and
3019    // ObjCCategoryImplDecl returns the category name.
3020    return createCXString(CIMP->getIdentifier()->getNameStart());
3021
3022  if (isa<UsingDirectiveDecl>(D))
3023    return createCXString("");
3024
3025  SmallString<1024> S;
3026  llvm::raw_svector_ostream os(S);
3027  ND->printName(os);
3028
3029  return createCXString(os.str());
3030}
3031
3032CXString clang_getCursorSpelling(CXCursor C) {
3033  if (clang_isTranslationUnit(C.kind))
3034    return clang_getTranslationUnitSpelling(
3035                            static_cast<CXTranslationUnit>(C.data[2]));
3036
3037  if (clang_isReference(C.kind)) {
3038    switch (C.kind) {
3039    case CXCursor_ObjCSuperClassRef: {
3040      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3041      return createCXString(Super->getIdentifier()->getNameStart());
3042    }
3043    case CXCursor_ObjCClassRef: {
3044      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3045      return createCXString(Class->getIdentifier()->getNameStart());
3046    }
3047    case CXCursor_ObjCProtocolRef: {
3048      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3049      assert(OID && "getCursorSpelling(): Missing protocol decl");
3050      return createCXString(OID->getIdentifier()->getNameStart());
3051    }
3052    case CXCursor_CXXBaseSpecifier: {
3053      CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3054      return createCXString(B->getType().getAsString());
3055    }
3056    case CXCursor_TypeRef: {
3057      TypeDecl *Type = getCursorTypeRef(C).first;
3058      assert(Type && "Missing type decl");
3059
3060      return createCXString(getCursorContext(C).getTypeDeclType(Type).
3061                              getAsString());
3062    }
3063    case CXCursor_TemplateRef: {
3064      TemplateDecl *Template = getCursorTemplateRef(C).first;
3065      assert(Template && "Missing template decl");
3066
3067      return createCXString(Template->getNameAsString());
3068    }
3069
3070    case CXCursor_NamespaceRef: {
3071      NamedDecl *NS = getCursorNamespaceRef(C).first;
3072      assert(NS && "Missing namespace decl");
3073
3074      return createCXString(NS->getNameAsString());
3075    }
3076
3077    case CXCursor_MemberRef: {
3078      FieldDecl *Field = getCursorMemberRef(C).first;
3079      assert(Field && "Missing member decl");
3080
3081      return createCXString(Field->getNameAsString());
3082    }
3083
3084    case CXCursor_LabelRef: {
3085      LabelStmt *Label = getCursorLabelRef(C).first;
3086      assert(Label && "Missing label");
3087
3088      return createCXString(Label->getName());
3089    }
3090
3091    case CXCursor_OverloadedDeclRef: {
3092      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3093      if (Decl *D = Storage.dyn_cast<Decl *>()) {
3094        if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3095          return createCXString(ND->getNameAsString());
3096        return createCXString("");
3097      }
3098      if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3099        return createCXString(E->getName().getAsString());
3100      OverloadedTemplateStorage *Ovl
3101        = Storage.get<OverloadedTemplateStorage*>();
3102      if (Ovl->size() == 0)
3103        return createCXString("");
3104      return createCXString((*Ovl->begin())->getNameAsString());
3105    }
3106
3107    case CXCursor_VariableRef: {
3108      VarDecl *Var = getCursorVariableRef(C).first;
3109      assert(Var && "Missing variable decl");
3110
3111      return createCXString(Var->getNameAsString());
3112    }
3113
3114    default:
3115      return createCXString("<not implemented>");
3116    }
3117  }
3118
3119  if (clang_isExpression(C.kind)) {
3120    Decl *D = getDeclFromExpr(getCursorExpr(C));
3121    if (D)
3122      return getDeclSpelling(D);
3123    return createCXString("");
3124  }
3125
3126  if (clang_isStatement(C.kind)) {
3127    Stmt *S = getCursorStmt(C);
3128    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3129      return createCXString(Label->getName());
3130
3131    return createCXString("");
3132  }
3133
3134  if (C.kind == CXCursor_MacroExpansion)
3135    return createCXString(getCursorMacroExpansion(C)->getName()
3136                                                           ->getNameStart());
3137
3138  if (C.kind == CXCursor_MacroDefinition)
3139    return createCXString(getCursorMacroDefinition(C)->getName()
3140                                                           ->getNameStart());
3141
3142  if (C.kind == CXCursor_InclusionDirective)
3143    return createCXString(getCursorInclusionDirective(C)->getFileName());
3144
3145  if (clang_isDeclaration(C.kind))
3146    return getDeclSpelling(getCursorDecl(C));
3147
3148  if (C.kind == CXCursor_AnnotateAttr) {
3149    AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3150    return createCXString(AA->getAnnotation());
3151  }
3152
3153  if (C.kind == CXCursor_AsmLabelAttr) {
3154    AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3155    return createCXString(AA->getLabel());
3156  }
3157
3158  return createCXString("");
3159}
3160
3161CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3162                                                unsigned pieceIndex,
3163                                                unsigned options) {
3164  if (clang_Cursor_isNull(C))
3165    return clang_getNullRange();
3166
3167  ASTContext &Ctx = getCursorContext(C);
3168
3169  if (clang_isStatement(C.kind)) {
3170    Stmt *S = getCursorStmt(C);
3171    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3172      if (pieceIndex > 0)
3173        return clang_getNullRange();
3174      return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3175    }
3176
3177    return clang_getNullRange();
3178  }
3179
3180  if (C.kind == CXCursor_ObjCMessageExpr) {
3181    if (ObjCMessageExpr *
3182          ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3183      if (pieceIndex >= ME->getNumSelectorLocs())
3184        return clang_getNullRange();
3185      return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3186    }
3187  }
3188
3189  if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3190      C.kind == CXCursor_ObjCClassMethodDecl) {
3191    if (ObjCMethodDecl *
3192          MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3193      if (pieceIndex >= MD->getNumSelectorLocs())
3194        return clang_getNullRange();
3195      return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3196    }
3197  }
3198
3199  if (C.kind == CXCursor_ObjCCategoryDecl ||
3200      C.kind == CXCursor_ObjCCategoryImplDecl) {
3201    if (pieceIndex > 0)
3202      return clang_getNullRange();
3203    if (ObjCCategoryDecl *
3204          CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3205      return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3206    if (ObjCCategoryImplDecl *
3207          CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3208      return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3209  }
3210
3211  // FIXME: A CXCursor_InclusionDirective should give the location of the
3212  // filename, but we don't keep track of this.
3213
3214  // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3215  // but we don't keep track of this.
3216
3217  // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3218  // but we don't keep track of this.
3219
3220  // Default handling, give the location of the cursor.
3221
3222  if (pieceIndex > 0)
3223    return clang_getNullRange();
3224
3225  CXSourceLocation CXLoc = clang_getCursorLocation(C);
3226  SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3227  return cxloc::translateSourceRange(Ctx, Loc);
3228}
3229
3230CXString clang_getCursorDisplayName(CXCursor C) {
3231  if (!clang_isDeclaration(C.kind))
3232    return clang_getCursorSpelling(C);
3233
3234  Decl *D = getCursorDecl(C);
3235  if (!D)
3236    return createCXString("");
3237
3238  PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
3239  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3240    D = FunTmpl->getTemplatedDecl();
3241
3242  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3243    SmallString<64> Str;
3244    llvm::raw_svector_ostream OS(Str);
3245    OS << *Function;
3246    if (Function->getPrimaryTemplate())
3247      OS << "<>";
3248    OS << "(";
3249    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3250      if (I)
3251        OS << ", ";
3252      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3253    }
3254
3255    if (Function->isVariadic()) {
3256      if (Function->getNumParams())
3257        OS << ", ";
3258      OS << "...";
3259    }
3260    OS << ")";
3261    return createCXString(OS.str());
3262  }
3263
3264  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3265    SmallString<64> Str;
3266    llvm::raw_svector_ostream OS(Str);
3267    OS << *ClassTemplate;
3268    OS << "<";
3269    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3270    for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3271      if (I)
3272        OS << ", ";
3273
3274      NamedDecl *Param = Params->getParam(I);
3275      if (Param->getIdentifier()) {
3276        OS << Param->getIdentifier()->getName();
3277        continue;
3278      }
3279
3280      // There is no parameter name, which makes this tricky. Try to come up
3281      // with something useful that isn't too long.
3282      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3283        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3284      else if (NonTypeTemplateParmDecl *NTTP
3285                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
3286        OS << NTTP->getType().getAsString(Policy);
3287      else
3288        OS << "template<...> class";
3289    }
3290
3291    OS << ">";
3292    return createCXString(OS.str());
3293  }
3294
3295  if (ClassTemplateSpecializationDecl *ClassSpec
3296                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3297    // If the type was explicitly written, use that.
3298    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3299      return createCXString(TSInfo->getType().getAsString(Policy));
3300
3301    SmallString<64> Str;
3302    llvm::raw_svector_ostream OS(Str);
3303    OS << *ClassSpec;
3304    OS << TemplateSpecializationType::PrintTemplateArgumentList(
3305                                      ClassSpec->getTemplateArgs().data(),
3306                                      ClassSpec->getTemplateArgs().size(),
3307                                                                Policy);
3308    return createCXString(OS.str());
3309  }
3310
3311  return clang_getCursorSpelling(C);
3312}
3313
3314CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
3315  switch (Kind) {
3316  case CXCursor_FunctionDecl:
3317      return createCXString("FunctionDecl");
3318  case CXCursor_TypedefDecl:
3319      return createCXString("TypedefDecl");
3320  case CXCursor_EnumDecl:
3321      return createCXString("EnumDecl");
3322  case CXCursor_EnumConstantDecl:
3323      return createCXString("EnumConstantDecl");
3324  case CXCursor_StructDecl:
3325      return createCXString("StructDecl");
3326  case CXCursor_UnionDecl:
3327      return createCXString("UnionDecl");
3328  case CXCursor_ClassDecl:
3329      return createCXString("ClassDecl");
3330  case CXCursor_FieldDecl:
3331      return createCXString("FieldDecl");
3332  case CXCursor_VarDecl:
3333      return createCXString("VarDecl");
3334  case CXCursor_ParmDecl:
3335      return createCXString("ParmDecl");
3336  case CXCursor_ObjCInterfaceDecl:
3337      return createCXString("ObjCInterfaceDecl");
3338  case CXCursor_ObjCCategoryDecl:
3339      return createCXString("ObjCCategoryDecl");
3340  case CXCursor_ObjCProtocolDecl:
3341      return createCXString("ObjCProtocolDecl");
3342  case CXCursor_ObjCPropertyDecl:
3343      return createCXString("ObjCPropertyDecl");
3344  case CXCursor_ObjCIvarDecl:
3345      return createCXString("ObjCIvarDecl");
3346  case CXCursor_ObjCInstanceMethodDecl:
3347      return createCXString("ObjCInstanceMethodDecl");
3348  case CXCursor_ObjCClassMethodDecl:
3349      return createCXString("ObjCClassMethodDecl");
3350  case CXCursor_ObjCImplementationDecl:
3351      return createCXString("ObjCImplementationDecl");
3352  case CXCursor_ObjCCategoryImplDecl:
3353      return createCXString("ObjCCategoryImplDecl");
3354  case CXCursor_CXXMethod:
3355      return createCXString("CXXMethod");
3356  case CXCursor_UnexposedDecl:
3357      return createCXString("UnexposedDecl");
3358  case CXCursor_ObjCSuperClassRef:
3359      return createCXString("ObjCSuperClassRef");
3360  case CXCursor_ObjCProtocolRef:
3361      return createCXString("ObjCProtocolRef");
3362  case CXCursor_ObjCClassRef:
3363      return createCXString("ObjCClassRef");
3364  case CXCursor_TypeRef:
3365      return createCXString("TypeRef");
3366  case CXCursor_TemplateRef:
3367      return createCXString("TemplateRef");
3368  case CXCursor_NamespaceRef:
3369    return createCXString("NamespaceRef");
3370  case CXCursor_MemberRef:
3371    return createCXString("MemberRef");
3372  case CXCursor_LabelRef:
3373    return createCXString("LabelRef");
3374  case CXCursor_OverloadedDeclRef:
3375    return createCXString("OverloadedDeclRef");
3376  case CXCursor_VariableRef:
3377    return createCXString("VariableRef");
3378  case CXCursor_IntegerLiteral:
3379      return createCXString("IntegerLiteral");
3380  case CXCursor_FloatingLiteral:
3381      return createCXString("FloatingLiteral");
3382  case CXCursor_ImaginaryLiteral:
3383      return createCXString("ImaginaryLiteral");
3384  case CXCursor_StringLiteral:
3385      return createCXString("StringLiteral");
3386  case CXCursor_CharacterLiteral:
3387      return createCXString("CharacterLiteral");
3388  case CXCursor_ParenExpr:
3389      return createCXString("ParenExpr");
3390  case CXCursor_UnaryOperator:
3391      return createCXString("UnaryOperator");
3392  case CXCursor_ArraySubscriptExpr:
3393      return createCXString("ArraySubscriptExpr");
3394  case CXCursor_BinaryOperator:
3395      return createCXString("BinaryOperator");
3396  case CXCursor_CompoundAssignOperator:
3397      return createCXString("CompoundAssignOperator");
3398  case CXCursor_ConditionalOperator:
3399      return createCXString("ConditionalOperator");
3400  case CXCursor_CStyleCastExpr:
3401      return createCXString("CStyleCastExpr");
3402  case CXCursor_CompoundLiteralExpr:
3403      return createCXString("CompoundLiteralExpr");
3404  case CXCursor_InitListExpr:
3405      return createCXString("InitListExpr");
3406  case CXCursor_AddrLabelExpr:
3407      return createCXString("AddrLabelExpr");
3408  case CXCursor_StmtExpr:
3409      return createCXString("StmtExpr");
3410  case CXCursor_GenericSelectionExpr:
3411      return createCXString("GenericSelectionExpr");
3412  case CXCursor_GNUNullExpr:
3413      return createCXString("GNUNullExpr");
3414  case CXCursor_CXXStaticCastExpr:
3415      return createCXString("CXXStaticCastExpr");
3416  case CXCursor_CXXDynamicCastExpr:
3417      return createCXString("CXXDynamicCastExpr");
3418  case CXCursor_CXXReinterpretCastExpr:
3419      return createCXString("CXXReinterpretCastExpr");
3420  case CXCursor_CXXConstCastExpr:
3421      return createCXString("CXXConstCastExpr");
3422  case CXCursor_CXXFunctionalCastExpr:
3423      return createCXString("CXXFunctionalCastExpr");
3424  case CXCursor_CXXTypeidExpr:
3425      return createCXString("CXXTypeidExpr");
3426  case CXCursor_CXXBoolLiteralExpr:
3427      return createCXString("CXXBoolLiteralExpr");
3428  case CXCursor_CXXNullPtrLiteralExpr:
3429      return createCXString("CXXNullPtrLiteralExpr");
3430  case CXCursor_CXXThisExpr:
3431      return createCXString("CXXThisExpr");
3432  case CXCursor_CXXThrowExpr:
3433      return createCXString("CXXThrowExpr");
3434  case CXCursor_CXXNewExpr:
3435      return createCXString("CXXNewExpr");
3436  case CXCursor_CXXDeleteExpr:
3437      return createCXString("CXXDeleteExpr");
3438  case CXCursor_UnaryExpr:
3439      return createCXString("UnaryExpr");
3440  case CXCursor_ObjCStringLiteral:
3441      return createCXString("ObjCStringLiteral");
3442  case CXCursor_ObjCBoolLiteralExpr:
3443      return createCXString("ObjCBoolLiteralExpr");
3444  case CXCursor_ObjCEncodeExpr:
3445      return createCXString("ObjCEncodeExpr");
3446  case CXCursor_ObjCSelectorExpr:
3447      return createCXString("ObjCSelectorExpr");
3448  case CXCursor_ObjCProtocolExpr:
3449      return createCXString("ObjCProtocolExpr");
3450  case CXCursor_ObjCBridgedCastExpr:
3451      return createCXString("ObjCBridgedCastExpr");
3452  case CXCursor_BlockExpr:
3453      return createCXString("BlockExpr");
3454  case CXCursor_PackExpansionExpr:
3455      return createCXString("PackExpansionExpr");
3456  case CXCursor_SizeOfPackExpr:
3457      return createCXString("SizeOfPackExpr");
3458  case CXCursor_LambdaExpr:
3459    return createCXString("LambdaExpr");
3460  case CXCursor_UnexposedExpr:
3461      return createCXString("UnexposedExpr");
3462  case CXCursor_DeclRefExpr:
3463      return createCXString("DeclRefExpr");
3464  case CXCursor_MemberRefExpr:
3465      return createCXString("MemberRefExpr");
3466  case CXCursor_CallExpr:
3467      return createCXString("CallExpr");
3468  case CXCursor_ObjCMessageExpr:
3469      return createCXString("ObjCMessageExpr");
3470  case CXCursor_UnexposedStmt:
3471      return createCXString("UnexposedStmt");
3472  case CXCursor_DeclStmt:
3473      return createCXString("DeclStmt");
3474  case CXCursor_LabelStmt:
3475      return createCXString("LabelStmt");
3476  case CXCursor_CompoundStmt:
3477      return createCXString("CompoundStmt");
3478  case CXCursor_CaseStmt:
3479      return createCXString("CaseStmt");
3480  case CXCursor_DefaultStmt:
3481      return createCXString("DefaultStmt");
3482  case CXCursor_IfStmt:
3483      return createCXString("IfStmt");
3484  case CXCursor_SwitchStmt:
3485      return createCXString("SwitchStmt");
3486  case CXCursor_WhileStmt:
3487      return createCXString("WhileStmt");
3488  case CXCursor_DoStmt:
3489      return createCXString("DoStmt");
3490  case CXCursor_ForStmt:
3491      return createCXString("ForStmt");
3492  case CXCursor_GotoStmt:
3493      return createCXString("GotoStmt");
3494  case CXCursor_IndirectGotoStmt:
3495      return createCXString("IndirectGotoStmt");
3496  case CXCursor_ContinueStmt:
3497      return createCXString("ContinueStmt");
3498  case CXCursor_BreakStmt:
3499      return createCXString("BreakStmt");
3500  case CXCursor_ReturnStmt:
3501      return createCXString("ReturnStmt");
3502  case CXCursor_AsmStmt:
3503      return createCXString("AsmStmt");
3504  case CXCursor_ObjCAtTryStmt:
3505      return createCXString("ObjCAtTryStmt");
3506  case CXCursor_ObjCAtCatchStmt:
3507      return createCXString("ObjCAtCatchStmt");
3508  case CXCursor_ObjCAtFinallyStmt:
3509      return createCXString("ObjCAtFinallyStmt");
3510  case CXCursor_ObjCAtThrowStmt:
3511      return createCXString("ObjCAtThrowStmt");
3512  case CXCursor_ObjCAtSynchronizedStmt:
3513      return createCXString("ObjCAtSynchronizedStmt");
3514  case CXCursor_ObjCAutoreleasePoolStmt:
3515      return createCXString("ObjCAutoreleasePoolStmt");
3516  case CXCursor_ObjCForCollectionStmt:
3517      return createCXString("ObjCForCollectionStmt");
3518  case CXCursor_CXXCatchStmt:
3519      return createCXString("CXXCatchStmt");
3520  case CXCursor_CXXTryStmt:
3521      return createCXString("CXXTryStmt");
3522  case CXCursor_CXXForRangeStmt:
3523      return createCXString("CXXForRangeStmt");
3524  case CXCursor_SEHTryStmt:
3525      return createCXString("SEHTryStmt");
3526  case CXCursor_SEHExceptStmt:
3527      return createCXString("SEHExceptStmt");
3528  case CXCursor_SEHFinallyStmt:
3529      return createCXString("SEHFinallyStmt");
3530  case CXCursor_NullStmt:
3531      return createCXString("NullStmt");
3532  case CXCursor_InvalidFile:
3533      return createCXString("InvalidFile");
3534  case CXCursor_InvalidCode:
3535    return createCXString("InvalidCode");
3536  case CXCursor_NoDeclFound:
3537      return createCXString("NoDeclFound");
3538  case CXCursor_NotImplemented:
3539      return createCXString("NotImplemented");
3540  case CXCursor_TranslationUnit:
3541      return createCXString("TranslationUnit");
3542  case CXCursor_UnexposedAttr:
3543      return createCXString("UnexposedAttr");
3544  case CXCursor_IBActionAttr:
3545      return createCXString("attribute(ibaction)");
3546  case CXCursor_IBOutletAttr:
3547     return createCXString("attribute(iboutlet)");
3548  case CXCursor_IBOutletCollectionAttr:
3549      return createCXString("attribute(iboutletcollection)");
3550  case CXCursor_CXXFinalAttr:
3551      return createCXString("attribute(final)");
3552  case CXCursor_CXXOverrideAttr:
3553      return createCXString("attribute(override)");
3554  case CXCursor_AnnotateAttr:
3555    return createCXString("attribute(annotate)");
3556  case CXCursor_AsmLabelAttr:
3557    return createCXString("asm label");
3558  case CXCursor_PreprocessingDirective:
3559    return createCXString("preprocessing directive");
3560  case CXCursor_MacroDefinition:
3561    return createCXString("macro definition");
3562  case CXCursor_MacroExpansion:
3563    return createCXString("macro expansion");
3564  case CXCursor_InclusionDirective:
3565    return createCXString("inclusion directive");
3566  case CXCursor_Namespace:
3567    return createCXString("Namespace");
3568  case CXCursor_LinkageSpec:
3569    return createCXString("LinkageSpec");
3570  case CXCursor_CXXBaseSpecifier:
3571    return createCXString("C++ base class specifier");
3572  case CXCursor_Constructor:
3573    return createCXString("CXXConstructor");
3574  case CXCursor_Destructor:
3575    return createCXString("CXXDestructor");
3576  case CXCursor_ConversionFunction:
3577    return createCXString("CXXConversion");
3578  case CXCursor_TemplateTypeParameter:
3579    return createCXString("TemplateTypeParameter");
3580  case CXCursor_NonTypeTemplateParameter:
3581    return createCXString("NonTypeTemplateParameter");
3582  case CXCursor_TemplateTemplateParameter:
3583    return createCXString("TemplateTemplateParameter");
3584  case CXCursor_FunctionTemplate:
3585    return createCXString("FunctionTemplate");
3586  case CXCursor_ClassTemplate:
3587    return createCXString("ClassTemplate");
3588  case CXCursor_ClassTemplatePartialSpecialization:
3589    return createCXString("ClassTemplatePartialSpecialization");
3590  case CXCursor_NamespaceAlias:
3591    return createCXString("NamespaceAlias");
3592  case CXCursor_UsingDirective:
3593    return createCXString("UsingDirective");
3594  case CXCursor_UsingDeclaration:
3595    return createCXString("UsingDeclaration");
3596  case CXCursor_TypeAliasDecl:
3597    return createCXString("TypeAliasDecl");
3598  case CXCursor_ObjCSynthesizeDecl:
3599    return createCXString("ObjCSynthesizeDecl");
3600  case CXCursor_ObjCDynamicDecl:
3601    return createCXString("ObjCDynamicDecl");
3602  case CXCursor_CXXAccessSpecifier:
3603    return createCXString("CXXAccessSpecifier");
3604  }
3605
3606  llvm_unreachable("Unhandled CXCursorKind");
3607}
3608
3609struct GetCursorData {
3610  SourceLocation TokenBeginLoc;
3611  bool PointsAtMacroArgExpansion;
3612  CXCursor &BestCursor;
3613
3614  GetCursorData(SourceManager &SM,
3615                SourceLocation tokenBegin, CXCursor &outputCursor)
3616    : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3617    PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3618  }
3619};
3620
3621static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3622                                                CXCursor parent,
3623                                                CXClientData client_data) {
3624  GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3625  CXCursor *BestCursor = &Data->BestCursor;
3626
3627  // If we point inside a macro argument we should provide info of what the
3628  // token is so use the actual cursor, don't replace it with a macro expansion
3629  // cursor.
3630  if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3631    return CXChildVisit_Recurse;
3632
3633  if (clang_isDeclaration(cursor.kind)) {
3634    // Avoid having the implicit methods override the property decls.
3635    if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor)))
3636      if (MD->isImplicit())
3637        return CXChildVisit_Break;
3638  }
3639
3640  if (clang_isExpression(cursor.kind) &&
3641      clang_isDeclaration(BestCursor->kind)) {
3642    if (Decl *D = getCursorDecl(*BestCursor)) {
3643      // Avoid having the cursor of an expression replace the declaration cursor
3644      // when the expression source range overlaps the declaration range.
3645      // This can happen for C++ constructor expressions whose range generally
3646      // include the variable declaration, e.g.:
3647      //  MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3648      if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3649          D->getLocation() == Data->TokenBeginLoc)
3650        return CXChildVisit_Break;
3651    }
3652  }
3653
3654  // If our current best cursor is the construction of a temporary object,
3655  // don't replace that cursor with a type reference, because we want
3656  // clang_getCursor() to point at the constructor.
3657  if (clang_isExpression(BestCursor->kind) &&
3658      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3659      cursor.kind == CXCursor_TypeRef) {
3660    // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3661    // as having the actual point on the type reference.
3662    *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
3663    return CXChildVisit_Recurse;
3664  }
3665
3666  *BestCursor = cursor;
3667  return CXChildVisit_Recurse;
3668}
3669
3670CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3671  if (!TU)
3672    return clang_getNullCursor();
3673
3674  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3675  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3676
3677  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3678  CXCursor Result = cxcursor::getCursor(TU, SLoc);
3679
3680  bool Logging = getenv("LIBCLANG_LOGGING");
3681  if (Logging) {
3682    CXFile SearchFile;
3683    unsigned SearchLine, SearchColumn;
3684    CXFile ResultFile;
3685    unsigned ResultLine, ResultColumn;
3686    CXString SearchFileName, ResultFileName, KindSpelling, USR;
3687    const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
3688    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3689
3690    clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3691    clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3692                               &ResultColumn, 0);
3693    SearchFileName = clang_getFileName(SearchFile);
3694    ResultFileName = clang_getFileName(ResultFile);
3695    KindSpelling = clang_getCursorKindSpelling(Result.kind);
3696    USR = clang_getCursorUSR(Result);
3697    fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
3698            clang_getCString(SearchFileName), SearchLine, SearchColumn,
3699            clang_getCString(KindSpelling),
3700            clang_getCString(ResultFileName), ResultLine, ResultColumn,
3701            clang_getCString(USR), IsDef);
3702    clang_disposeString(SearchFileName);
3703    clang_disposeString(ResultFileName);
3704    clang_disposeString(KindSpelling);
3705    clang_disposeString(USR);
3706
3707    CXCursor Definition = clang_getCursorDefinition(Result);
3708    if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3709      CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3710      CXString DefinitionKindSpelling
3711                                = clang_getCursorKindSpelling(Definition.kind);
3712      CXFile DefinitionFile;
3713      unsigned DefinitionLine, DefinitionColumn;
3714      clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3715                                 &DefinitionLine, &DefinitionColumn, 0);
3716      CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3717      fprintf(stderr, "  -> %s(%s:%d:%d)\n",
3718              clang_getCString(DefinitionKindSpelling),
3719              clang_getCString(DefinitionFileName),
3720              DefinitionLine, DefinitionColumn);
3721      clang_disposeString(DefinitionFileName);
3722      clang_disposeString(DefinitionKindSpelling);
3723    }
3724  }
3725
3726  return Result;
3727}
3728
3729CXCursor clang_getNullCursor(void) {
3730  return MakeCXCursorInvalid(CXCursor_InvalidFile);
3731}
3732
3733unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3734  return X == Y;
3735}
3736
3737unsigned clang_hashCursor(CXCursor C) {
3738  unsigned Index = 0;
3739  if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3740    Index = 1;
3741
3742  return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3743                                        std::make_pair(C.kind, C.data[Index]));
3744}
3745
3746unsigned clang_isInvalid(enum CXCursorKind K) {
3747  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3748}
3749
3750unsigned clang_isDeclaration(enum CXCursorKind K) {
3751  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3752}
3753
3754unsigned clang_isReference(enum CXCursorKind K) {
3755  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3756}
3757
3758unsigned clang_isExpression(enum CXCursorKind K) {
3759  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3760}
3761
3762unsigned clang_isStatement(enum CXCursorKind K) {
3763  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3764}
3765
3766unsigned clang_isAttribute(enum CXCursorKind K) {
3767    return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3768}
3769
3770unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3771  return K == CXCursor_TranslationUnit;
3772}
3773
3774unsigned clang_isPreprocessing(enum CXCursorKind K) {
3775  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3776}
3777
3778unsigned clang_isUnexposed(enum CXCursorKind K) {
3779  switch (K) {
3780    case CXCursor_UnexposedDecl:
3781    case CXCursor_UnexposedExpr:
3782    case CXCursor_UnexposedStmt:
3783    case CXCursor_UnexposedAttr:
3784      return true;
3785    default:
3786      return false;
3787  }
3788}
3789
3790CXCursorKind clang_getCursorKind(CXCursor C) {
3791  return C.kind;
3792}
3793
3794CXSourceLocation clang_getCursorLocation(CXCursor C) {
3795  if (clang_isReference(C.kind)) {
3796    switch (C.kind) {
3797    case CXCursor_ObjCSuperClassRef: {
3798      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3799        = getCursorObjCSuperClassRef(C);
3800      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3801    }
3802
3803    case CXCursor_ObjCProtocolRef: {
3804      std::pair<ObjCProtocolDecl *, SourceLocation> P
3805        = getCursorObjCProtocolRef(C);
3806      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3807    }
3808
3809    case CXCursor_ObjCClassRef: {
3810      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3811        = getCursorObjCClassRef(C);
3812      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3813    }
3814
3815    case CXCursor_TypeRef: {
3816      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3817      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3818    }
3819
3820    case CXCursor_TemplateRef: {
3821      std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3822      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3823    }
3824
3825    case CXCursor_NamespaceRef: {
3826      std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3827      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3828    }
3829
3830    case CXCursor_MemberRef: {
3831      std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3832      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3833    }
3834
3835    case CXCursor_VariableRef: {
3836      std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3837      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3838    }
3839
3840    case CXCursor_CXXBaseSpecifier: {
3841      CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3842      if (!BaseSpec)
3843        return clang_getNullLocation();
3844
3845      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3846        return cxloc::translateSourceLocation(getCursorContext(C),
3847                                            TSInfo->getTypeLoc().getBeginLoc());
3848
3849      return cxloc::translateSourceLocation(getCursorContext(C),
3850                                        BaseSpec->getLocStart());
3851    }
3852
3853    case CXCursor_LabelRef: {
3854      std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3855      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3856    }
3857
3858    case CXCursor_OverloadedDeclRef:
3859      return cxloc::translateSourceLocation(getCursorContext(C),
3860                                          getCursorOverloadedDeclRef(C).second);
3861
3862    default:
3863      // FIXME: Need a way to enumerate all non-reference cases.
3864      llvm_unreachable("Missed a reference kind");
3865    }
3866  }
3867
3868  if (clang_isExpression(C.kind))
3869    return cxloc::translateSourceLocation(getCursorContext(C),
3870                                   getLocationFromExpr(getCursorExpr(C)));
3871
3872  if (clang_isStatement(C.kind))
3873    return cxloc::translateSourceLocation(getCursorContext(C),
3874                                          getCursorStmt(C)->getLocStart());
3875
3876  if (C.kind == CXCursor_PreprocessingDirective) {
3877    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3878    return cxloc::translateSourceLocation(getCursorContext(C), L);
3879  }
3880
3881  if (C.kind == CXCursor_MacroExpansion) {
3882    SourceLocation L
3883      = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
3884    return cxloc::translateSourceLocation(getCursorContext(C), L);
3885  }
3886
3887  if (C.kind == CXCursor_MacroDefinition) {
3888    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3889    return cxloc::translateSourceLocation(getCursorContext(C), L);
3890  }
3891
3892  if (C.kind == CXCursor_InclusionDirective) {
3893    SourceLocation L
3894      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3895    return cxloc::translateSourceLocation(getCursorContext(C), L);
3896  }
3897
3898  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3899    return clang_getNullLocation();
3900
3901  Decl *D = getCursorDecl(C);
3902  if (!D)
3903    return clang_getNullLocation();
3904
3905  SourceLocation Loc = D->getLocation();
3906  // FIXME: Multiple variables declared in a single declaration
3907  // currently lack the information needed to correctly determine their
3908  // ranges when accounting for the type-specifier.  We use context
3909  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3910  // and if so, whether it is the first decl.
3911  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3912    if (!cxcursor::isFirstInDeclGroup(C))
3913      Loc = VD->getLocation();
3914  }
3915
3916  // For ObjC methods, give the start location of the method name.
3917  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3918    Loc = MD->getSelectorStartLoc();
3919
3920  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3921}
3922
3923} // end extern "C"
3924
3925CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3926  assert(TU);
3927
3928  // Guard against an invalid SourceLocation, or we may assert in one
3929  // of the following calls.
3930  if (SLoc.isInvalid())
3931    return clang_getNullCursor();
3932
3933  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3934
3935  // Translate the given source location to make it point at the beginning of
3936  // the token under the cursor.
3937  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3938                                    CXXUnit->getASTContext().getLangOpts());
3939
3940  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3941  if (SLoc.isValid()) {
3942    GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
3943    CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
3944                            /*VisitPreprocessorLast=*/true,
3945                            /*VisitIncludedEntities=*/false,
3946                            SourceLocation(SLoc));
3947    CursorVis.visitFileRegion();
3948  }
3949
3950  return Result;
3951}
3952
3953static SourceRange getRawCursorExtent(CXCursor C) {
3954  if (clang_isReference(C.kind)) {
3955    switch (C.kind) {
3956    case CXCursor_ObjCSuperClassRef:
3957      return  getCursorObjCSuperClassRef(C).second;
3958
3959    case CXCursor_ObjCProtocolRef:
3960      return getCursorObjCProtocolRef(C).second;
3961
3962    case CXCursor_ObjCClassRef:
3963      return getCursorObjCClassRef(C).second;
3964
3965    case CXCursor_TypeRef:
3966      return getCursorTypeRef(C).second;
3967
3968    case CXCursor_TemplateRef:
3969      return getCursorTemplateRef(C).second;
3970
3971    case CXCursor_NamespaceRef:
3972      return getCursorNamespaceRef(C).second;
3973
3974    case CXCursor_MemberRef:
3975      return getCursorMemberRef(C).second;
3976
3977    case CXCursor_CXXBaseSpecifier:
3978      return getCursorCXXBaseSpecifier(C)->getSourceRange();
3979
3980    case CXCursor_LabelRef:
3981      return getCursorLabelRef(C).second;
3982
3983    case CXCursor_OverloadedDeclRef:
3984      return getCursorOverloadedDeclRef(C).second;
3985
3986    case CXCursor_VariableRef:
3987      return getCursorVariableRef(C).second;
3988
3989    default:
3990      // FIXME: Need a way to enumerate all non-reference cases.
3991      llvm_unreachable("Missed a reference kind");
3992    }
3993  }
3994
3995  if (clang_isExpression(C.kind))
3996    return getCursorExpr(C)->getSourceRange();
3997
3998  if (clang_isStatement(C.kind))
3999    return getCursorStmt(C)->getSourceRange();
4000
4001  if (clang_isAttribute(C.kind))
4002    return getCursorAttr(C)->getRange();
4003
4004  if (C.kind == CXCursor_PreprocessingDirective)
4005    return cxcursor::getCursorPreprocessingDirective(C);
4006
4007  if (C.kind == CXCursor_MacroExpansion) {
4008    ASTUnit *TU = getCursorASTUnit(C);
4009    SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
4010    return TU->mapRangeFromPreamble(Range);
4011  }
4012
4013  if (C.kind == CXCursor_MacroDefinition) {
4014    ASTUnit *TU = getCursorASTUnit(C);
4015    SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4016    return TU->mapRangeFromPreamble(Range);
4017  }
4018
4019  if (C.kind == CXCursor_InclusionDirective) {
4020    ASTUnit *TU = getCursorASTUnit(C);
4021    SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4022    return TU->mapRangeFromPreamble(Range);
4023  }
4024
4025  if (C.kind == CXCursor_TranslationUnit) {
4026    ASTUnit *TU = getCursorASTUnit(C);
4027    FileID MainID = TU->getSourceManager().getMainFileID();
4028    SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4029    SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4030    return SourceRange(Start, End);
4031  }
4032
4033  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4034    Decl *D = cxcursor::getCursorDecl(C);
4035    if (!D)
4036      return SourceRange();
4037
4038    SourceRange R = D->getSourceRange();
4039    // FIXME: Multiple variables declared in a single declaration
4040    // currently lack the information needed to correctly determine their
4041    // ranges when accounting for the type-specifier.  We use context
4042    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4043    // and if so, whether it is the first decl.
4044    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4045      if (!cxcursor::isFirstInDeclGroup(C))
4046        R.setBegin(VD->getLocation());
4047    }
4048    return R;
4049  }
4050  return SourceRange();
4051}
4052
4053/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4054/// the decl-specifier-seq for declarations.
4055static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4056  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4057    Decl *D = cxcursor::getCursorDecl(C);
4058    if (!D)
4059      return SourceRange();
4060
4061    SourceRange R = D->getSourceRange();
4062
4063    // Adjust the start of the location for declarations preceded by
4064    // declaration specifiers.
4065    SourceLocation StartLoc;
4066    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4067      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4068        StartLoc = TI->getTypeLoc().getLocStart();
4069    } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4070      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4071        StartLoc = TI->getTypeLoc().getLocStart();
4072    }
4073
4074    if (StartLoc.isValid() && R.getBegin().isValid() &&
4075        SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4076      R.setBegin(StartLoc);
4077
4078    // FIXME: Multiple variables declared in a single declaration
4079    // currently lack the information needed to correctly determine their
4080    // ranges when accounting for the type-specifier.  We use context
4081    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4082    // and if so, whether it is the first decl.
4083    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4084      if (!cxcursor::isFirstInDeclGroup(C))
4085        R.setBegin(VD->getLocation());
4086    }
4087
4088    return R;
4089  }
4090
4091  return getRawCursorExtent(C);
4092}
4093
4094extern "C" {
4095
4096CXSourceRange clang_getCursorExtent(CXCursor C) {
4097  SourceRange R = getRawCursorExtent(C);
4098  if (R.isInvalid())
4099    return clang_getNullRange();
4100
4101  return cxloc::translateSourceRange(getCursorContext(C), R);
4102}
4103
4104CXCursor clang_getCursorReferenced(CXCursor C) {
4105  if (clang_isInvalid(C.kind))
4106    return clang_getNullCursor();
4107
4108  CXTranslationUnit tu = getCursorTU(C);
4109  if (clang_isDeclaration(C.kind)) {
4110    Decl *D = getCursorDecl(C);
4111    if (!D)
4112      return clang_getNullCursor();
4113    if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4114      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
4115    if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
4116      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4117        return MakeCXCursor(Property, tu);
4118
4119    return C;
4120  }
4121
4122  if (clang_isExpression(C.kind)) {
4123    Expr *E = getCursorExpr(C);
4124    Decl *D = getDeclFromExpr(E);
4125    if (D) {
4126      CXCursor declCursor = MakeCXCursor(D, tu);
4127      declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4128                                               declCursor);
4129      return declCursor;
4130    }
4131
4132    if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
4133      return MakeCursorOverloadedDeclRef(Ovl, tu);
4134
4135    return clang_getNullCursor();
4136  }
4137
4138  if (clang_isStatement(C.kind)) {
4139    Stmt *S = getCursorStmt(C);
4140    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
4141      if (LabelDecl *label = Goto->getLabel())
4142        if (LabelStmt *labelS = label->getStmt())
4143        return MakeCXCursor(labelS, getCursorDecl(C), tu);
4144
4145    return clang_getNullCursor();
4146  }
4147
4148  if (C.kind == CXCursor_MacroExpansion) {
4149    if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
4150      return MakeMacroDefinitionCursor(Def, tu);
4151  }
4152
4153  if (!clang_isReference(C.kind))
4154    return clang_getNullCursor();
4155
4156  switch (C.kind) {
4157    case CXCursor_ObjCSuperClassRef:
4158      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
4159
4160    case CXCursor_ObjCProtocolRef: {
4161      ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4162      if (ObjCProtocolDecl *Def = Prot->getDefinition())
4163        return MakeCXCursor(Def, tu);
4164
4165      return MakeCXCursor(Prot, tu);
4166    }
4167
4168    case CXCursor_ObjCClassRef: {
4169      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4170      if (ObjCInterfaceDecl *Def = Class->getDefinition())
4171        return MakeCXCursor(Def, tu);
4172
4173      return MakeCXCursor(Class, tu);
4174    }
4175
4176    case CXCursor_TypeRef:
4177      return MakeCXCursor(getCursorTypeRef(C).first, tu );
4178
4179    case CXCursor_TemplateRef:
4180      return MakeCXCursor(getCursorTemplateRef(C).first, tu );
4181
4182    case CXCursor_NamespaceRef:
4183      return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
4184
4185    case CXCursor_MemberRef:
4186      return MakeCXCursor(getCursorMemberRef(C).first, tu );
4187
4188    case CXCursor_CXXBaseSpecifier: {
4189      CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4190      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
4191                                                         tu ));
4192    }
4193
4194    case CXCursor_LabelRef:
4195      // FIXME: We end up faking the "parent" declaration here because we
4196      // don't want to make CXCursor larger.
4197      return MakeCXCursor(getCursorLabelRef(C).first,
4198               static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4199                          .getTranslationUnitDecl(),
4200                          tu);
4201
4202    case CXCursor_OverloadedDeclRef:
4203      return C;
4204
4205    case CXCursor_VariableRef:
4206      return MakeCXCursor(getCursorVariableRef(C).first, tu);
4207
4208    default:
4209      // We would prefer to enumerate all non-reference cursor kinds here.
4210      llvm_unreachable("Unhandled reference cursor kind");
4211  }
4212}
4213
4214CXCursor clang_getCursorDefinition(CXCursor C) {
4215  if (clang_isInvalid(C.kind))
4216    return clang_getNullCursor();
4217
4218  CXTranslationUnit TU = getCursorTU(C);
4219
4220  bool WasReference = false;
4221  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
4222    C = clang_getCursorReferenced(C);
4223    WasReference = true;
4224  }
4225
4226  if (C.kind == CXCursor_MacroExpansion)
4227    return clang_getCursorReferenced(C);
4228
4229  if (!clang_isDeclaration(C.kind))
4230    return clang_getNullCursor();
4231
4232  Decl *D = getCursorDecl(C);
4233  if (!D)
4234    return clang_getNullCursor();
4235
4236  switch (D->getKind()) {
4237  // Declaration kinds that don't really separate the notions of
4238  // declaration and definition.
4239  case Decl::Namespace:
4240  case Decl::Typedef:
4241  case Decl::TypeAlias:
4242  case Decl::TypeAliasTemplate:
4243  case Decl::TemplateTypeParm:
4244  case Decl::EnumConstant:
4245  case Decl::Field:
4246  case Decl::IndirectField:
4247  case Decl::ObjCIvar:
4248  case Decl::ObjCAtDefsField:
4249  case Decl::ImplicitParam:
4250  case Decl::ParmVar:
4251  case Decl::NonTypeTemplateParm:
4252  case Decl::TemplateTemplateParm:
4253  case Decl::ObjCCategoryImpl:
4254  case Decl::ObjCImplementation:
4255  case Decl::AccessSpec:
4256  case Decl::LinkageSpec:
4257  case Decl::ObjCPropertyImpl:
4258  case Decl::FileScopeAsm:
4259  case Decl::StaticAssert:
4260  case Decl::Block:
4261  case Decl::Label:  // FIXME: Is this right??
4262  case Decl::ClassScopeFunctionSpecialization:
4263  case Decl::Import:
4264    return C;
4265
4266  // Declaration kinds that don't make any sense here, but are
4267  // nonetheless harmless.
4268  case Decl::TranslationUnit:
4269    break;
4270
4271  // Declaration kinds for which the definition is not resolvable.
4272  case Decl::UnresolvedUsingTypename:
4273  case Decl::UnresolvedUsingValue:
4274    break;
4275
4276  case Decl::UsingDirective:
4277    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
4278                        TU);
4279
4280  case Decl::NamespaceAlias:
4281    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
4282
4283  case Decl::Enum:
4284  case Decl::Record:
4285  case Decl::CXXRecord:
4286  case Decl::ClassTemplateSpecialization:
4287  case Decl::ClassTemplatePartialSpecialization:
4288    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
4289      return MakeCXCursor(Def, TU);
4290    return clang_getNullCursor();
4291
4292  case Decl::Function:
4293  case Decl::CXXMethod:
4294  case Decl::CXXConstructor:
4295  case Decl::CXXDestructor:
4296  case Decl::CXXConversion: {
4297    const FunctionDecl *Def = 0;
4298    if (cast<FunctionDecl>(D)->getBody(Def))
4299      return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
4300    return clang_getNullCursor();
4301  }
4302
4303  case Decl::Var: {
4304    // Ask the variable if it has a definition.
4305    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
4306      return MakeCXCursor(Def, TU);
4307    return clang_getNullCursor();
4308  }
4309
4310  case Decl::FunctionTemplate: {
4311    const FunctionDecl *Def = 0;
4312    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
4313      return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
4314    return clang_getNullCursor();
4315  }
4316
4317  case Decl::ClassTemplate: {
4318    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
4319                                                            ->getDefinition())
4320      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
4321                          TU);
4322    return clang_getNullCursor();
4323  }
4324
4325  case Decl::Using:
4326    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
4327                                       D->getLocation(), TU);
4328
4329  case Decl::UsingShadow:
4330    return clang_getCursorDefinition(
4331                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
4332                                    TU));
4333
4334  case Decl::ObjCMethod: {
4335    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4336    if (Method->isThisDeclarationADefinition())
4337      return C;
4338
4339    // Dig out the method definition in the associated
4340    // @implementation, if we have it.
4341    // FIXME: The ASTs should make finding the definition easier.
4342    if (ObjCInterfaceDecl *Class
4343                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4344      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4345        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4346                                                  Method->isInstanceMethod()))
4347          if (Def->isThisDeclarationADefinition())
4348            return MakeCXCursor(Def, TU);
4349
4350    return clang_getNullCursor();
4351  }
4352
4353  case Decl::ObjCCategory:
4354    if (ObjCCategoryImplDecl *Impl
4355                               = cast<ObjCCategoryDecl>(D)->getImplementation())
4356      return MakeCXCursor(Impl, TU);
4357    return clang_getNullCursor();
4358
4359  case Decl::ObjCProtocol:
4360    if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4361      return MakeCXCursor(Def, TU);
4362    return clang_getNullCursor();
4363
4364  case Decl::ObjCInterface: {
4365    // There are two notions of a "definition" for an Objective-C
4366    // class: the interface and its implementation. When we resolved a
4367    // reference to an Objective-C class, produce the @interface as
4368    // the definition; when we were provided with the interface,
4369    // produce the @implementation as the definition.
4370    ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
4371    if (WasReference) {
4372      if (ObjCInterfaceDecl *Def = IFace->getDefinition())
4373        return MakeCXCursor(Def, TU);
4374    } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4375      return MakeCXCursor(Impl, TU);
4376    return clang_getNullCursor();
4377  }
4378
4379  case Decl::ObjCProperty:
4380    // FIXME: We don't really know where to find the
4381    // ObjCPropertyImplDecls that implement this property.
4382    return clang_getNullCursor();
4383
4384  case Decl::ObjCCompatibleAlias:
4385    if (ObjCInterfaceDecl *Class
4386          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4387      if (ObjCInterfaceDecl *Def = Class->getDefinition())
4388        return MakeCXCursor(Def, TU);
4389
4390    return clang_getNullCursor();
4391
4392  case Decl::Friend:
4393    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
4394      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4395    return clang_getNullCursor();
4396
4397  case Decl::FriendTemplate:
4398    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
4399      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4400    return clang_getNullCursor();
4401  }
4402
4403  return clang_getNullCursor();
4404}
4405
4406unsigned clang_isCursorDefinition(CXCursor C) {
4407  if (!clang_isDeclaration(C.kind))
4408    return 0;
4409
4410  return clang_getCursorDefinition(C) == C;
4411}
4412
4413CXCursor clang_getCanonicalCursor(CXCursor C) {
4414  if (!clang_isDeclaration(C.kind))
4415    return C;
4416
4417  if (Decl *D = getCursorDecl(C)) {
4418    if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4419      if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4420        return MakeCXCursor(CatD, getCursorTU(C));
4421
4422    if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4423      if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4424        return MakeCXCursor(IFD, getCursorTU(C));
4425
4426    return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4427  }
4428
4429  return C;
4430}
4431
4432int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4433  return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4434}
4435
4436unsigned clang_getNumOverloadedDecls(CXCursor C) {
4437  if (C.kind != CXCursor_OverloadedDeclRef)
4438    return 0;
4439
4440  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4441  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4442    return E->getNumDecls();
4443
4444  if (OverloadedTemplateStorage *S
4445                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4446    return S->size();
4447
4448  Decl *D = Storage.get<Decl*>();
4449  if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4450    return Using->shadow_size();
4451
4452  return 0;
4453}
4454
4455CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
4456  if (cursor.kind != CXCursor_OverloadedDeclRef)
4457    return clang_getNullCursor();
4458
4459  if (index >= clang_getNumOverloadedDecls(cursor))
4460    return clang_getNullCursor();
4461
4462  CXTranslationUnit TU = getCursorTU(cursor);
4463  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4464  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4465    return MakeCXCursor(E->decls_begin()[index], TU);
4466
4467  if (OverloadedTemplateStorage *S
4468                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4469    return MakeCXCursor(S->begin()[index], TU);
4470
4471  Decl *D = Storage.get<Decl*>();
4472  if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4473    // FIXME: This is, unfortunately, linear time.
4474    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4475    std::advance(Pos, index);
4476    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
4477  }
4478
4479  return clang_getNullCursor();
4480}
4481
4482void clang_getDefinitionSpellingAndExtent(CXCursor C,
4483                                          const char **startBuf,
4484                                          const char **endBuf,
4485                                          unsigned *startLine,
4486                                          unsigned *startColumn,
4487                                          unsigned *endLine,
4488                                          unsigned *endColumn) {
4489  assert(getCursorDecl(C) && "CXCursor has null decl");
4490  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
4491  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4492  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
4493
4494  SourceManager &SM = FD->getASTContext().getSourceManager();
4495  *startBuf = SM.getCharacterData(Body->getLBracLoc());
4496  *endBuf = SM.getCharacterData(Body->getRBracLoc());
4497  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4498  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4499  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4500  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4501}
4502
4503
4504CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4505                                                unsigned PieceIndex) {
4506  RefNamePieces Pieces;
4507
4508  switch (C.kind) {
4509  case CXCursor_MemberRefExpr:
4510    if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4511      Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4512                           E->getQualifierLoc().getSourceRange());
4513    break;
4514
4515  case CXCursor_DeclRefExpr:
4516    if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4517      Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4518                           E->getQualifierLoc().getSourceRange(),
4519                           E->getOptionalExplicitTemplateArgs());
4520    break;
4521
4522  case CXCursor_CallExpr:
4523    if (CXXOperatorCallExpr *OCE =
4524        dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4525      Expr *Callee = OCE->getCallee();
4526      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4527        Callee = ICE->getSubExpr();
4528
4529      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4530        Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4531                             DRE->getQualifierLoc().getSourceRange());
4532    }
4533    break;
4534
4535  default:
4536    break;
4537  }
4538
4539  if (Pieces.empty()) {
4540    if (PieceIndex == 0)
4541      return clang_getCursorExtent(C);
4542  } else if (PieceIndex < Pieces.size()) {
4543      SourceRange R = Pieces[PieceIndex];
4544      if (R.isValid())
4545        return cxloc::translateSourceRange(getCursorContext(C), R);
4546  }
4547
4548  return clang_getNullRange();
4549}
4550
4551void clang_enableStackTraces(void) {
4552  llvm::sys::PrintStackTraceOnErrorSignal();
4553}
4554
4555void clang_executeOnThread(void (*fn)(void*), void *user_data,
4556                           unsigned stack_size) {
4557  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4558}
4559
4560} // end: extern "C"
4561
4562//===----------------------------------------------------------------------===//
4563// Token-based Operations.
4564//===----------------------------------------------------------------------===//
4565
4566/* CXToken layout:
4567 *   int_data[0]: a CXTokenKind
4568 *   int_data[1]: starting token location
4569 *   int_data[2]: token length
4570 *   int_data[3]: reserved
4571 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
4572 *   otherwise unused.
4573 */
4574extern "C" {
4575
4576CXTokenKind clang_getTokenKind(CXToken CXTok) {
4577  return static_cast<CXTokenKind>(CXTok.int_data[0]);
4578}
4579
4580CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4581  switch (clang_getTokenKind(CXTok)) {
4582  case CXToken_Identifier:
4583  case CXToken_Keyword:
4584    // We know we have an IdentifierInfo*, so use that.
4585    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4586                            ->getNameStart());
4587
4588  case CXToken_Literal: {
4589    // We have stashed the starting pointer in the ptr_data field. Use it.
4590    const char *Text = static_cast<const char *>(CXTok.ptr_data);
4591    return createCXString(StringRef(Text, CXTok.int_data[2]));
4592  }
4593
4594  case CXToken_Punctuation:
4595  case CXToken_Comment:
4596    break;
4597  }
4598
4599  // We have to find the starting buffer pointer the hard way, by
4600  // deconstructing the source location.
4601  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4602  if (!CXXUnit)
4603    return createCXString("");
4604
4605  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4606  std::pair<FileID, unsigned> LocInfo
4607    = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
4608  bool Invalid = false;
4609  StringRef Buffer
4610    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4611  if (Invalid)
4612    return createCXString("");
4613
4614  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
4615}
4616
4617CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
4618  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4619  if (!CXXUnit)
4620    return clang_getNullLocation();
4621
4622  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4623                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4624}
4625
4626CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
4627  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4628  if (!CXXUnit)
4629    return clang_getNullRange();
4630
4631  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
4632                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4633}
4634
4635static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4636                      SmallVectorImpl<CXToken> &CXTokens) {
4637  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4638  std::pair<FileID, unsigned> BeginLocInfo
4639    = SourceMgr.getDecomposedLoc(Range.getBegin());
4640  std::pair<FileID, unsigned> EndLocInfo
4641    = SourceMgr.getDecomposedLoc(Range.getEnd());
4642
4643  // Cannot tokenize across files.
4644  if (BeginLocInfo.first != EndLocInfo.first)
4645    return;
4646
4647  // Create a lexer
4648  bool Invalid = false;
4649  StringRef Buffer
4650    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4651  if (Invalid)
4652    return;
4653
4654  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4655            CXXUnit->getASTContext().getLangOpts(),
4656            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
4657  Lex.SetCommentRetentionState(true);
4658
4659  // Lex tokens until we hit the end of the range.
4660  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
4661  Token Tok;
4662  bool previousWasAt = false;
4663  do {
4664    // Lex the next token
4665    Lex.LexFromRawLexer(Tok);
4666    if (Tok.is(tok::eof))
4667      break;
4668
4669    // Initialize the CXToken.
4670    CXToken CXTok;
4671
4672    //   - Common fields
4673    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4674    CXTok.int_data[2] = Tok.getLength();
4675    CXTok.int_data[3] = 0;
4676
4677    //   - Kind-specific fields
4678    if (Tok.isLiteral()) {
4679      CXTok.int_data[0] = CXToken_Literal;
4680      CXTok.ptr_data = (void *)Tok.getLiteralData();
4681    } else if (Tok.is(tok::raw_identifier)) {
4682      // Lookup the identifier to determine whether we have a keyword.
4683      IdentifierInfo *II
4684        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4685
4686      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4687        CXTok.int_data[0] = CXToken_Keyword;
4688      }
4689      else {
4690        CXTok.int_data[0] = Tok.is(tok::identifier)
4691          ? CXToken_Identifier
4692          : CXToken_Keyword;
4693      }
4694      CXTok.ptr_data = II;
4695    } else if (Tok.is(tok::comment)) {
4696      CXTok.int_data[0] = CXToken_Comment;
4697      CXTok.ptr_data = 0;
4698    } else {
4699      CXTok.int_data[0] = CXToken_Punctuation;
4700      CXTok.ptr_data = 0;
4701    }
4702    CXTokens.push_back(CXTok);
4703    previousWasAt = Tok.is(tok::at);
4704  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4705}
4706
4707void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4708                    CXToken **Tokens, unsigned *NumTokens) {
4709  if (Tokens)
4710    *Tokens = 0;
4711  if (NumTokens)
4712    *NumTokens = 0;
4713
4714  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4715  if (!CXXUnit || !Tokens || !NumTokens)
4716    return;
4717
4718  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4719
4720  SourceRange R = cxloc::translateCXSourceRange(Range);
4721  if (R.isInvalid())
4722    return;
4723
4724  SmallVector<CXToken, 32> CXTokens;
4725  getTokens(CXXUnit, R, CXTokens);
4726
4727  if (CXTokens.empty())
4728    return;
4729
4730  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4731  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4732  *NumTokens = CXTokens.size();
4733}
4734
4735void clang_disposeTokens(CXTranslationUnit TU,
4736                         CXToken *Tokens, unsigned NumTokens) {
4737  free(Tokens);
4738}
4739
4740} // end: extern "C"
4741
4742//===----------------------------------------------------------------------===//
4743// Token annotation APIs.
4744//===----------------------------------------------------------------------===//
4745
4746typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
4747static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4748                                                     CXCursor parent,
4749                                                     CXClientData client_data);
4750namespace {
4751class AnnotateTokensWorker {
4752  AnnotateTokensData &Annotated;
4753  CXToken *Tokens;
4754  CXCursor *Cursors;
4755  unsigned NumTokens;
4756  unsigned TokIdx;
4757  unsigned PreprocessingTokIdx;
4758  CursorVisitor AnnotateVis;
4759  SourceManager &SrcMgr;
4760  bool HasContextSensitiveKeywords;
4761
4762  bool MoreTokens() const { return TokIdx < NumTokens; }
4763  unsigned NextToken() const { return TokIdx; }
4764  void AdvanceToken() { ++TokIdx; }
4765  SourceLocation GetTokenLoc(unsigned tokI) {
4766    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4767  }
4768  bool isFunctionMacroToken(unsigned tokI) const {
4769    return Tokens[tokI].int_data[3] != 0;
4770  }
4771  SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
4772    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4773  }
4774
4775  void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
4776  void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4777                                             SourceRange);
4778
4779public:
4780  AnnotateTokensWorker(AnnotateTokensData &annotated,
4781                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
4782                       CXTranslationUnit tu, SourceRange RegionOfInterest)
4783    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
4784      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4785      AnnotateVis(tu,
4786                  AnnotateTokensVisitor, this,
4787                  /*VisitPreprocessorLast=*/true,
4788                  /*VisitIncludedEntities=*/false,
4789                  RegionOfInterest),
4790      SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4791      HasContextSensitiveKeywords(false) { }
4792
4793  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4794  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4795  void AnnotateTokens();
4796
4797  /// \brief Determine whether the annotator saw any cursors that have
4798  /// context-sensitive keywords.
4799  bool hasContextSensitiveKeywords() const {
4800    return HasContextSensitiveKeywords;
4801  }
4802};
4803}
4804
4805void AnnotateTokensWorker::AnnotateTokens() {
4806  // Walk the AST within the region of interest, annotating tokens
4807  // along the way.
4808  AnnotateVis.visitFileRegion();
4809
4810  for (unsigned I = 0 ; I < TokIdx ; ++I) {
4811    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4812    if (Pos != Annotated.end() &&
4813        (clang_isInvalid(Cursors[I].kind) ||
4814         Pos->second.kind != CXCursor_PreprocessingDirective))
4815      Cursors[I] = Pos->second;
4816  }
4817
4818  // Finish up annotating any tokens left.
4819  if (!MoreTokens())
4820    return;
4821
4822  const CXCursor &C = clang_getNullCursor();
4823  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4824    if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4825      continue;
4826
4827    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4828    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4829  }
4830}
4831
4832/// \brief It annotates and advances tokens with a cursor until the comparison
4833//// between the cursor location and the source range is the same as
4834/// \arg compResult.
4835///
4836/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4837/// Pass RangeOverlap to annotate tokens inside a range.
4838void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4839                                               RangeComparisonResult compResult,
4840                                               SourceRange range) {
4841  while (MoreTokens()) {
4842    const unsigned I = NextToken();
4843    if (isFunctionMacroToken(I))
4844      return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
4845
4846    SourceLocation TokLoc = GetTokenLoc(I);
4847    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4848      Cursors[I] = updateC;
4849      AdvanceToken();
4850      continue;
4851    }
4852    break;
4853  }
4854}
4855
4856/// \brief Special annotation handling for macro argument tokens.
4857void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4858                                               CXCursor updateC,
4859                                               RangeComparisonResult compResult,
4860                                               SourceRange range) {
4861  assert(MoreTokens());
4862  assert(isFunctionMacroToken(NextToken()) &&
4863         "Should be called only for macro arg tokens");
4864
4865  // This works differently than annotateAndAdvanceTokens; because expanded
4866  // macro arguments can have arbitrary translation-unit source order, we do not
4867  // advance the token index one by one until a token fails the range test.
4868  // We only advance once past all of the macro arg tokens if all of them
4869  // pass the range test. If one of them fails we keep the token index pointing
4870  // at the start of the macro arg tokens so that the failing token will be
4871  // annotated by a subsequent annotation try.
4872
4873  bool atLeastOneCompFail = false;
4874
4875  unsigned I = NextToken();
4876  for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4877    SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
4878    if (TokLoc.isFileID())
4879      continue; // not macro arg token, it's parens or comma.
4880    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4881      if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4882        Cursors[I] = updateC;
4883    } else
4884      atLeastOneCompFail = true;
4885  }
4886
4887  if (!atLeastOneCompFail)
4888    TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4889}
4890
4891enum CXChildVisitResult
4892AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
4893  CXSourceLocation Loc = clang_getCursorLocation(cursor);
4894  SourceRange cursorRange = getRawCursorExtent(cursor);
4895  if (cursorRange.isInvalid())
4896    return CXChildVisit_Recurse;
4897
4898  if (!HasContextSensitiveKeywords) {
4899    // Objective-C properties can have context-sensitive keywords.
4900    if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4901      if (ObjCPropertyDecl *Property
4902                  = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4903        HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4904    }
4905    // Objective-C methods can have context-sensitive keywords.
4906    else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4907             cursor.kind == CXCursor_ObjCClassMethodDecl) {
4908      if (ObjCMethodDecl *Method
4909            = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4910        if (Method->getObjCDeclQualifier())
4911          HasContextSensitiveKeywords = true;
4912        else {
4913          for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4914                                           PEnd = Method->param_end();
4915               P != PEnd; ++P) {
4916            if ((*P)->getObjCDeclQualifier()) {
4917              HasContextSensitiveKeywords = true;
4918              break;
4919            }
4920          }
4921        }
4922      }
4923    }
4924    // C++ methods can have context-sensitive keywords.
4925    else if (cursor.kind == CXCursor_CXXMethod) {
4926      if (CXXMethodDecl *Method
4927                  = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4928        if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4929          HasContextSensitiveKeywords = true;
4930      }
4931    }
4932    // C++ classes can have context-sensitive keywords.
4933    else if (cursor.kind == CXCursor_StructDecl ||
4934             cursor.kind == CXCursor_ClassDecl ||
4935             cursor.kind == CXCursor_ClassTemplate ||
4936             cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4937      if (Decl *D = getCursorDecl(cursor))
4938        if (D->hasAttr<FinalAttr>())
4939          HasContextSensitiveKeywords = true;
4940    }
4941  }
4942
4943  if (clang_isPreprocessing(cursor.kind)) {
4944    // For macro expansions, just note where the beginning of the macro
4945    // expansion occurs.
4946    if (cursor.kind == CXCursor_MacroExpansion) {
4947      Annotated[Loc.int_data] = cursor;
4948      return CXChildVisit_Recurse;
4949    }
4950
4951    // Items in the preprocessing record are kept separate from items in
4952    // declarations, so we keep a separate token index.
4953    unsigned SavedTokIdx = TokIdx;
4954    TokIdx = PreprocessingTokIdx;
4955
4956    // Skip tokens up until we catch up to the beginning of the preprocessing
4957    // entry.
4958    while (MoreTokens()) {
4959      const unsigned I = NextToken();
4960      SourceLocation TokLoc = GetTokenLoc(I);
4961      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4962      case RangeBefore:
4963        AdvanceToken();
4964        continue;
4965      case RangeAfter:
4966      case RangeOverlap:
4967        break;
4968      }
4969      break;
4970    }
4971
4972    // Look at all of the tokens within this range.
4973    while (MoreTokens()) {
4974      const unsigned I = NextToken();
4975      SourceLocation TokLoc = GetTokenLoc(I);
4976      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4977      case RangeBefore:
4978        llvm_unreachable("Infeasible");
4979      case RangeAfter:
4980        break;
4981      case RangeOverlap:
4982        Cursors[I] = cursor;
4983        AdvanceToken();
4984        continue;
4985      }
4986      break;
4987    }
4988
4989    // Save the preprocessing token index; restore the non-preprocessing
4990    // token index.
4991    PreprocessingTokIdx = TokIdx;
4992    TokIdx = SavedTokIdx;
4993    return CXChildVisit_Recurse;
4994  }
4995
4996  if (cursorRange.isInvalid())
4997    return CXChildVisit_Continue;
4998
4999  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5000
5001  // Adjust the annotated range based specific declarations.
5002  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5003  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
5004    Decl *D = cxcursor::getCursorDecl(cursor);
5005
5006    SourceLocation StartLoc;
5007    if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
5008      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5009        StartLoc = TI->getTypeLoc().getLocStart();
5010    } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
5011      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5012        StartLoc = TI->getTypeLoc().getLocStart();
5013    }
5014
5015    if (StartLoc.isValid() && L.isValid() &&
5016        SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5017      cursorRange.setBegin(StartLoc);
5018  }
5019
5020  // If the location of the cursor occurs within a macro instantiation, record
5021  // the spelling location of the cursor in our annotation map.  We can then
5022  // paper over the token labelings during a post-processing step to try and
5023  // get cursor mappings for tokens that are the *arguments* of a macro
5024  // instantiation.
5025  if (L.isMacroID()) {
5026    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5027    // Only invalidate the old annotation if it isn't part of a preprocessing
5028    // directive.  Here we assume that the default construction of CXCursor
5029    // results in CXCursor.kind being an initialized value (i.e., 0).  If
5030    // this isn't the case, we can fix by doing lookup + insertion.
5031
5032    CXCursor &oldC = Annotated[rawEncoding];
5033    if (!clang_isPreprocessing(oldC.kind))
5034      oldC = cursor;
5035  }
5036
5037  const enum CXCursorKind K = clang_getCursorKind(parent);
5038  const CXCursor updateC =
5039    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5040     ? clang_getNullCursor() : parent;
5041
5042  annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
5043
5044  // Avoid having the cursor of an expression "overwrite" the annotation of the
5045  // variable declaration that it belongs to.
5046  // This can happen for C++ constructor expressions whose range generally
5047  // include the variable declaration, e.g.:
5048  //  MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5049  if (clang_isExpression(cursorK)) {
5050    Expr *E = getCursorExpr(cursor);
5051    if (Decl *D = getCursorParentDecl(cursor)) {
5052      const unsigned I = NextToken();
5053      if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5054          E->getLocStart() == D->getLocation() &&
5055          E->getLocStart() == GetTokenLoc(I)) {
5056        Cursors[I] = updateC;
5057        AdvanceToken();
5058      }
5059    }
5060  }
5061
5062  // Visit children to get their cursor information.
5063  const unsigned BeforeChildren = NextToken();
5064  VisitChildren(cursor);
5065  const unsigned AfterChildren = NextToken();
5066
5067  // Scan the tokens that are at the end of the cursor, but are not captured
5068  // but the child cursors.
5069  annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
5070
5071  // Scan the tokens that are at the beginning of the cursor, but are not
5072  // capture by the child cursors.
5073  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5074    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5075      break;
5076
5077    Cursors[I] = cursor;
5078  }
5079
5080  return CXChildVisit_Continue;
5081}
5082
5083static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5084                                                     CXCursor parent,
5085                                                     CXClientData client_data) {
5086  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5087}
5088
5089namespace {
5090
5091/// \brief Uses the macro expansions in the preprocessing record to find
5092/// and mark tokens that are macro arguments. This info is used by the
5093/// AnnotateTokensWorker.
5094class MarkMacroArgTokensVisitor {
5095  SourceManager &SM;
5096  CXToken *Tokens;
5097  unsigned NumTokens;
5098  unsigned CurIdx;
5099
5100public:
5101  MarkMacroArgTokensVisitor(SourceManager &SM,
5102                            CXToken *tokens, unsigned numTokens)
5103    : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5104
5105  CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5106    if (cursor.kind != CXCursor_MacroExpansion)
5107      return CXChildVisit_Continue;
5108
5109    SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5110    if (macroRange.getBegin() == macroRange.getEnd())
5111      return CXChildVisit_Continue; // it's not a function macro.
5112
5113    for (; CurIdx < NumTokens; ++CurIdx) {
5114      if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5115                                        macroRange.getBegin()))
5116        break;
5117    }
5118
5119    if (CurIdx == NumTokens)
5120      return CXChildVisit_Break;
5121
5122    for (; CurIdx < NumTokens; ++CurIdx) {
5123      SourceLocation tokLoc = getTokenLoc(CurIdx);
5124      if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5125        break;
5126
5127      setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
5128    }
5129
5130    if (CurIdx == NumTokens)
5131      return CXChildVisit_Break;
5132
5133    return CXChildVisit_Continue;
5134  }
5135
5136private:
5137  SourceLocation getTokenLoc(unsigned tokI) {
5138    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5139  }
5140
5141  void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
5142    // The third field is reserved and currently not used. Use it here
5143    // to mark macro arg expanded tokens with their expanded locations.
5144    Tokens[tokI].int_data[3] = loc.getRawEncoding();
5145  }
5146};
5147
5148} // end anonymous namespace
5149
5150static CXChildVisitResult
5151MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5152                                  CXClientData client_data) {
5153  return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5154                                                                     parent);
5155}
5156
5157namespace {
5158  struct clang_annotateTokens_Data {
5159    CXTranslationUnit TU;
5160    ASTUnit *CXXUnit;
5161    CXToken *Tokens;
5162    unsigned NumTokens;
5163    CXCursor *Cursors;
5164  };
5165}
5166
5167static void annotatePreprocessorTokens(CXTranslationUnit TU,
5168                                       SourceRange RegionOfInterest,
5169                                       AnnotateTokensData &Annotated) {
5170  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5171
5172  SourceManager &SourceMgr = CXXUnit->getSourceManager();
5173  std::pair<FileID, unsigned> BeginLocInfo
5174    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5175  std::pair<FileID, unsigned> EndLocInfo
5176    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5177
5178  if (BeginLocInfo.first != EndLocInfo.first)
5179    return;
5180
5181  StringRef Buffer;
5182  bool Invalid = false;
5183  Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5184  if (Buffer.empty() || Invalid)
5185    return;
5186
5187  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5188            CXXUnit->getASTContext().getLangOpts(),
5189            Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5190            Buffer.end());
5191  Lex.SetCommentRetentionState(true);
5192
5193  // Lex tokens in raw mode until we hit the end of the range, to avoid
5194  // entering #includes or expanding macros.
5195  while (true) {
5196    Token Tok;
5197    Lex.LexFromRawLexer(Tok);
5198
5199  reprocess:
5200    if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5201      // We have found a preprocessing directive. Gobble it up so that we
5202      // don't see it while preprocessing these tokens later, but keep track
5203      // of all of the token locations inside this preprocessing directive so
5204      // that we can annotate them appropriately.
5205      //
5206      // FIXME: Some simple tests here could identify macro definitions and
5207      // #undefs, to provide specific cursor kinds for those.
5208      SmallVector<SourceLocation, 32> Locations;
5209      do {
5210        Locations.push_back(Tok.getLocation());
5211        Lex.LexFromRawLexer(Tok);
5212      } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5213
5214      using namespace cxcursor;
5215      CXCursor Cursor
5216      = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5217                                                     Locations.back()),
5218                                         TU);
5219      for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5220        Annotated[Locations[I].getRawEncoding()] = Cursor;
5221      }
5222
5223      if (Tok.isAtStartOfLine())
5224        goto reprocess;
5225
5226      continue;
5227    }
5228
5229    if (Tok.is(tok::eof))
5230      break;
5231  }
5232}
5233
5234// This gets run a separate thread to avoid stack blowout.
5235static void clang_annotateTokensImpl(void *UserData) {
5236  CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5237  ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5238  CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5239  const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5240  CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5241
5242  CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5243  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
5244    setThreadBackgroundPriority();
5245
5246  // Determine the region of interest, which contains all of the tokens.
5247  SourceRange RegionOfInterest;
5248  RegionOfInterest.setBegin(
5249    cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5250  RegionOfInterest.setEnd(
5251    cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5252                                                         Tokens[NumTokens-1])));
5253
5254  // A mapping from the source locations found when re-lexing or traversing the
5255  // region of interest to the corresponding cursors.
5256  AnnotateTokensData Annotated;
5257
5258  // Relex the tokens within the source range to look for preprocessing
5259  // directives.
5260  annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
5261
5262  if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5263    // Search and mark tokens that are macro argument expansions.
5264    MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5265                                      Tokens, NumTokens);
5266    CursorVisitor MacroArgMarker(TU,
5267                                 MarkMacroArgTokensVisitorDelegate, &Visitor,
5268                                 /*VisitPreprocessorLast=*/true,
5269                                 /*VisitIncludedEntities=*/false,
5270                                 RegionOfInterest);
5271    MacroArgMarker.visitPreprocessedEntitiesInRegion();
5272  }
5273
5274  // Annotate all of the source locations in the region of interest that map to
5275  // a specific cursor.
5276  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5277                         TU, RegionOfInterest);
5278
5279  // FIXME: We use a ridiculous stack size here because the data-recursion
5280  // algorithm uses a large stack frame than the non-data recursive version,
5281  // and AnnotationTokensWorker currently transforms the data-recursion
5282  // algorithm back into a traditional recursion by explicitly calling
5283  // VisitChildren().  We will need to remove this explicit recursive call.
5284  W.AnnotateTokens();
5285
5286  // If we ran into any entities that involve context-sensitive keywords,
5287  // take another pass through the tokens to mark them as such.
5288  if (W.hasContextSensitiveKeywords()) {
5289    for (unsigned I = 0; I != NumTokens; ++I) {
5290      if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5291        continue;
5292
5293      if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5294        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5295        if (ObjCPropertyDecl *Property
5296            = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5297          if (Property->getPropertyAttributesAsWritten() != 0 &&
5298              llvm::StringSwitch<bool>(II->getName())
5299              .Case("readonly", true)
5300              .Case("assign", true)
5301              .Case("unsafe_unretained", true)
5302              .Case("readwrite", true)
5303              .Case("retain", true)
5304              .Case("copy", true)
5305              .Case("nonatomic", true)
5306              .Case("atomic", true)
5307              .Case("getter", true)
5308              .Case("setter", true)
5309              .Case("strong", true)
5310              .Case("weak", true)
5311              .Default(false))
5312            Tokens[I].int_data[0] = CXToken_Keyword;
5313        }
5314        continue;
5315      }
5316
5317      if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5318          Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5319        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5320        if (llvm::StringSwitch<bool>(II->getName())
5321            .Case("in", true)
5322            .Case("out", true)
5323            .Case("inout", true)
5324            .Case("oneway", true)
5325            .Case("bycopy", true)
5326            .Case("byref", true)
5327            .Default(false))
5328          Tokens[I].int_data[0] = CXToken_Keyword;
5329        continue;
5330      }
5331
5332      if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5333          Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5334        Tokens[I].int_data[0] = CXToken_Keyword;
5335        continue;
5336      }
5337    }
5338  }
5339}
5340
5341extern "C" {
5342
5343void clang_annotateTokens(CXTranslationUnit TU,
5344                          CXToken *Tokens, unsigned NumTokens,
5345                          CXCursor *Cursors) {
5346
5347  if (NumTokens == 0 || !Tokens || !Cursors)
5348    return;
5349
5350  // Any token we don't specifically annotate will have a NULL cursor.
5351  CXCursor C = clang_getNullCursor();
5352  for (unsigned I = 0; I != NumTokens; ++I)
5353    Cursors[I] = C;
5354
5355  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5356  if (!CXXUnit)
5357    return;
5358
5359  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5360
5361  clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
5362  llvm::CrashRecoveryContext CRC;
5363  if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
5364                 GetSafetyThreadStackSize() * 2)) {
5365    fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5366  }
5367}
5368
5369} // end: extern "C"
5370
5371//===----------------------------------------------------------------------===//
5372// Operations for querying linkage of a cursor.
5373//===----------------------------------------------------------------------===//
5374
5375extern "C" {
5376CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
5377  if (!clang_isDeclaration(cursor.kind))
5378    return CXLinkage_Invalid;
5379
5380  Decl *D = cxcursor::getCursorDecl(cursor);
5381  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5382    switch (ND->getLinkage()) {
5383      case NoLinkage: return CXLinkage_NoLinkage;
5384      case InternalLinkage: return CXLinkage_Internal;
5385      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5386      case ExternalLinkage: return CXLinkage_External;
5387    };
5388
5389  return CXLinkage_Invalid;
5390}
5391} // end: extern "C"
5392
5393//===----------------------------------------------------------------------===//
5394// Operations for querying language of a cursor.
5395//===----------------------------------------------------------------------===//
5396
5397static CXLanguageKind getDeclLanguage(const Decl *D) {
5398  if (!D)
5399    return CXLanguage_C;
5400
5401  switch (D->getKind()) {
5402    default:
5403      break;
5404    case Decl::ImplicitParam:
5405    case Decl::ObjCAtDefsField:
5406    case Decl::ObjCCategory:
5407    case Decl::ObjCCategoryImpl:
5408    case Decl::ObjCCompatibleAlias:
5409    case Decl::ObjCImplementation:
5410    case Decl::ObjCInterface:
5411    case Decl::ObjCIvar:
5412    case Decl::ObjCMethod:
5413    case Decl::ObjCProperty:
5414    case Decl::ObjCPropertyImpl:
5415    case Decl::ObjCProtocol:
5416      return CXLanguage_ObjC;
5417    case Decl::CXXConstructor:
5418    case Decl::CXXConversion:
5419    case Decl::CXXDestructor:
5420    case Decl::CXXMethod:
5421    case Decl::CXXRecord:
5422    case Decl::ClassTemplate:
5423    case Decl::ClassTemplatePartialSpecialization:
5424    case Decl::ClassTemplateSpecialization:
5425    case Decl::Friend:
5426    case Decl::FriendTemplate:
5427    case Decl::FunctionTemplate:
5428    case Decl::LinkageSpec:
5429    case Decl::Namespace:
5430    case Decl::NamespaceAlias:
5431    case Decl::NonTypeTemplateParm:
5432    case Decl::StaticAssert:
5433    case Decl::TemplateTemplateParm:
5434    case Decl::TemplateTypeParm:
5435    case Decl::UnresolvedUsingTypename:
5436    case Decl::UnresolvedUsingValue:
5437    case Decl::Using:
5438    case Decl::UsingDirective:
5439    case Decl::UsingShadow:
5440      return CXLanguage_CPlusPlus;
5441  }
5442
5443  return CXLanguage_C;
5444}
5445
5446extern "C" {
5447
5448enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5449  if (clang_isDeclaration(cursor.kind))
5450    if (Decl *D = cxcursor::getCursorDecl(cursor)) {
5451      if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
5452        return CXAvailability_Available;
5453
5454      switch (D->getAvailability()) {
5455      case AR_Available:
5456      case AR_NotYetIntroduced:
5457        return CXAvailability_Available;
5458
5459      case AR_Deprecated:
5460        return CXAvailability_Deprecated;
5461
5462      case AR_Unavailable:
5463        return CXAvailability_NotAvailable;
5464      }
5465    }
5466
5467  return CXAvailability_Available;
5468}
5469
5470CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5471  if (clang_isDeclaration(cursor.kind))
5472    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5473
5474  return CXLanguage_Invalid;
5475}
5476
5477 /// \brief If the given cursor is the "templated" declaration
5478 /// descibing a class or function template, return the class or
5479 /// function template.
5480static Decl *maybeGetTemplateCursor(Decl *D) {
5481  if (!D)
5482    return 0;
5483
5484  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5485    if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5486      return FunTmpl;
5487
5488  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5489    if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5490      return ClassTmpl;
5491
5492  return D;
5493}
5494
5495CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5496  if (clang_isDeclaration(cursor.kind)) {
5497    if (Decl *D = getCursorDecl(cursor)) {
5498      DeclContext *DC = D->getDeclContext();
5499      if (!DC)
5500        return clang_getNullCursor();
5501
5502      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5503                          getCursorTU(cursor));
5504    }
5505  }
5506
5507  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5508    if (Decl *D = getCursorDecl(cursor))
5509      return MakeCXCursor(D, getCursorTU(cursor));
5510  }
5511
5512  return clang_getNullCursor();
5513}
5514
5515CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5516  if (clang_isDeclaration(cursor.kind)) {
5517    if (Decl *D = getCursorDecl(cursor)) {
5518      DeclContext *DC = D->getLexicalDeclContext();
5519      if (!DC)
5520        return clang_getNullCursor();
5521
5522      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5523                          getCursorTU(cursor));
5524    }
5525  }
5526
5527  // FIXME: Note that we can't easily compute the lexical context of a
5528  // statement or expression, so we return nothing.
5529  return clang_getNullCursor();
5530}
5531
5532void clang_getOverriddenCursors(CXCursor cursor,
5533                                CXCursor **overridden,
5534                                unsigned *num_overridden) {
5535  if (overridden)
5536    *overridden = 0;
5537  if (num_overridden)
5538    *num_overridden = 0;
5539  if (!overridden || !num_overridden)
5540    return;
5541  if (!clang_isDeclaration(cursor.kind))
5542    return;
5543
5544  SmallVector<CXCursor, 8> Overridden;
5545  cxcursor::getOverriddenCursors(cursor, Overridden);
5546
5547  // Don't allocate memory if we have no overriden cursors.
5548  if (Overridden.size() == 0)
5549    return;
5550
5551  *num_overridden = Overridden.size();
5552  *overridden = new CXCursor [Overridden.size()];
5553  std::copy(Overridden.begin(), Overridden.end(), *overridden);
5554}
5555
5556void clang_disposeOverriddenCursors(CXCursor *overridden) {
5557  delete [] overridden;
5558}
5559
5560CXFile clang_getIncludedFile(CXCursor cursor) {
5561  if (cursor.kind != CXCursor_InclusionDirective)
5562    return 0;
5563
5564  InclusionDirective *ID = getCursorInclusionDirective(cursor);
5565  return (void *)ID->getFile();
5566}
5567
5568} // end: extern "C"
5569
5570
5571//===----------------------------------------------------------------------===//
5572// C++ AST instrospection.
5573//===----------------------------------------------------------------------===//
5574
5575extern "C" {
5576unsigned clang_CXXMethod_isStatic(CXCursor C) {
5577  if (!clang_isDeclaration(C.kind))
5578    return 0;
5579
5580  CXXMethodDecl *Method = 0;
5581  Decl *D = cxcursor::getCursorDecl(C);
5582  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5583    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5584  else
5585    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5586  return (Method && Method->isStatic()) ? 1 : 0;
5587}
5588
5589unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5590  if (!clang_isDeclaration(C.kind))
5591    return 0;
5592
5593  CXXMethodDecl *Method = 0;
5594  Decl *D = cxcursor::getCursorDecl(C);
5595  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5596    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5597  else
5598    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5599  return (Method && Method->isVirtual()) ? 1 : 0;
5600}
5601} // end: extern "C"
5602
5603//===----------------------------------------------------------------------===//
5604// Attribute introspection.
5605//===----------------------------------------------------------------------===//
5606
5607extern "C" {
5608CXType clang_getIBOutletCollectionType(CXCursor C) {
5609  if (C.kind != CXCursor_IBOutletCollectionAttr)
5610    return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
5611
5612  IBOutletCollectionAttr *A =
5613    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5614
5615  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
5616}
5617} // end: extern "C"
5618
5619//===----------------------------------------------------------------------===//
5620// Inspecting memory usage.
5621//===----------------------------------------------------------------------===//
5622
5623typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
5624
5625static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5626                                              enum CXTUResourceUsageKind k,
5627                                              unsigned long amount) {
5628  CXTUResourceUsageEntry entry = { k, amount };
5629  entries.push_back(entry);
5630}
5631
5632extern "C" {
5633
5634const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
5635  const char *str = "";
5636  switch (kind) {
5637    case CXTUResourceUsage_AST:
5638      str = "ASTContext: expressions, declarations, and types";
5639      break;
5640    case CXTUResourceUsage_Identifiers:
5641      str = "ASTContext: identifiers";
5642      break;
5643    case CXTUResourceUsage_Selectors:
5644      str = "ASTContext: selectors";
5645      break;
5646    case CXTUResourceUsage_GlobalCompletionResults:
5647      str = "Code completion: cached global results";
5648      break;
5649    case CXTUResourceUsage_SourceManagerContentCache:
5650      str = "SourceManager: content cache allocator";
5651      break;
5652    case CXTUResourceUsage_AST_SideTables:
5653      str = "ASTContext: side tables";
5654      break;
5655    case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5656      str = "SourceManager: malloc'ed memory buffers";
5657      break;
5658    case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5659      str = "SourceManager: mmap'ed memory buffers";
5660      break;
5661    case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5662      str = "ExternalASTSource: malloc'ed memory buffers";
5663      break;
5664    case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5665      str = "ExternalASTSource: mmap'ed memory buffers";
5666      break;
5667    case CXTUResourceUsage_Preprocessor:
5668      str = "Preprocessor: malloc'ed memory";
5669      break;
5670    case CXTUResourceUsage_PreprocessingRecord:
5671      str = "Preprocessor: PreprocessingRecord";
5672      break;
5673    case CXTUResourceUsage_SourceManager_DataStructures:
5674      str = "SourceManager: data structures and tables";
5675      break;
5676    case CXTUResourceUsage_Preprocessor_HeaderSearch:
5677      str = "Preprocessor: header search tables";
5678      break;
5679  }
5680  return str;
5681}
5682
5683CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
5684  if (!TU) {
5685    CXTUResourceUsage usage = { (void*) 0, 0, 0 };
5686    return usage;
5687  }
5688
5689  ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5690  OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5691  ASTContext &astContext = astUnit->getASTContext();
5692
5693  // How much memory is used by AST nodes and types?
5694  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
5695    (unsigned long) astContext.getASTAllocatedMemory());
5696
5697  // How much memory is used by identifiers?
5698  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
5699    (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5700
5701  // How much memory is used for selectors?
5702  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
5703    (unsigned long) astContext.Selectors.getTotalMemory());
5704
5705  // How much memory is used by ASTContext's side tables?
5706  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5707    (unsigned long) astContext.getSideTableAllocatedMemory());
5708
5709  // How much memory is used for caching global code completion results?
5710  unsigned long completionBytes = 0;
5711  if (GlobalCodeCompletionAllocator *completionAllocator =
5712      astUnit->getCachedCompletionAllocator().getPtr()) {
5713    completionBytes = completionAllocator->getTotalMemory();
5714  }
5715  createCXTUResourceUsageEntry(*entries,
5716                               CXTUResourceUsage_GlobalCompletionResults,
5717                               completionBytes);
5718
5719  // How much memory is being used by SourceManager's content cache?
5720  createCXTUResourceUsageEntry(*entries,
5721          CXTUResourceUsage_SourceManagerContentCache,
5722          (unsigned long) astContext.getSourceManager().getContentCacheSize());
5723
5724  // How much memory is being used by the MemoryBuffer's in SourceManager?
5725  const SourceManager::MemoryBufferSizes &srcBufs =
5726    astUnit->getSourceManager().getMemoryBufferSizes();
5727
5728  createCXTUResourceUsageEntry(*entries,
5729                               CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5730                               (unsigned long) srcBufs.malloc_bytes);
5731  createCXTUResourceUsageEntry(*entries,
5732                               CXTUResourceUsage_SourceManager_Membuffer_MMap,
5733                               (unsigned long) srcBufs.mmap_bytes);
5734  createCXTUResourceUsageEntry(*entries,
5735                               CXTUResourceUsage_SourceManager_DataStructures,
5736                               (unsigned long) astContext.getSourceManager()
5737                                .getDataStructureSizes());
5738
5739  // How much memory is being used by the ExternalASTSource?
5740  if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5741    const ExternalASTSource::MemoryBufferSizes &sizes =
5742      esrc->getMemoryBufferSizes();
5743
5744    createCXTUResourceUsageEntry(*entries,
5745      CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5746                                 (unsigned long) sizes.malloc_bytes);
5747    createCXTUResourceUsageEntry(*entries,
5748      CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5749                                 (unsigned long) sizes.mmap_bytes);
5750  }
5751
5752  // How much memory is being used by the Preprocessor?
5753  Preprocessor &pp = astUnit->getPreprocessor();
5754  createCXTUResourceUsageEntry(*entries,
5755                               CXTUResourceUsage_Preprocessor,
5756                               pp.getTotalMemory());
5757
5758  if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5759    createCXTUResourceUsageEntry(*entries,
5760                                 CXTUResourceUsage_PreprocessingRecord,
5761                                 pRec->getTotalMemory());
5762  }
5763
5764  createCXTUResourceUsageEntry(*entries,
5765                               CXTUResourceUsage_Preprocessor_HeaderSearch,
5766                               pp.getHeaderSearchInfo().getTotalMemory());
5767
5768  CXTUResourceUsage usage = { (void*) entries.get(),
5769                            (unsigned) entries->size(),
5770                            entries->size() ? &(*entries)[0] : 0 };
5771  entries.take();
5772  return usage;
5773}
5774
5775void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
5776  if (usage.data)
5777    delete (MemUsageEntries*) usage.data;
5778}
5779
5780} // end extern "C"
5781
5782void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5783  CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5784  for (unsigned I = 0; I != Usage.numEntries; ++I)
5785    fprintf(stderr, "  %s: %lu\n",
5786            clang_getTUResourceUsageName(Usage.entries[I].kind),
5787            Usage.entries[I].amount);
5788
5789  clang_disposeCXTUResourceUsage(Usage);
5790}
5791
5792//===----------------------------------------------------------------------===//
5793// Misc. utility functions.
5794//===----------------------------------------------------------------------===//
5795
5796/// Default to using an 8 MB stack size on "safety" threads.
5797static unsigned SafetyStackThreadSize = 8 << 20;
5798
5799namespace clang {
5800
5801bool RunSafely(llvm::CrashRecoveryContext &CRC,
5802               void (*Fn)(void*), void *UserData,
5803               unsigned Size) {
5804  if (!Size)
5805    Size = GetSafetyThreadStackSize();
5806  if (Size)
5807    return CRC.RunSafelyOnThread(Fn, UserData, Size);
5808  return CRC.RunSafely(Fn, UserData);
5809}
5810
5811unsigned GetSafetyThreadStackSize() {
5812  return SafetyStackThreadSize;
5813}
5814
5815void SetSafetyThreadStackSize(unsigned Value) {
5816  SafetyStackThreadSize = Value;
5817}
5818
5819}
5820
5821void clang::setThreadBackgroundPriority() {
5822  // FIXME: Move to llvm/Support and make it cross-platform.
5823#ifdef __APPLE__
5824  setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
5825#endif
5826}
5827
5828void cxindex::printDiagsToStderr(ASTUnit *Unit) {
5829  if (!Unit)
5830    return;
5831
5832  for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
5833                                  DEnd = Unit->stored_diag_end();
5834       D != DEnd; ++D) {
5835    CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
5836    CXString Msg = clang_formatDiagnostic(&Diag,
5837                                clang_defaultDiagnosticDisplayOptions());
5838    fprintf(stderr, "%s\n", clang_getCString(Msg));
5839    clang_disposeString(Msg);
5840  }
5841#ifdef LLVM_ON_WIN32
5842  // On Windows, force a flush, since there may be multiple copies of
5843  // stderr and stdout in the file system, all with different buffers
5844  // but writing to the same device.
5845  fflush(stderr);
5846#endif
5847}
5848
5849extern "C" {
5850
5851CXString clang_getClangVersion() {
5852  return createCXString(getClangFullVersion());
5853}
5854
5855} // end: extern "C"
5856
5857