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