CIndex.cpp revision a7fc901a2e39bfe55bfcff5934b2d9fdf9656491
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 CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
693  CXXBaseOrMemberInitializer const * const *X
694    = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
695  CXXBaseOrMemberInitializer const * const *Y
696    = static_cast<CXXBaseOrMemberInitializer 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<CXXBaseOrMemberInitializer *, 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                           &CompareCXXBaseOrMemberInitializers);
754
755      // Visit the initializers in source order
756      for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
757        CXXBaseOrMemberInitializer *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
2653  return 0;
2654}
2655
2656static SourceLocation getLocationFromExpr(Expr *E) {
2657  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2658    return /*FIXME:*/Msg->getLeftLoc();
2659  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2660    return DRE->getLocation();
2661  if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2662    return RefExpr->getLocation();
2663  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2664    return Member->getMemberLoc();
2665  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2666    return Ivar->getLocation();
2667  return E->getLocStart();
2668}
2669
2670extern "C" {
2671
2672unsigned clang_visitChildren(CXCursor parent,
2673                             CXCursorVisitor visitor,
2674                             CXClientData client_data) {
2675  CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2676                          getCursorASTUnit(parent)->getMaxPCHLevel());
2677  return CursorVis.VisitChildren(parent);
2678}
2679
2680#ifndef __has_feature
2681#define __has_feature(x) 0
2682#endif
2683#if __has_feature(blocks)
2684typedef enum CXChildVisitResult
2685     (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2686
2687static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2688    CXClientData client_data) {
2689  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2690  return block(cursor, parent);
2691}
2692#else
2693// If we are compiled with a compiler that doesn't have native blocks support,
2694// define and call the block manually, so the
2695typedef struct _CXChildVisitResult
2696{
2697	void *isa;
2698	int flags;
2699	int reserved;
2700	enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2701                                         CXCursor);
2702} *CXCursorVisitorBlock;
2703
2704static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2705    CXClientData client_data) {
2706  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2707  return block->invoke(block, cursor, parent);
2708}
2709#endif
2710
2711
2712unsigned clang_visitChildrenWithBlock(CXCursor parent,
2713                                      CXCursorVisitorBlock block) {
2714  return clang_visitChildren(parent, visitWithBlock, block);
2715}
2716
2717static CXString getDeclSpelling(Decl *D) {
2718  NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2719  if (!ND) {
2720    if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
2721      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
2722        return createCXString(Property->getIdentifier()->getName());
2723
2724    return createCXString("");
2725  }
2726
2727  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2728    return createCXString(OMD->getSelector().getAsString());
2729
2730  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2731    // No, this isn't the same as the code below. getIdentifier() is non-virtual
2732    // and returns different names. NamedDecl returns the class name and
2733    // ObjCCategoryImplDecl returns the category name.
2734    return createCXString(CIMP->getIdentifier()->getNameStart());
2735
2736  if (isa<UsingDirectiveDecl>(D))
2737    return createCXString("");
2738
2739  llvm::SmallString<1024> S;
2740  llvm::raw_svector_ostream os(S);
2741  ND->printName(os);
2742
2743  return createCXString(os.str());
2744}
2745
2746CXString clang_getCursorSpelling(CXCursor C) {
2747  if (clang_isTranslationUnit(C.kind))
2748    return clang_getTranslationUnitSpelling(
2749                            static_cast<CXTranslationUnit>(C.data[2]));
2750
2751  if (clang_isReference(C.kind)) {
2752    switch (C.kind) {
2753    case CXCursor_ObjCSuperClassRef: {
2754      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
2755      return createCXString(Super->getIdentifier()->getNameStart());
2756    }
2757    case CXCursor_ObjCClassRef: {
2758      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
2759      return createCXString(Class->getIdentifier()->getNameStart());
2760    }
2761    case CXCursor_ObjCProtocolRef: {
2762      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
2763      assert(OID && "getCursorSpelling(): Missing protocol decl");
2764      return createCXString(OID->getIdentifier()->getNameStart());
2765    }
2766    case CXCursor_CXXBaseSpecifier: {
2767      CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2768      return createCXString(B->getType().getAsString());
2769    }
2770    case CXCursor_TypeRef: {
2771      TypeDecl *Type = getCursorTypeRef(C).first;
2772      assert(Type && "Missing type decl");
2773
2774      return createCXString(getCursorContext(C).getTypeDeclType(Type).
2775                              getAsString());
2776    }
2777    case CXCursor_TemplateRef: {
2778      TemplateDecl *Template = getCursorTemplateRef(C).first;
2779      assert(Template && "Missing template decl");
2780
2781      return createCXString(Template->getNameAsString());
2782    }
2783
2784    case CXCursor_NamespaceRef: {
2785      NamedDecl *NS = getCursorNamespaceRef(C).first;
2786      assert(NS && "Missing namespace decl");
2787
2788      return createCXString(NS->getNameAsString());
2789    }
2790
2791    case CXCursor_MemberRef: {
2792      FieldDecl *Field = getCursorMemberRef(C).first;
2793      assert(Field && "Missing member decl");
2794
2795      return createCXString(Field->getNameAsString());
2796    }
2797
2798    case CXCursor_LabelRef: {
2799      LabelStmt *Label = getCursorLabelRef(C).first;
2800      assert(Label && "Missing label");
2801
2802      return createCXString(Label->getID()->getName());
2803    }
2804
2805    case CXCursor_OverloadedDeclRef: {
2806      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2807      if (Decl *D = Storage.dyn_cast<Decl *>()) {
2808        if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2809          return createCXString(ND->getNameAsString());
2810        return createCXString("");
2811      }
2812      if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2813        return createCXString(E->getName().getAsString());
2814      OverloadedTemplateStorage *Ovl
2815        = Storage.get<OverloadedTemplateStorage*>();
2816      if (Ovl->size() == 0)
2817        return createCXString("");
2818      return createCXString((*Ovl->begin())->getNameAsString());
2819    }
2820
2821    default:
2822      return createCXString("<not implemented>");
2823    }
2824  }
2825
2826  if (clang_isExpression(C.kind)) {
2827    Decl *D = getDeclFromExpr(getCursorExpr(C));
2828    if (D)
2829      return getDeclSpelling(D);
2830    return createCXString("");
2831  }
2832
2833  if (clang_isStatement(C.kind)) {
2834    Stmt *S = getCursorStmt(C);
2835    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2836      return createCXString(Label->getID()->getName());
2837
2838    return createCXString("");
2839  }
2840
2841  if (C.kind == CXCursor_MacroInstantiation)
2842    return createCXString(getCursorMacroInstantiation(C)->getName()
2843                                                           ->getNameStart());
2844
2845  if (C.kind == CXCursor_MacroDefinition)
2846    return createCXString(getCursorMacroDefinition(C)->getName()
2847                                                           ->getNameStart());
2848
2849  if (C.kind == CXCursor_InclusionDirective)
2850    return createCXString(getCursorInclusionDirective(C)->getFileName());
2851
2852  if (clang_isDeclaration(C.kind))
2853    return getDeclSpelling(getCursorDecl(C));
2854
2855  return createCXString("");
2856}
2857
2858CXString clang_getCursorDisplayName(CXCursor C) {
2859  if (!clang_isDeclaration(C.kind))
2860    return clang_getCursorSpelling(C);
2861
2862  Decl *D = getCursorDecl(C);
2863  if (!D)
2864    return createCXString("");
2865
2866  PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2867  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2868    D = FunTmpl->getTemplatedDecl();
2869
2870  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2871    llvm::SmallString<64> Str;
2872    llvm::raw_svector_ostream OS(Str);
2873    OS << Function->getNameAsString();
2874    if (Function->getPrimaryTemplate())
2875      OS << "<>";
2876    OS << "(";
2877    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2878      if (I)
2879        OS << ", ";
2880      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2881    }
2882
2883    if (Function->isVariadic()) {
2884      if (Function->getNumParams())
2885        OS << ", ";
2886      OS << "...";
2887    }
2888    OS << ")";
2889    return createCXString(OS.str());
2890  }
2891
2892  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2893    llvm::SmallString<64> Str;
2894    llvm::raw_svector_ostream OS(Str);
2895    OS << ClassTemplate->getNameAsString();
2896    OS << "<";
2897    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2898    for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2899      if (I)
2900        OS << ", ";
2901
2902      NamedDecl *Param = Params->getParam(I);
2903      if (Param->getIdentifier()) {
2904        OS << Param->getIdentifier()->getName();
2905        continue;
2906      }
2907
2908      // There is no parameter name, which makes this tricky. Try to come up
2909      // with something useful that isn't too long.
2910      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2911        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2912      else if (NonTypeTemplateParmDecl *NTTP
2913                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
2914        OS << NTTP->getType().getAsString(Policy);
2915      else
2916        OS << "template<...> class";
2917    }
2918
2919    OS << ">";
2920    return createCXString(OS.str());
2921  }
2922
2923  if (ClassTemplateSpecializationDecl *ClassSpec
2924                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2925    // If the type was explicitly written, use that.
2926    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2927      return createCXString(TSInfo->getType().getAsString(Policy));
2928
2929    llvm::SmallString<64> Str;
2930    llvm::raw_svector_ostream OS(Str);
2931    OS << ClassSpec->getNameAsString();
2932    OS << TemplateSpecializationType::PrintTemplateArgumentList(
2933                                      ClassSpec->getTemplateArgs().data(),
2934                                      ClassSpec->getTemplateArgs().size(),
2935                                                                Policy);
2936    return createCXString(OS.str());
2937  }
2938
2939  return clang_getCursorSpelling(C);
2940}
2941
2942CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
2943  switch (Kind) {
2944  case CXCursor_FunctionDecl:
2945      return createCXString("FunctionDecl");
2946  case CXCursor_TypedefDecl:
2947      return createCXString("TypedefDecl");
2948  case CXCursor_EnumDecl:
2949      return createCXString("EnumDecl");
2950  case CXCursor_EnumConstantDecl:
2951      return createCXString("EnumConstantDecl");
2952  case CXCursor_StructDecl:
2953      return createCXString("StructDecl");
2954  case CXCursor_UnionDecl:
2955      return createCXString("UnionDecl");
2956  case CXCursor_ClassDecl:
2957      return createCXString("ClassDecl");
2958  case CXCursor_FieldDecl:
2959      return createCXString("FieldDecl");
2960  case CXCursor_VarDecl:
2961      return createCXString("VarDecl");
2962  case CXCursor_ParmDecl:
2963      return createCXString("ParmDecl");
2964  case CXCursor_ObjCInterfaceDecl:
2965      return createCXString("ObjCInterfaceDecl");
2966  case CXCursor_ObjCCategoryDecl:
2967      return createCXString("ObjCCategoryDecl");
2968  case CXCursor_ObjCProtocolDecl:
2969      return createCXString("ObjCProtocolDecl");
2970  case CXCursor_ObjCPropertyDecl:
2971      return createCXString("ObjCPropertyDecl");
2972  case CXCursor_ObjCIvarDecl:
2973      return createCXString("ObjCIvarDecl");
2974  case CXCursor_ObjCInstanceMethodDecl:
2975      return createCXString("ObjCInstanceMethodDecl");
2976  case CXCursor_ObjCClassMethodDecl:
2977      return createCXString("ObjCClassMethodDecl");
2978  case CXCursor_ObjCImplementationDecl:
2979      return createCXString("ObjCImplementationDecl");
2980  case CXCursor_ObjCCategoryImplDecl:
2981      return createCXString("ObjCCategoryImplDecl");
2982  case CXCursor_CXXMethod:
2983      return createCXString("CXXMethod");
2984  case CXCursor_UnexposedDecl:
2985      return createCXString("UnexposedDecl");
2986  case CXCursor_ObjCSuperClassRef:
2987      return createCXString("ObjCSuperClassRef");
2988  case CXCursor_ObjCProtocolRef:
2989      return createCXString("ObjCProtocolRef");
2990  case CXCursor_ObjCClassRef:
2991      return createCXString("ObjCClassRef");
2992  case CXCursor_TypeRef:
2993      return createCXString("TypeRef");
2994  case CXCursor_TemplateRef:
2995      return createCXString("TemplateRef");
2996  case CXCursor_NamespaceRef:
2997    return createCXString("NamespaceRef");
2998  case CXCursor_MemberRef:
2999    return createCXString("MemberRef");
3000  case CXCursor_LabelRef:
3001    return createCXString("LabelRef");
3002  case CXCursor_OverloadedDeclRef:
3003    return createCXString("OverloadedDeclRef");
3004  case CXCursor_UnexposedExpr:
3005      return createCXString("UnexposedExpr");
3006  case CXCursor_BlockExpr:
3007      return createCXString("BlockExpr");
3008  case CXCursor_DeclRefExpr:
3009      return createCXString("DeclRefExpr");
3010  case CXCursor_MemberRefExpr:
3011      return createCXString("MemberRefExpr");
3012  case CXCursor_CallExpr:
3013      return createCXString("CallExpr");
3014  case CXCursor_ObjCMessageExpr:
3015      return createCXString("ObjCMessageExpr");
3016  case CXCursor_UnexposedStmt:
3017      return createCXString("UnexposedStmt");
3018  case CXCursor_LabelStmt:
3019      return createCXString("LabelStmt");
3020  case CXCursor_InvalidFile:
3021      return createCXString("InvalidFile");
3022  case CXCursor_InvalidCode:
3023    return createCXString("InvalidCode");
3024  case CXCursor_NoDeclFound:
3025      return createCXString("NoDeclFound");
3026  case CXCursor_NotImplemented:
3027      return createCXString("NotImplemented");
3028  case CXCursor_TranslationUnit:
3029      return createCXString("TranslationUnit");
3030  case CXCursor_UnexposedAttr:
3031      return createCXString("UnexposedAttr");
3032  case CXCursor_IBActionAttr:
3033      return createCXString("attribute(ibaction)");
3034  case CXCursor_IBOutletAttr:
3035     return createCXString("attribute(iboutlet)");
3036  case CXCursor_IBOutletCollectionAttr:
3037      return createCXString("attribute(iboutletcollection)");
3038  case CXCursor_PreprocessingDirective:
3039    return createCXString("preprocessing directive");
3040  case CXCursor_MacroDefinition:
3041    return createCXString("macro definition");
3042  case CXCursor_MacroInstantiation:
3043    return createCXString("macro instantiation");
3044  case CXCursor_InclusionDirective:
3045    return createCXString("inclusion directive");
3046  case CXCursor_Namespace:
3047    return createCXString("Namespace");
3048  case CXCursor_LinkageSpec:
3049    return createCXString("LinkageSpec");
3050  case CXCursor_CXXBaseSpecifier:
3051    return createCXString("C++ base class specifier");
3052  case CXCursor_Constructor:
3053    return createCXString("CXXConstructor");
3054  case CXCursor_Destructor:
3055    return createCXString("CXXDestructor");
3056  case CXCursor_ConversionFunction:
3057    return createCXString("CXXConversion");
3058  case CXCursor_TemplateTypeParameter:
3059    return createCXString("TemplateTypeParameter");
3060  case CXCursor_NonTypeTemplateParameter:
3061    return createCXString("NonTypeTemplateParameter");
3062  case CXCursor_TemplateTemplateParameter:
3063    return createCXString("TemplateTemplateParameter");
3064  case CXCursor_FunctionTemplate:
3065    return createCXString("FunctionTemplate");
3066  case CXCursor_ClassTemplate:
3067    return createCXString("ClassTemplate");
3068  case CXCursor_ClassTemplatePartialSpecialization:
3069    return createCXString("ClassTemplatePartialSpecialization");
3070  case CXCursor_NamespaceAlias:
3071    return createCXString("NamespaceAlias");
3072  case CXCursor_UsingDirective:
3073    return createCXString("UsingDirective");
3074  case CXCursor_UsingDeclaration:
3075    return createCXString("UsingDeclaration");
3076  }
3077
3078  llvm_unreachable("Unhandled CXCursorKind");
3079  return createCXString((const char*) 0);
3080}
3081
3082enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3083                                         CXCursor parent,
3084                                         CXClientData client_data) {
3085  CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
3086
3087  // If our current best cursor is the construction of a temporary object,
3088  // don't replace that cursor with a type reference, because we want
3089  // clang_getCursor() to point at the constructor.
3090  if (clang_isExpression(BestCursor->kind) &&
3091      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3092      cursor.kind == CXCursor_TypeRef)
3093    return CXChildVisit_Recurse;
3094
3095  // Don't override a preprocessing cursor with another preprocessing
3096  // cursor; we want the outermost preprocessing cursor.
3097  if (clang_isPreprocessing(cursor.kind) &&
3098      clang_isPreprocessing(BestCursor->kind))
3099    return CXChildVisit_Recurse;
3100
3101  *BestCursor = cursor;
3102  return CXChildVisit_Recurse;
3103}
3104
3105CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3106  if (!TU)
3107    return clang_getNullCursor();
3108
3109  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3110  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3111
3112  // Translate the given source location to make it point at the beginning of
3113  // the token under the cursor.
3114  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3115
3116  // Guard against an invalid SourceLocation, or we may assert in one
3117  // of the following calls.
3118  if (SLoc.isInvalid())
3119    return clang_getNullCursor();
3120
3121  bool Logging = getenv("LIBCLANG_LOGGING");
3122  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3123                                    CXXUnit->getASTContext().getLangOptions());
3124
3125  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3126  if (SLoc.isValid()) {
3127    // FIXME: Would be great to have a "hint" cursor, then walk from that
3128    // hint cursor upward until we find a cursor whose source range encloses
3129    // the region of interest, rather than starting from the translation unit.
3130    CXCursor Parent = clang_getTranslationUnitCursor(TU);
3131    CursorVisitor CursorVis(TU, GetCursorVisitor, &Result,
3132                            Decl::MaxPCHLevel, SourceLocation(SLoc));
3133    CursorVis.VisitChildren(Parent);
3134  }
3135
3136  if (Logging) {
3137    CXFile SearchFile;
3138    unsigned SearchLine, SearchColumn;
3139    CXFile ResultFile;
3140    unsigned ResultLine, ResultColumn;
3141    CXString SearchFileName, ResultFileName, KindSpelling, USR;
3142    const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
3143    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3144
3145    clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3146                                   0);
3147    clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3148                                   &ResultColumn, 0);
3149    SearchFileName = clang_getFileName(SearchFile);
3150    ResultFileName = clang_getFileName(ResultFile);
3151    KindSpelling = clang_getCursorKindSpelling(Result.kind);
3152    USR = clang_getCursorUSR(Result);
3153    fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
3154            clang_getCString(SearchFileName), SearchLine, SearchColumn,
3155            clang_getCString(KindSpelling),
3156            clang_getCString(ResultFileName), ResultLine, ResultColumn,
3157            clang_getCString(USR), IsDef);
3158    clang_disposeString(SearchFileName);
3159    clang_disposeString(ResultFileName);
3160    clang_disposeString(KindSpelling);
3161    clang_disposeString(USR);
3162
3163    CXCursor Definition = clang_getCursorDefinition(Result);
3164    if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3165      CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3166      CXString DefinitionKindSpelling
3167                                = clang_getCursorKindSpelling(Definition.kind);
3168      CXFile DefinitionFile;
3169      unsigned DefinitionLine, DefinitionColumn;
3170      clang_getInstantiationLocation(DefinitionLoc, &DefinitionFile,
3171                                     &DefinitionLine, &DefinitionColumn, 0);
3172      CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3173      fprintf(stderr, "  -> %s(%s:%d:%d)\n",
3174              clang_getCString(DefinitionKindSpelling),
3175              clang_getCString(DefinitionFileName),
3176              DefinitionLine, DefinitionColumn);
3177      clang_disposeString(DefinitionFileName);
3178      clang_disposeString(DefinitionKindSpelling);
3179    }
3180  }
3181
3182  return Result;
3183}
3184
3185CXCursor clang_getNullCursor(void) {
3186  return MakeCXCursorInvalid(CXCursor_InvalidFile);
3187}
3188
3189unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3190  return X == Y;
3191}
3192
3193unsigned clang_hashCursor(CXCursor C) {
3194  unsigned Index = 0;
3195  if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3196    Index = 1;
3197
3198  return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3199                                        std::make_pair(C.kind, C.data[Index]));
3200}
3201
3202unsigned clang_isInvalid(enum CXCursorKind K) {
3203  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3204}
3205
3206unsigned clang_isDeclaration(enum CXCursorKind K) {
3207  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3208}
3209
3210unsigned clang_isReference(enum CXCursorKind K) {
3211  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3212}
3213
3214unsigned clang_isExpression(enum CXCursorKind K) {
3215  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3216}
3217
3218unsigned clang_isStatement(enum CXCursorKind K) {
3219  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3220}
3221
3222unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3223  return K == CXCursor_TranslationUnit;
3224}
3225
3226unsigned clang_isPreprocessing(enum CXCursorKind K) {
3227  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3228}
3229
3230unsigned clang_isUnexposed(enum CXCursorKind K) {
3231  switch (K) {
3232    case CXCursor_UnexposedDecl:
3233    case CXCursor_UnexposedExpr:
3234    case CXCursor_UnexposedStmt:
3235    case CXCursor_UnexposedAttr:
3236      return true;
3237    default:
3238      return false;
3239  }
3240}
3241
3242CXCursorKind clang_getCursorKind(CXCursor C) {
3243  return C.kind;
3244}
3245
3246CXSourceLocation clang_getCursorLocation(CXCursor C) {
3247  if (clang_isReference(C.kind)) {
3248    switch (C.kind) {
3249    case CXCursor_ObjCSuperClassRef: {
3250      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3251        = getCursorObjCSuperClassRef(C);
3252      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3253    }
3254
3255    case CXCursor_ObjCProtocolRef: {
3256      std::pair<ObjCProtocolDecl *, SourceLocation> P
3257        = getCursorObjCProtocolRef(C);
3258      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3259    }
3260
3261    case CXCursor_ObjCClassRef: {
3262      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3263        = getCursorObjCClassRef(C);
3264      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3265    }
3266
3267    case CXCursor_TypeRef: {
3268      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3269      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3270    }
3271
3272    case CXCursor_TemplateRef: {
3273      std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3274      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3275    }
3276
3277    case CXCursor_NamespaceRef: {
3278      std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3279      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3280    }
3281
3282    case CXCursor_MemberRef: {
3283      std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3284      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3285    }
3286
3287    case CXCursor_CXXBaseSpecifier: {
3288      CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3289      if (!BaseSpec)
3290        return clang_getNullLocation();
3291
3292      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3293        return cxloc::translateSourceLocation(getCursorContext(C),
3294                                            TSInfo->getTypeLoc().getBeginLoc());
3295
3296      return cxloc::translateSourceLocation(getCursorContext(C),
3297                                        BaseSpec->getSourceRange().getBegin());
3298    }
3299
3300    case CXCursor_LabelRef: {
3301      std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3302      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3303    }
3304
3305    case CXCursor_OverloadedDeclRef:
3306      return cxloc::translateSourceLocation(getCursorContext(C),
3307                                          getCursorOverloadedDeclRef(C).second);
3308
3309    default:
3310      // FIXME: Need a way to enumerate all non-reference cases.
3311      llvm_unreachable("Missed a reference kind");
3312    }
3313  }
3314
3315  if (clang_isExpression(C.kind))
3316    return cxloc::translateSourceLocation(getCursorContext(C),
3317                                   getLocationFromExpr(getCursorExpr(C)));
3318
3319  if (clang_isStatement(C.kind))
3320    return cxloc::translateSourceLocation(getCursorContext(C),
3321                                          getCursorStmt(C)->getLocStart());
3322
3323  if (C.kind == CXCursor_PreprocessingDirective) {
3324    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3325    return cxloc::translateSourceLocation(getCursorContext(C), L);
3326  }
3327
3328  if (C.kind == CXCursor_MacroInstantiation) {
3329    SourceLocation L
3330      = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
3331    return cxloc::translateSourceLocation(getCursorContext(C), L);
3332  }
3333
3334  if (C.kind == CXCursor_MacroDefinition) {
3335    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3336    return cxloc::translateSourceLocation(getCursorContext(C), L);
3337  }
3338
3339  if (C.kind == CXCursor_InclusionDirective) {
3340    SourceLocation L
3341      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3342    return cxloc::translateSourceLocation(getCursorContext(C), L);
3343  }
3344
3345  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3346    return clang_getNullLocation();
3347
3348  Decl *D = getCursorDecl(C);
3349  SourceLocation Loc = D->getLocation();
3350  if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3351    Loc = Class->getClassLoc();
3352  // FIXME: Multiple variables declared in a single declaration
3353  // currently lack the information needed to correctly determine their
3354  // ranges when accounting for the type-specifier.  We use context
3355  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3356  // and if so, whether it is the first decl.
3357  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3358    if (!cxcursor::isFirstInDeclGroup(C))
3359      Loc = VD->getLocation();
3360  }
3361
3362  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3363}
3364
3365} // end extern "C"
3366
3367static SourceRange getRawCursorExtent(CXCursor C) {
3368  if (clang_isReference(C.kind)) {
3369    switch (C.kind) {
3370    case CXCursor_ObjCSuperClassRef:
3371      return  getCursorObjCSuperClassRef(C).second;
3372
3373    case CXCursor_ObjCProtocolRef:
3374      return getCursorObjCProtocolRef(C).second;
3375
3376    case CXCursor_ObjCClassRef:
3377      return getCursorObjCClassRef(C).second;
3378
3379    case CXCursor_TypeRef:
3380      return getCursorTypeRef(C).second;
3381
3382    case CXCursor_TemplateRef:
3383      return getCursorTemplateRef(C).second;
3384
3385    case CXCursor_NamespaceRef:
3386      return getCursorNamespaceRef(C).second;
3387
3388    case CXCursor_MemberRef:
3389      return getCursorMemberRef(C).second;
3390
3391    case CXCursor_CXXBaseSpecifier:
3392      return getCursorCXXBaseSpecifier(C)->getSourceRange();
3393
3394    case CXCursor_LabelRef:
3395      return getCursorLabelRef(C).second;
3396
3397    case CXCursor_OverloadedDeclRef:
3398      return getCursorOverloadedDeclRef(C).second;
3399
3400    default:
3401      // FIXME: Need a way to enumerate all non-reference cases.
3402      llvm_unreachable("Missed a reference kind");
3403    }
3404  }
3405
3406  if (clang_isExpression(C.kind))
3407    return getCursorExpr(C)->getSourceRange();
3408
3409  if (clang_isStatement(C.kind))
3410    return getCursorStmt(C)->getSourceRange();
3411
3412  if (C.kind == CXCursor_PreprocessingDirective)
3413    return cxcursor::getCursorPreprocessingDirective(C);
3414
3415  if (C.kind == CXCursor_MacroInstantiation)
3416    return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
3417
3418  if (C.kind == CXCursor_MacroDefinition)
3419    return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3420
3421  if (C.kind == CXCursor_InclusionDirective)
3422    return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3423
3424  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3425    Decl *D = cxcursor::getCursorDecl(C);
3426    SourceRange R = D->getSourceRange();
3427    // FIXME: Multiple variables declared in a single declaration
3428    // currently lack the information needed to correctly determine their
3429    // ranges when accounting for the type-specifier.  We use context
3430    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3431    // and if so, whether it is the first decl.
3432    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3433      if (!cxcursor::isFirstInDeclGroup(C))
3434        R.setBegin(VD->getLocation());
3435    }
3436    return R;
3437  }
3438  return SourceRange();
3439}
3440
3441/// \brief Retrieves the "raw" cursor extent, which is then extended to include
3442/// the decl-specifier-seq for declarations.
3443static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
3444  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3445    Decl *D = cxcursor::getCursorDecl(C);
3446    SourceRange R = D->getSourceRange();
3447
3448    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3449      if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3450        TypeLoc TL = TI->getTypeLoc();
3451        SourceLocation TLoc = TL.getSourceRange().getBegin();
3452        if (TLoc.isValid() && R.getBegin().isValid() &&
3453            SrcMgr.isBeforeInTranslationUnit(TLoc, R.getBegin()))
3454          R.setBegin(TLoc);
3455      }
3456
3457      // FIXME: Multiple variables declared in a single declaration
3458      // currently lack the information needed to correctly determine their
3459      // ranges when accounting for the type-specifier.  We use context
3460      // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3461      // and if so, whether it is the first decl.
3462      if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3463        if (!cxcursor::isFirstInDeclGroup(C))
3464          R.setBegin(VD->getLocation());
3465      }
3466    }
3467
3468    return R;
3469  }
3470
3471  return getRawCursorExtent(C);
3472}
3473
3474extern "C" {
3475
3476CXSourceRange clang_getCursorExtent(CXCursor C) {
3477  SourceRange R = getRawCursorExtent(C);
3478  if (R.isInvalid())
3479    return clang_getNullRange();
3480
3481  return cxloc::translateSourceRange(getCursorContext(C), R);
3482}
3483
3484CXCursor clang_getCursorReferenced(CXCursor C) {
3485  if (clang_isInvalid(C.kind))
3486    return clang_getNullCursor();
3487
3488  CXTranslationUnit tu = getCursorTU(C);
3489  if (clang_isDeclaration(C.kind)) {
3490    Decl *D = getCursorDecl(C);
3491    if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3492      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
3493    if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3494      return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), tu);
3495    if (ObjCForwardProtocolDecl *Protocols
3496                                        = dyn_cast<ObjCForwardProtocolDecl>(D))
3497      return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), tu);
3498    if (ObjCPropertyImplDecl *PropImpl =llvm::dyn_cast<ObjCPropertyImplDecl>(D))
3499      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3500        return MakeCXCursor(Property, tu);
3501
3502    return C;
3503  }
3504
3505  if (clang_isExpression(C.kind)) {
3506    Expr *E = getCursorExpr(C);
3507    Decl *D = getDeclFromExpr(E);
3508    if (D)
3509      return MakeCXCursor(D, tu);
3510
3511    if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3512      return MakeCursorOverloadedDeclRef(Ovl, tu);
3513
3514    return clang_getNullCursor();
3515  }
3516
3517  if (clang_isStatement(C.kind)) {
3518    Stmt *S = getCursorStmt(C);
3519    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3520      return MakeCXCursor(Goto->getLabel(), getCursorDecl(C), tu);
3521
3522    return clang_getNullCursor();
3523  }
3524
3525  if (C.kind == CXCursor_MacroInstantiation) {
3526    if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3527      return MakeMacroDefinitionCursor(Def, tu);
3528  }
3529
3530  if (!clang_isReference(C.kind))
3531    return clang_getNullCursor();
3532
3533  switch (C.kind) {
3534    case CXCursor_ObjCSuperClassRef:
3535      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
3536
3537    case CXCursor_ObjCProtocolRef: {
3538      return MakeCXCursor(getCursorObjCProtocolRef(C).first, tu);
3539
3540    case CXCursor_ObjCClassRef:
3541      return MakeCXCursor(getCursorObjCClassRef(C).first, tu );
3542
3543    case CXCursor_TypeRef:
3544      return MakeCXCursor(getCursorTypeRef(C).first, tu );
3545
3546    case CXCursor_TemplateRef:
3547      return MakeCXCursor(getCursorTemplateRef(C).first, tu );
3548
3549    case CXCursor_NamespaceRef:
3550      return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
3551
3552    case CXCursor_MemberRef:
3553      return MakeCXCursor(getCursorMemberRef(C).first, tu );
3554
3555    case CXCursor_CXXBaseSpecifier: {
3556      CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3557      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3558                                                         tu ));
3559    }
3560
3561    case CXCursor_LabelRef:
3562      // FIXME: We end up faking the "parent" declaration here because we
3563      // don't want to make CXCursor larger.
3564      return MakeCXCursor(getCursorLabelRef(C).first,
3565               static_cast<ASTUnit*>(tu->TUData)->getASTContext()
3566                          .getTranslationUnitDecl(),
3567                          tu);
3568
3569    case CXCursor_OverloadedDeclRef:
3570      return C;
3571
3572    default:
3573      // We would prefer to enumerate all non-reference cursor kinds here.
3574      llvm_unreachable("Unhandled reference cursor kind");
3575      break;
3576    }
3577  }
3578
3579  return clang_getNullCursor();
3580}
3581
3582CXCursor clang_getCursorDefinition(CXCursor C) {
3583  if (clang_isInvalid(C.kind))
3584    return clang_getNullCursor();
3585
3586  CXTranslationUnit TU = getCursorTU(C);
3587
3588  bool WasReference = false;
3589  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
3590    C = clang_getCursorReferenced(C);
3591    WasReference = true;
3592  }
3593
3594  if (C.kind == CXCursor_MacroInstantiation)
3595    return clang_getCursorReferenced(C);
3596
3597  if (!clang_isDeclaration(C.kind))
3598    return clang_getNullCursor();
3599
3600  Decl *D = getCursorDecl(C);
3601  if (!D)
3602    return clang_getNullCursor();
3603
3604  switch (D->getKind()) {
3605  // Declaration kinds that don't really separate the notions of
3606  // declaration and definition.
3607  case Decl::Namespace:
3608  case Decl::Typedef:
3609  case Decl::TemplateTypeParm:
3610  case Decl::EnumConstant:
3611  case Decl::Field:
3612  case Decl::IndirectField:
3613  case Decl::ObjCIvar:
3614  case Decl::ObjCAtDefsField:
3615  case Decl::ImplicitParam:
3616  case Decl::ParmVar:
3617  case Decl::NonTypeTemplateParm:
3618  case Decl::TemplateTemplateParm:
3619  case Decl::ObjCCategoryImpl:
3620  case Decl::ObjCImplementation:
3621  case Decl::AccessSpec:
3622  case Decl::LinkageSpec:
3623  case Decl::ObjCPropertyImpl:
3624  case Decl::FileScopeAsm:
3625  case Decl::StaticAssert:
3626  case Decl::Block:
3627    return C;
3628
3629  // Declaration kinds that don't make any sense here, but are
3630  // nonetheless harmless.
3631  case Decl::TranslationUnit:
3632    break;
3633
3634  // Declaration kinds for which the definition is not resolvable.
3635  case Decl::UnresolvedUsingTypename:
3636  case Decl::UnresolvedUsingValue:
3637    break;
3638
3639  case Decl::UsingDirective:
3640    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3641                        TU);
3642
3643  case Decl::NamespaceAlias:
3644    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
3645
3646  case Decl::Enum:
3647  case Decl::Record:
3648  case Decl::CXXRecord:
3649  case Decl::ClassTemplateSpecialization:
3650  case Decl::ClassTemplatePartialSpecialization:
3651    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
3652      return MakeCXCursor(Def, TU);
3653    return clang_getNullCursor();
3654
3655  case Decl::Function:
3656  case Decl::CXXMethod:
3657  case Decl::CXXConstructor:
3658  case Decl::CXXDestructor:
3659  case Decl::CXXConversion: {
3660    const FunctionDecl *Def = 0;
3661    if (cast<FunctionDecl>(D)->getBody(Def))
3662      return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
3663    return clang_getNullCursor();
3664  }
3665
3666  case Decl::Var: {
3667    // Ask the variable if it has a definition.
3668    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3669      return MakeCXCursor(Def, TU);
3670    return clang_getNullCursor();
3671  }
3672
3673  case Decl::FunctionTemplate: {
3674    const FunctionDecl *Def = 0;
3675    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
3676      return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
3677    return clang_getNullCursor();
3678  }
3679
3680  case Decl::ClassTemplate: {
3681    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
3682                                                            ->getDefinition())
3683      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
3684                          TU);
3685    return clang_getNullCursor();
3686  }
3687
3688  case Decl::Using:
3689    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3690                                       D->getLocation(), TU);
3691
3692  case Decl::UsingShadow:
3693    return clang_getCursorDefinition(
3694                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
3695                                    TU));
3696
3697  case Decl::ObjCMethod: {
3698    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3699    if (Method->isThisDeclarationADefinition())
3700      return C;
3701
3702    // Dig out the method definition in the associated
3703    // @implementation, if we have it.
3704    // FIXME: The ASTs should make finding the definition easier.
3705    if (ObjCInterfaceDecl *Class
3706                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3707      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3708        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3709                                                  Method->isInstanceMethod()))
3710          if (Def->isThisDeclarationADefinition())
3711            return MakeCXCursor(Def, TU);
3712
3713    return clang_getNullCursor();
3714  }
3715
3716  case Decl::ObjCCategory:
3717    if (ObjCCategoryImplDecl *Impl
3718                               = cast<ObjCCategoryDecl>(D)->getImplementation())
3719      return MakeCXCursor(Impl, TU);
3720    return clang_getNullCursor();
3721
3722  case Decl::ObjCProtocol:
3723    if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3724      return C;
3725    return clang_getNullCursor();
3726
3727  case Decl::ObjCInterface:
3728    // There are two notions of a "definition" for an Objective-C
3729    // class: the interface and its implementation. When we resolved a
3730    // reference to an Objective-C class, produce the @interface as
3731    // the definition; when we were provided with the interface,
3732    // produce the @implementation as the definition.
3733    if (WasReference) {
3734      if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3735        return C;
3736    } else if (ObjCImplementationDecl *Impl
3737                              = cast<ObjCInterfaceDecl>(D)->getImplementation())
3738      return MakeCXCursor(Impl, TU);
3739    return clang_getNullCursor();
3740
3741  case Decl::ObjCProperty:
3742    // FIXME: We don't really know where to find the
3743    // ObjCPropertyImplDecls that implement this property.
3744    return clang_getNullCursor();
3745
3746  case Decl::ObjCCompatibleAlias:
3747    if (ObjCInterfaceDecl *Class
3748          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3749      if (!Class->isForwardDecl())
3750        return MakeCXCursor(Class, TU);
3751
3752    return clang_getNullCursor();
3753
3754  case Decl::ObjCForwardProtocol:
3755    return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3756                                       D->getLocation(), TU);
3757
3758  case Decl::ObjCClass:
3759    return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3760                                       TU);
3761
3762  case Decl::Friend:
3763    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
3764      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
3765    return clang_getNullCursor();
3766
3767  case Decl::FriendTemplate:
3768    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
3769      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
3770    return clang_getNullCursor();
3771  }
3772
3773  return clang_getNullCursor();
3774}
3775
3776unsigned clang_isCursorDefinition(CXCursor C) {
3777  if (!clang_isDeclaration(C.kind))
3778    return 0;
3779
3780  return clang_getCursorDefinition(C) == C;
3781}
3782
3783CXCursor clang_getCanonicalCursor(CXCursor C) {
3784  if (!clang_isDeclaration(C.kind))
3785    return C;
3786
3787  if (Decl *D = getCursorDecl(C))
3788    return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
3789
3790  return C;
3791}
3792
3793unsigned clang_getNumOverloadedDecls(CXCursor C) {
3794  if (C.kind != CXCursor_OverloadedDeclRef)
3795    return 0;
3796
3797  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3798  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3799    return E->getNumDecls();
3800
3801  if (OverloadedTemplateStorage *S
3802                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
3803    return S->size();
3804
3805  Decl *D = Storage.get<Decl*>();
3806  if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3807    return Using->shadow_size();
3808  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3809    return Classes->size();
3810  if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3811    return Protocols->protocol_size();
3812
3813  return 0;
3814}
3815
3816CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
3817  if (cursor.kind != CXCursor_OverloadedDeclRef)
3818    return clang_getNullCursor();
3819
3820  if (index >= clang_getNumOverloadedDecls(cursor))
3821    return clang_getNullCursor();
3822
3823  CXTranslationUnit TU = getCursorTU(cursor);
3824  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3825  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3826    return MakeCXCursor(E->decls_begin()[index], TU);
3827
3828  if (OverloadedTemplateStorage *S
3829                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
3830    return MakeCXCursor(S->begin()[index], TU);
3831
3832  Decl *D = Storage.get<Decl*>();
3833  if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3834    // FIXME: This is, unfortunately, linear time.
3835    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3836    std::advance(Pos, index);
3837    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
3838  }
3839
3840  if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3841    return MakeCXCursor(Classes->begin()[index].getInterface(), TU);
3842
3843  if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3844    return MakeCXCursor(Protocols->protocol_begin()[index], TU);
3845
3846  return clang_getNullCursor();
3847}
3848
3849void clang_getDefinitionSpellingAndExtent(CXCursor C,
3850                                          const char **startBuf,
3851                                          const char **endBuf,
3852                                          unsigned *startLine,
3853                                          unsigned *startColumn,
3854                                          unsigned *endLine,
3855                                          unsigned *endColumn) {
3856  assert(getCursorDecl(C) && "CXCursor has null decl");
3857  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
3858  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3859  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
3860
3861  SourceManager &SM = FD->getASTContext().getSourceManager();
3862  *startBuf = SM.getCharacterData(Body->getLBracLoc());
3863  *endBuf = SM.getCharacterData(Body->getRBracLoc());
3864  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3865  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3866  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3867  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3868}
3869
3870void clang_enableStackTraces(void) {
3871  llvm::sys::PrintStackTraceOnErrorSignal();
3872}
3873
3874void clang_executeOnThread(void (*fn)(void*), void *user_data,
3875                           unsigned stack_size) {
3876  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3877}
3878
3879} // end: extern "C"
3880
3881//===----------------------------------------------------------------------===//
3882// Token-based Operations.
3883//===----------------------------------------------------------------------===//
3884
3885/* CXToken layout:
3886 *   int_data[0]: a CXTokenKind
3887 *   int_data[1]: starting token location
3888 *   int_data[2]: token length
3889 *   int_data[3]: reserved
3890 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
3891 *   otherwise unused.
3892 */
3893extern "C" {
3894
3895CXTokenKind clang_getTokenKind(CXToken CXTok) {
3896  return static_cast<CXTokenKind>(CXTok.int_data[0]);
3897}
3898
3899CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3900  switch (clang_getTokenKind(CXTok)) {
3901  case CXToken_Identifier:
3902  case CXToken_Keyword:
3903    // We know we have an IdentifierInfo*, so use that.
3904    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3905                            ->getNameStart());
3906
3907  case CXToken_Literal: {
3908    // We have stashed the starting pointer in the ptr_data field. Use it.
3909    const char *Text = static_cast<const char *>(CXTok.ptr_data);
3910    return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
3911  }
3912
3913  case CXToken_Punctuation:
3914  case CXToken_Comment:
3915    break;
3916  }
3917
3918  // We have to find the starting buffer pointer the hard way, by
3919  // deconstructing the source location.
3920  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3921  if (!CXXUnit)
3922    return createCXString("");
3923
3924  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3925  std::pair<FileID, unsigned> LocInfo
3926    = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
3927  bool Invalid = false;
3928  llvm::StringRef Buffer
3929    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3930  if (Invalid)
3931    return createCXString("");
3932
3933  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
3934}
3935
3936CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3937  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3938  if (!CXXUnit)
3939    return clang_getNullLocation();
3940
3941  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3942                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3943}
3944
3945CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3946  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3947  if (!CXXUnit)
3948    return clang_getNullRange();
3949
3950  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
3951                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3952}
3953
3954void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3955                    CXToken **Tokens, unsigned *NumTokens) {
3956  if (Tokens)
3957    *Tokens = 0;
3958  if (NumTokens)
3959    *NumTokens = 0;
3960
3961  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3962  if (!CXXUnit || !Tokens || !NumTokens)
3963    return;
3964
3965  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3966
3967  SourceRange R = cxloc::translateCXSourceRange(Range);
3968  if (R.isInvalid())
3969    return;
3970
3971  SourceManager &SourceMgr = CXXUnit->getSourceManager();
3972  std::pair<FileID, unsigned> BeginLocInfo
3973    = SourceMgr.getDecomposedLoc(R.getBegin());
3974  std::pair<FileID, unsigned> EndLocInfo
3975    = SourceMgr.getDecomposedLoc(R.getEnd());
3976
3977  // Cannot tokenize across files.
3978  if (BeginLocInfo.first != EndLocInfo.first)
3979    return;
3980
3981  // Create a lexer
3982  bool Invalid = false;
3983  llvm::StringRef Buffer
3984    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
3985  if (Invalid)
3986    return;
3987
3988  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3989            CXXUnit->getASTContext().getLangOptions(),
3990            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
3991  Lex.SetCommentRetentionState(true);
3992
3993  // Lex tokens until we hit the end of the range.
3994  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
3995  llvm::SmallVector<CXToken, 32> CXTokens;
3996  Token Tok;
3997  bool previousWasAt = false;
3998  do {
3999    // Lex the next token
4000    Lex.LexFromRawLexer(Tok);
4001    if (Tok.is(tok::eof))
4002      break;
4003
4004    // Initialize the CXToken.
4005    CXToken CXTok;
4006
4007    //   - Common fields
4008    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4009    CXTok.int_data[2] = Tok.getLength();
4010    CXTok.int_data[3] = 0;
4011
4012    //   - Kind-specific fields
4013    if (Tok.isLiteral()) {
4014      CXTok.int_data[0] = CXToken_Literal;
4015      CXTok.ptr_data = (void *)Tok.getLiteralData();
4016    } else if (Tok.is(tok::raw_identifier)) {
4017      // Lookup the identifier to determine whether we have a keyword.
4018      IdentifierInfo *II
4019        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4020
4021      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4022        CXTok.int_data[0] = CXToken_Keyword;
4023      }
4024      else {
4025        CXTok.int_data[0] = Tok.is(tok::identifier)
4026          ? CXToken_Identifier
4027          : CXToken_Keyword;
4028      }
4029      CXTok.ptr_data = II;
4030    } else if (Tok.is(tok::comment)) {
4031      CXTok.int_data[0] = CXToken_Comment;
4032      CXTok.ptr_data = 0;
4033    } else {
4034      CXTok.int_data[0] = CXToken_Punctuation;
4035      CXTok.ptr_data = 0;
4036    }
4037    CXTokens.push_back(CXTok);
4038    previousWasAt = Tok.is(tok::at);
4039  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4040
4041  if (CXTokens.empty())
4042    return;
4043
4044  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4045  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4046  *NumTokens = CXTokens.size();
4047}
4048
4049void clang_disposeTokens(CXTranslationUnit TU,
4050                         CXToken *Tokens, unsigned NumTokens) {
4051  free(Tokens);
4052}
4053
4054} // end: extern "C"
4055
4056//===----------------------------------------------------------------------===//
4057// Token annotation APIs.
4058//===----------------------------------------------------------------------===//
4059
4060typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
4061static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4062                                                     CXCursor parent,
4063                                                     CXClientData client_data);
4064namespace {
4065class AnnotateTokensWorker {
4066  AnnotateTokensData &Annotated;
4067  CXToken *Tokens;
4068  CXCursor *Cursors;
4069  unsigned NumTokens;
4070  unsigned TokIdx;
4071  unsigned PreprocessingTokIdx;
4072  CursorVisitor AnnotateVis;
4073  SourceManager &SrcMgr;
4074
4075  bool MoreTokens() const { return TokIdx < NumTokens; }
4076  unsigned NextToken() const { return TokIdx; }
4077  void AdvanceToken() { ++TokIdx; }
4078  SourceLocation GetTokenLoc(unsigned tokI) {
4079    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4080  }
4081
4082public:
4083  AnnotateTokensWorker(AnnotateTokensData &annotated,
4084                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
4085                       CXTranslationUnit tu, SourceRange RegionOfInterest)
4086    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
4087      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4088      AnnotateVis(tu,
4089                  AnnotateTokensVisitor, this,
4090                  Decl::MaxPCHLevel, RegionOfInterest),
4091      SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()) {}
4092
4093  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4094  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4095  void AnnotateTokens(CXCursor parent);
4096  void AnnotateTokens() {
4097    AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getTU()));
4098  }
4099};
4100}
4101
4102void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4103  // Walk the AST within the region of interest, annotating tokens
4104  // along the way.
4105  VisitChildren(parent);
4106
4107  for (unsigned I = 0 ; I < TokIdx ; ++I) {
4108    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4109    if (Pos != Annotated.end() &&
4110        (clang_isInvalid(Cursors[I].kind) ||
4111         Pos->second.kind != CXCursor_PreprocessingDirective))
4112      Cursors[I] = Pos->second;
4113  }
4114
4115  // Finish up annotating any tokens left.
4116  if (!MoreTokens())
4117    return;
4118
4119  const CXCursor &C = clang_getNullCursor();
4120  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4121    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4122    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4123  }
4124}
4125
4126enum CXChildVisitResult
4127AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
4128  CXSourceLocation Loc = clang_getCursorLocation(cursor);
4129  SourceRange cursorRange = getRawCursorExtent(cursor);
4130  if (cursorRange.isInvalid())
4131    return CXChildVisit_Recurse;
4132
4133  if (clang_isPreprocessing(cursor.kind)) {
4134    // For macro instantiations, just note where the beginning of the macro
4135    // instantiation occurs.
4136    if (cursor.kind == CXCursor_MacroInstantiation) {
4137      Annotated[Loc.int_data] = cursor;
4138      return CXChildVisit_Recurse;
4139    }
4140
4141    // Items in the preprocessing record are kept separate from items in
4142    // declarations, so we keep a separate token index.
4143    unsigned SavedTokIdx = TokIdx;
4144    TokIdx = PreprocessingTokIdx;
4145
4146    // Skip tokens up until we catch up to the beginning of the preprocessing
4147    // entry.
4148    while (MoreTokens()) {
4149      const unsigned I = NextToken();
4150      SourceLocation TokLoc = GetTokenLoc(I);
4151      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4152      case RangeBefore:
4153        AdvanceToken();
4154        continue;
4155      case RangeAfter:
4156      case RangeOverlap:
4157        break;
4158      }
4159      break;
4160    }
4161
4162    // Look at all of the tokens within this range.
4163    while (MoreTokens()) {
4164      const unsigned I = NextToken();
4165      SourceLocation TokLoc = GetTokenLoc(I);
4166      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4167      case RangeBefore:
4168        assert(0 && "Infeasible");
4169      case RangeAfter:
4170        break;
4171      case RangeOverlap:
4172        Cursors[I] = cursor;
4173        AdvanceToken();
4174        continue;
4175      }
4176      break;
4177    }
4178
4179    // Save the preprocessing token index; restore the non-preprocessing
4180    // token index.
4181    PreprocessingTokIdx = TokIdx;
4182    TokIdx = SavedTokIdx;
4183    return CXChildVisit_Recurse;
4184  }
4185
4186  if (cursorRange.isInvalid())
4187    return CXChildVisit_Continue;
4188
4189  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4190
4191  // Adjust the annotated range based specific declarations.
4192  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4193  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
4194    Decl *D = cxcursor::getCursorDecl(cursor);
4195    // Don't visit synthesized ObjC methods, since they have no syntatic
4196    // representation in the source.
4197    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4198      if (MD->isSynthesized())
4199        return CXChildVisit_Continue;
4200    }
4201    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4202      if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4203        TypeLoc TL = TI->getTypeLoc();
4204        SourceLocation TLoc = TL.getSourceRange().getBegin();
4205        if (TLoc.isValid() && L.isValid() &&
4206            SrcMgr.isBeforeInTranslationUnit(TLoc, L))
4207          cursorRange.setBegin(TLoc);
4208      }
4209    }
4210  }
4211
4212  // If the location of the cursor occurs within a macro instantiation, record
4213  // the spelling location of the cursor in our annotation map.  We can then
4214  // paper over the token labelings during a post-processing step to try and
4215  // get cursor mappings for tokens that are the *arguments* of a macro
4216  // instantiation.
4217  if (L.isMacroID()) {
4218    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4219    // Only invalidate the old annotation if it isn't part of a preprocessing
4220    // directive.  Here we assume that the default construction of CXCursor
4221    // results in CXCursor.kind being an initialized value (i.e., 0).  If
4222    // this isn't the case, we can fix by doing lookup + insertion.
4223
4224    CXCursor &oldC = Annotated[rawEncoding];
4225    if (!clang_isPreprocessing(oldC.kind))
4226      oldC = cursor;
4227  }
4228
4229  const enum CXCursorKind K = clang_getCursorKind(parent);
4230  const CXCursor updateC =
4231    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4232     ? clang_getNullCursor() : parent;
4233
4234  while (MoreTokens()) {
4235    const unsigned I = NextToken();
4236    SourceLocation TokLoc = GetTokenLoc(I);
4237    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4238      case RangeBefore:
4239        Cursors[I] = updateC;
4240        AdvanceToken();
4241        continue;
4242      case RangeAfter:
4243      case RangeOverlap:
4244        break;
4245    }
4246    break;
4247  }
4248
4249  // Visit children to get their cursor information.
4250  const unsigned BeforeChildren = NextToken();
4251  VisitChildren(cursor);
4252  const unsigned AfterChildren = NextToken();
4253
4254  // Adjust 'Last' to the last token within the extent of the cursor.
4255  while (MoreTokens()) {
4256    const unsigned I = NextToken();
4257    SourceLocation TokLoc = GetTokenLoc(I);
4258    switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4259      case RangeBefore:
4260        assert(0 && "Infeasible");
4261      case RangeAfter:
4262        break;
4263      case RangeOverlap:
4264        Cursors[I] = updateC;
4265        AdvanceToken();
4266        continue;
4267    }
4268    break;
4269  }
4270  const unsigned Last = NextToken();
4271
4272  // Scan the tokens that are at the beginning of the cursor, but are not
4273  // capture by the child cursors.
4274
4275  // For AST elements within macros, rely on a post-annotate pass to
4276  // to correctly annotate the tokens with cursors.  Otherwise we can
4277  // get confusing results of having tokens that map to cursors that really
4278  // are expanded by an instantiation.
4279  if (L.isMacroID())
4280    cursor = clang_getNullCursor();
4281
4282  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4283    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4284      break;
4285
4286    Cursors[I] = cursor;
4287  }
4288  // Scan the tokens that are at the end of the cursor, but are not captured
4289  // but the child cursors.
4290  for (unsigned I = AfterChildren; I != Last; ++I)
4291    Cursors[I] = cursor;
4292
4293  TokIdx = Last;
4294  return CXChildVisit_Continue;
4295}
4296
4297static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4298                                                     CXCursor parent,
4299                                                     CXClientData client_data) {
4300  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4301}
4302
4303// This gets run a separate thread to avoid stack blowout.
4304static void runAnnotateTokensWorker(void *UserData) {
4305  ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4306}
4307
4308extern "C" {
4309
4310void clang_annotateTokens(CXTranslationUnit TU,
4311                          CXToken *Tokens, unsigned NumTokens,
4312                          CXCursor *Cursors) {
4313
4314  if (NumTokens == 0 || !Tokens || !Cursors)
4315    return;
4316
4317  // Any token we don't specifically annotate will have a NULL cursor.
4318  CXCursor C = clang_getNullCursor();
4319  for (unsigned I = 0; I != NumTokens; ++I)
4320    Cursors[I] = C;
4321
4322  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4323  if (!CXXUnit)
4324    return;
4325
4326  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4327
4328  // Determine the region of interest, which contains all of the tokens.
4329  SourceRange RegionOfInterest;
4330  RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4331                                        clang_getTokenLocation(TU, Tokens[0])));
4332  RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4333                                clang_getTokenLocation(TU,
4334                                                       Tokens[NumTokens - 1])));
4335
4336  // A mapping from the source locations found when re-lexing or traversing the
4337  // region of interest to the corresponding cursors.
4338  AnnotateTokensData Annotated;
4339
4340  // Relex the tokens within the source range to look for preprocessing
4341  // directives.
4342  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4343  std::pair<FileID, unsigned> BeginLocInfo
4344    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4345  std::pair<FileID, unsigned> EndLocInfo
4346    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
4347
4348  llvm::StringRef Buffer;
4349  bool Invalid = false;
4350  if (BeginLocInfo.first == EndLocInfo.first &&
4351      ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4352      !Invalid) {
4353    Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4354              CXXUnit->getASTContext().getLangOptions(),
4355              Buffer.begin(), Buffer.data() + BeginLocInfo.second,
4356              Buffer.end());
4357    Lex.SetCommentRetentionState(true);
4358
4359    // Lex tokens in raw mode until we hit the end of the range, to avoid
4360    // entering #includes or expanding macros.
4361    while (true) {
4362      Token Tok;
4363      Lex.LexFromRawLexer(Tok);
4364
4365    reprocess:
4366      if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4367        // We have found a preprocessing directive. Gobble it up so that we
4368        // don't see it while preprocessing these tokens later, but keep track
4369        // of all of the token locations inside this preprocessing directive so
4370        // that we can annotate them appropriately.
4371        //
4372        // FIXME: Some simple tests here could identify macro definitions and
4373        // #undefs, to provide specific cursor kinds for those.
4374        std::vector<SourceLocation> Locations;
4375        do {
4376          Locations.push_back(Tok.getLocation());
4377          Lex.LexFromRawLexer(Tok);
4378        } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4379
4380        using namespace cxcursor;
4381        CXCursor Cursor
4382          = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4383                                                         Locations.back()),
4384                                           TU);
4385        for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4386          Annotated[Locations[I].getRawEncoding()] = Cursor;
4387        }
4388
4389        if (Tok.isAtStartOfLine())
4390          goto reprocess;
4391
4392        continue;
4393      }
4394
4395      if (Tok.is(tok::eof))
4396        break;
4397    }
4398  }
4399
4400  // Annotate all of the source locations in the region of interest that map to
4401  // a specific cursor.
4402  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4403                         TU, RegionOfInterest);
4404
4405  // Run the worker within a CrashRecoveryContext.
4406  // FIXME: We use a ridiculous stack size here because the data-recursion
4407  // algorithm uses a large stack frame than the non-data recursive version,
4408  // and AnnotationTokensWorker currently transforms the data-recursion
4409  // algorithm back into a traditional recursion by explicitly calling
4410  // VisitChildren().  We will need to remove this explicit recursive call.
4411  llvm::CrashRecoveryContext CRC;
4412  if (!RunSafely(CRC, runAnnotateTokensWorker, &W,
4413                 GetSafetyThreadStackSize() * 2)) {
4414    fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4415  }
4416}
4417} // end: extern "C"
4418
4419//===----------------------------------------------------------------------===//
4420// Operations for querying linkage of a cursor.
4421//===----------------------------------------------------------------------===//
4422
4423extern "C" {
4424CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
4425  if (!clang_isDeclaration(cursor.kind))
4426    return CXLinkage_Invalid;
4427
4428  Decl *D = cxcursor::getCursorDecl(cursor);
4429  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4430    switch (ND->getLinkage()) {
4431      case NoLinkage: return CXLinkage_NoLinkage;
4432      case InternalLinkage: return CXLinkage_Internal;
4433      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4434      case ExternalLinkage: return CXLinkage_External;
4435    };
4436
4437  return CXLinkage_Invalid;
4438}
4439} // end: extern "C"
4440
4441//===----------------------------------------------------------------------===//
4442// Operations for querying language of a cursor.
4443//===----------------------------------------------------------------------===//
4444
4445static CXLanguageKind getDeclLanguage(const Decl *D) {
4446  switch (D->getKind()) {
4447    default:
4448      break;
4449    case Decl::ImplicitParam:
4450    case Decl::ObjCAtDefsField:
4451    case Decl::ObjCCategory:
4452    case Decl::ObjCCategoryImpl:
4453    case Decl::ObjCClass:
4454    case Decl::ObjCCompatibleAlias:
4455    case Decl::ObjCForwardProtocol:
4456    case Decl::ObjCImplementation:
4457    case Decl::ObjCInterface:
4458    case Decl::ObjCIvar:
4459    case Decl::ObjCMethod:
4460    case Decl::ObjCProperty:
4461    case Decl::ObjCPropertyImpl:
4462    case Decl::ObjCProtocol:
4463      return CXLanguage_ObjC;
4464    case Decl::CXXConstructor:
4465    case Decl::CXXConversion:
4466    case Decl::CXXDestructor:
4467    case Decl::CXXMethod:
4468    case Decl::CXXRecord:
4469    case Decl::ClassTemplate:
4470    case Decl::ClassTemplatePartialSpecialization:
4471    case Decl::ClassTemplateSpecialization:
4472    case Decl::Friend:
4473    case Decl::FriendTemplate:
4474    case Decl::FunctionTemplate:
4475    case Decl::LinkageSpec:
4476    case Decl::Namespace:
4477    case Decl::NamespaceAlias:
4478    case Decl::NonTypeTemplateParm:
4479    case Decl::StaticAssert:
4480    case Decl::TemplateTemplateParm:
4481    case Decl::TemplateTypeParm:
4482    case Decl::UnresolvedUsingTypename:
4483    case Decl::UnresolvedUsingValue:
4484    case Decl::Using:
4485    case Decl::UsingDirective:
4486    case Decl::UsingShadow:
4487      return CXLanguage_CPlusPlus;
4488  }
4489
4490  return CXLanguage_C;
4491}
4492
4493extern "C" {
4494
4495enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4496  if (clang_isDeclaration(cursor.kind))
4497    if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4498      if (D->hasAttr<UnavailableAttr>() ||
4499          (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4500        return CXAvailability_Available;
4501
4502      if (D->hasAttr<DeprecatedAttr>())
4503        return CXAvailability_Deprecated;
4504    }
4505
4506  return CXAvailability_Available;
4507}
4508
4509CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4510  if (clang_isDeclaration(cursor.kind))
4511    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4512
4513  return CXLanguage_Invalid;
4514}
4515
4516 /// \brief If the given cursor is the "templated" declaration
4517 /// descibing a class or function template, return the class or
4518 /// function template.
4519static Decl *maybeGetTemplateCursor(Decl *D) {
4520  if (!D)
4521    return 0;
4522
4523  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4524    if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
4525      return FunTmpl;
4526
4527  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4528    if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
4529      return ClassTmpl;
4530
4531  return D;
4532}
4533
4534CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4535  if (clang_isDeclaration(cursor.kind)) {
4536    if (Decl *D = getCursorDecl(cursor)) {
4537      DeclContext *DC = D->getDeclContext();
4538      if (!DC)
4539        return clang_getNullCursor();
4540
4541      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4542                          getCursorTU(cursor));
4543    }
4544  }
4545
4546  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4547    if (Decl *D = getCursorDecl(cursor))
4548      return MakeCXCursor(D, getCursorTU(cursor));
4549  }
4550
4551  return clang_getNullCursor();
4552}
4553
4554CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4555  if (clang_isDeclaration(cursor.kind)) {
4556    if (Decl *D = getCursorDecl(cursor)) {
4557      DeclContext *DC = D->getLexicalDeclContext();
4558      if (!DC)
4559        return clang_getNullCursor();
4560
4561      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
4562                          getCursorTU(cursor));
4563    }
4564  }
4565
4566  // FIXME: Note that we can't easily compute the lexical context of a
4567  // statement or expression, so we return nothing.
4568  return clang_getNullCursor();
4569}
4570
4571static void CollectOverriddenMethods(DeclContext *Ctx,
4572                                     ObjCMethodDecl *Method,
4573                            llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4574  if (!Ctx)
4575    return;
4576
4577  // If we have a class or category implementation, jump straight to the
4578  // interface.
4579  if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4580    return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4581
4582  ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4583  if (!Container)
4584    return;
4585
4586  // Check whether we have a matching method at this level.
4587  if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4588                                                    Method->isInstanceMethod()))
4589    if (Method != Overridden) {
4590      // We found an override at this level; there is no need to look
4591      // into other protocols or categories.
4592      Methods.push_back(Overridden);
4593      return;
4594    }
4595
4596  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4597    for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4598                                          PEnd = Protocol->protocol_end();
4599         P != PEnd; ++P)
4600      CollectOverriddenMethods(*P, Method, Methods);
4601  }
4602
4603  if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4604    for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4605                                          PEnd = Category->protocol_end();
4606         P != PEnd; ++P)
4607      CollectOverriddenMethods(*P, Method, Methods);
4608  }
4609
4610  if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4611    for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4612                                           PEnd = Interface->protocol_end();
4613         P != PEnd; ++P)
4614      CollectOverriddenMethods(*P, Method, Methods);
4615
4616    for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4617         Category; Category = Category->getNextClassCategory())
4618      CollectOverriddenMethods(Category, Method, Methods);
4619
4620    // We only look into the superclass if we haven't found anything yet.
4621    if (Methods.empty())
4622      if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4623        return CollectOverriddenMethods(Super, Method, Methods);
4624  }
4625}
4626
4627void clang_getOverriddenCursors(CXCursor cursor,
4628                                CXCursor **overridden,
4629                                unsigned *num_overridden) {
4630  if (overridden)
4631    *overridden = 0;
4632  if (num_overridden)
4633    *num_overridden = 0;
4634  if (!overridden || !num_overridden)
4635    return;
4636
4637  if (!clang_isDeclaration(cursor.kind))
4638    return;
4639
4640  Decl *D = getCursorDecl(cursor);
4641  if (!D)
4642    return;
4643
4644  // Handle C++ member functions.
4645  CXTranslationUnit TU = getCursorTU(cursor);
4646  if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4647    *num_overridden = CXXMethod->size_overridden_methods();
4648    if (!*num_overridden)
4649      return;
4650
4651    *overridden = new CXCursor [*num_overridden];
4652    unsigned I = 0;
4653    for (CXXMethodDecl::method_iterator
4654              M = CXXMethod->begin_overridden_methods(),
4655           MEnd = CXXMethod->end_overridden_methods();
4656         M != MEnd; (void)++M, ++I)
4657      (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU);
4658    return;
4659  }
4660
4661  ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4662  if (!Method)
4663    return;
4664
4665  // Handle Objective-C methods.
4666  llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4667  CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4668
4669  if (Methods.empty())
4670    return;
4671
4672  *num_overridden = Methods.size();
4673  *overridden = new CXCursor [Methods.size()];
4674  for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4675    (*overridden)[I] = MakeCXCursor(Methods[I], TU);
4676}
4677
4678void clang_disposeOverriddenCursors(CXCursor *overridden) {
4679  delete [] overridden;
4680}
4681
4682CXFile clang_getIncludedFile(CXCursor cursor) {
4683  if (cursor.kind != CXCursor_InclusionDirective)
4684    return 0;
4685
4686  InclusionDirective *ID = getCursorInclusionDirective(cursor);
4687  return (void *)ID->getFile();
4688}
4689
4690} // end: extern "C"
4691
4692
4693//===----------------------------------------------------------------------===//
4694// C++ AST instrospection.
4695//===----------------------------------------------------------------------===//
4696
4697extern "C" {
4698unsigned clang_CXXMethod_isStatic(CXCursor C) {
4699  if (!clang_isDeclaration(C.kind))
4700    return 0;
4701
4702  CXXMethodDecl *Method = 0;
4703  Decl *D = cxcursor::getCursorDecl(C);
4704  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4705    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4706  else
4707    Method = dyn_cast_or_null<CXXMethodDecl>(D);
4708  return (Method && Method->isStatic()) ? 1 : 0;
4709}
4710
4711} // end: extern "C"
4712
4713//===----------------------------------------------------------------------===//
4714// Attribute introspection.
4715//===----------------------------------------------------------------------===//
4716
4717extern "C" {
4718CXType clang_getIBOutletCollectionType(CXCursor C) {
4719  if (C.kind != CXCursor_IBOutletCollectionAttr)
4720    return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
4721
4722  IBOutletCollectionAttr *A =
4723    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4724
4725  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
4726}
4727} // end: extern "C"
4728
4729//===----------------------------------------------------------------------===//
4730// Misc. utility functions.
4731//===----------------------------------------------------------------------===//
4732
4733/// Default to using an 8 MB stack size on "safety" threads.
4734static unsigned SafetyStackThreadSize = 8 << 20;
4735
4736namespace clang {
4737
4738bool RunSafely(llvm::CrashRecoveryContext &CRC,
4739               void (*Fn)(void*), void *UserData,
4740               unsigned Size) {
4741  if (!Size)
4742    Size = GetSafetyThreadStackSize();
4743  if (Size)
4744    return CRC.RunSafelyOnThread(Fn, UserData, Size);
4745  return CRC.RunSafely(Fn, UserData);
4746}
4747
4748unsigned GetSafetyThreadStackSize() {
4749  return SafetyStackThreadSize;
4750}
4751
4752void SetSafetyThreadStackSize(unsigned Value) {
4753  SafetyStackThreadSize = Value;
4754}
4755
4756}
4757
4758extern "C" {
4759
4760CXString clang_getClangVersion() {
4761  return createCXString(getClangFullVersion());
4762}
4763
4764} // end: extern "C"
4765