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