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