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