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