]> granicus.if.org Git - clang/blob - tools/libclang/CIndex.cpp
[OpenCL] Add new types for OpenCL 2.0.
[clang] / tools / libclang / CIndex.cpp
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 "CIndexDiagnostic.h"
17 #include "CLog.h"
18 #include "CXCursor.h"
19 #include "CXSourceLocation.h"
20 #include "CXString.h"
21 #include "CXTranslationUnit.h"
22 #include "CXType.h"
23 #include "CursorVisitor.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/Mangle.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/Basic/Diagnostic.h"
28 #include "clang/Basic/DiagnosticCategories.h"
29 #include "clang/Basic/DiagnosticIDs.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Basic/Version.h"
32 #include "clang/Frontend/ASTUnit.h"
33 #include "clang/Frontend/CompilerInstance.h"
34 #include "clang/Frontend/FrontendDiagnostic.h"
35 #include "clang/Index/CommentToXML.h"
36 #include "clang/Lex/HeaderSearch.h"
37 #include "clang/Lex/Lexer.h"
38 #include "clang/Lex/PreprocessingRecord.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Serialization/SerializationDiagnostic.h"
41 #include "llvm/ADT/Optional.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/ADT/StringSwitch.h"
44 #include "llvm/Config/llvm-config.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/Mangler.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/CrashRecoveryContext.h"
49 #include "llvm/Support/Format.h"
50 #include "llvm/Support/ManagedStatic.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/Mutex.h"
53 #include "llvm/Support/Program.h"
54 #include "llvm/Support/SaveAndRestore.h"
55 #include "llvm/Support/Signals.h"
56 #include "llvm/Support/TargetSelect.h"
57 #include "llvm/Support/Threading.h"
58 #include "llvm/Support/Timer.h"
59 #include "llvm/Support/raw_ostream.h"
60
61 #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
62 #define USE_DARWIN_THREADS
63 #endif
64
65 #ifdef USE_DARWIN_THREADS
66 #include <pthread.h>
67 #endif
68
69 using namespace clang;
70 using namespace clang::cxcursor;
71 using namespace clang::cxtu;
72 using namespace clang::cxindex;
73
74 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *AU) {
75   if (!AU)
76     return nullptr;
77   assert(CIdx);
78   CXTranslationUnit D = new CXTranslationUnitImpl();
79   D->CIdx = CIdx;
80   D->TheASTUnit = AU;
81   D->StringPool = new cxstring::CXStringPool();
82   D->Diagnostics = nullptr;
83   D->OverridenCursorsPool = createOverridenCXCursorsPool();
84   D->CommentToXML = nullptr;
85   return D;
86 }
87
88 bool cxtu::isASTReadError(ASTUnit *AU) {
89   for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
90                                      DEnd = AU->stored_diag_end();
91        D != DEnd; ++D) {
92     if (D->getLevel() >= DiagnosticsEngine::Error &&
93         DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
94             diag::DiagCat_AST_Deserialization_Issue)
95       return true;
96   }
97   return false;
98 }
99
100 cxtu::CXTUOwner::~CXTUOwner() {
101   if (TU)
102     clang_disposeTranslationUnit(TU);
103 }
104
105 /// \brief Compare two source ranges to determine their relative position in
106 /// the translation unit.
107 static RangeComparisonResult RangeCompare(SourceManager &SM,
108                                           SourceRange R1,
109                                           SourceRange R2) {
110   assert(R1.isValid() && "First range is invalid?");
111   assert(R2.isValid() && "Second range is invalid?");
112   if (R1.getEnd() != R2.getBegin() &&
113       SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
114     return RangeBefore;
115   if (R2.getEnd() != R1.getBegin() &&
116       SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
117     return RangeAfter;
118   return RangeOverlap;
119 }
120
121 /// \brief Determine if a source location falls within, before, or after a
122 ///   a given source range.
123 static RangeComparisonResult LocationCompare(SourceManager &SM,
124                                              SourceLocation L, SourceRange R) {
125   assert(R.isValid() && "First range is invalid?");
126   assert(L.isValid() && "Second range is invalid?");
127   if (L == R.getBegin() || L == R.getEnd())
128     return RangeOverlap;
129   if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
130     return RangeBefore;
131   if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
132     return RangeAfter;
133   return RangeOverlap;
134 }
135
136 /// \brief Translate a Clang source range into a CIndex source range.
137 ///
138 /// Clang internally represents ranges where the end location points to the
139 /// start of the token at the end. However, for external clients it is more
140 /// useful to have a CXSourceRange be a proper half-open interval. This routine
141 /// does the appropriate translation.
142 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
143                                           const LangOptions &LangOpts,
144                                           const CharSourceRange &R) {
145   // We want the last character in this location, so we will adjust the
146   // location accordingly.
147   SourceLocation EndLoc = R.getEnd();
148   if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
149     EndLoc = SM.getExpansionRange(EndLoc).second;
150   if (R.isTokenRange() && !EndLoc.isInvalid()) {
151     unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
152                                                 SM, LangOpts);
153     EndLoc = EndLoc.getLocWithOffset(Length);
154   }
155
156   CXSourceRange Result = {
157     { &SM, &LangOpts },
158     R.getBegin().getRawEncoding(),
159     EndLoc.getRawEncoding()
160   };
161   return Result;
162 }
163
164 //===----------------------------------------------------------------------===//
165 // Cursor visitor.
166 //===----------------------------------------------------------------------===//
167
168 static SourceRange getRawCursorExtent(CXCursor C);
169 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
170
171
172 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
173   return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
174 }
175
176 /// \brief Visit the given cursor and, if requested by the visitor,
177 /// its children.
178 ///
179 /// \param Cursor the cursor to visit.
180 ///
181 /// \param CheckedRegionOfInterest if true, then the caller already checked
182 /// that this cursor is within the region of interest.
183 ///
184 /// \returns true if the visitation should be aborted, false if it
185 /// should continue.
186 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
187   if (clang_isInvalid(Cursor.kind))
188     return false;
189
190   if (clang_isDeclaration(Cursor.kind)) {
191     const Decl *D = getCursorDecl(Cursor);
192     if (!D) {
193       assert(0 && "Invalid declaration cursor");
194       return true; // abort.
195     }
196     
197     // Ignore implicit declarations, unless it's an objc method because
198     // currently we should report implicit methods for properties when indexing.
199     if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
200       return false;
201   }
202
203   // If we have a range of interest, and this cursor doesn't intersect with it,
204   // we're done.
205   if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
206     SourceRange Range = getRawCursorExtent(Cursor);
207     if (Range.isInvalid() || CompareRegionOfInterest(Range))
208       return false;
209   }
210
211   switch (Visitor(Cursor, Parent, ClientData)) {
212   case CXChildVisit_Break:
213     return true;
214
215   case CXChildVisit_Continue:
216     return false;
217
218   case CXChildVisit_Recurse: {
219     bool ret = VisitChildren(Cursor);
220     if (PostChildrenVisitor)
221       if (PostChildrenVisitor(Cursor, ClientData))
222         return true;
223     return ret;
224   }
225   }
226
227   llvm_unreachable("Invalid CXChildVisitResult!");
228 }
229
230 static bool visitPreprocessedEntitiesInRange(SourceRange R,
231                                              PreprocessingRecord &PPRec,
232                                              CursorVisitor &Visitor) {
233   SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
234   FileID FID;
235   
236   if (!Visitor.shouldVisitIncludedEntities()) {
237     // If the begin/end of the range lie in the same FileID, do the optimization
238     // where we skip preprocessed entities that do not come from the same FileID.
239     FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
240     if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
241       FID = FileID();
242   }
243
244   const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
245   return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
246                                            PPRec, FID);
247 }
248
249 bool CursorVisitor::visitFileRegion() {
250   if (RegionOfInterest.isInvalid())
251     return false;
252
253   ASTUnit *Unit = cxtu::getASTUnit(TU);
254   SourceManager &SM = Unit->getSourceManager();
255   
256   std::pair<FileID, unsigned>
257     Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())), 
258     End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd())); 
259
260   if (End.first != Begin.first) {
261     // If the end does not reside in the same file, try to recover by
262     // picking the end of the file of begin location.
263     End.first = Begin.first;
264     End.second = SM.getFileIDSize(Begin.first);
265   }
266
267   assert(Begin.first == End.first);
268   if (Begin.second > End.second)
269     return false;
270   
271   FileID File = Begin.first;
272   unsigned Offset = Begin.second;
273   unsigned Length = End.second - Begin.second;
274
275   if (!VisitDeclsOnly && !VisitPreprocessorLast)
276     if (visitPreprocessedEntitiesInRegion())
277       return true; // visitation break.
278
279   if (visitDeclsFromFileRegion(File, Offset, Length))
280     return true; // visitation break.
281
282   if (!VisitDeclsOnly && VisitPreprocessorLast)
283     return visitPreprocessedEntitiesInRegion();
284
285   return false;
286 }
287
288 static bool isInLexicalContext(Decl *D, DeclContext *DC) {
289   if (!DC)
290     return false;
291
292   for (DeclContext *DeclDC = D->getLexicalDeclContext();
293          DeclDC; DeclDC = DeclDC->getLexicalParent()) {
294     if (DeclDC == DC)
295       return true;
296   }
297   return false;
298 }
299
300 bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
301                                              unsigned Offset, unsigned Length) {
302   ASTUnit *Unit = cxtu::getASTUnit(TU);
303   SourceManager &SM = Unit->getSourceManager();
304   SourceRange Range = RegionOfInterest;
305
306   SmallVector<Decl *, 16> Decls;
307   Unit->findFileRegionDecls(File, Offset, Length, Decls);
308
309   // If we didn't find any file level decls for the file, try looking at the
310   // file that it was included from.
311   while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
312     bool Invalid = false;
313     const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
314     if (Invalid)
315       return false;
316
317     SourceLocation Outer;
318     if (SLEntry.isFile())
319       Outer = SLEntry.getFile().getIncludeLoc();
320     else
321       Outer = SLEntry.getExpansion().getExpansionLocStart();
322     if (Outer.isInvalid())
323       return false;
324
325     std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
326     Length = 0;
327     Unit->findFileRegionDecls(File, Offset, Length, Decls);
328   }
329
330   assert(!Decls.empty());
331
332   bool VisitedAtLeastOnce = false;
333   DeclContext *CurDC = nullptr;
334   SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
335   for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
336     Decl *D = *DIt;
337     if (D->getSourceRange().isInvalid())
338       continue;
339
340     if (isInLexicalContext(D, CurDC))
341       continue;
342
343     CurDC = dyn_cast<DeclContext>(D);
344
345     if (TagDecl *TD = dyn_cast<TagDecl>(D))
346       if (!TD->isFreeStanding())
347         continue;
348
349     RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
350     if (CompRes == RangeBefore)
351       continue;
352     if (CompRes == RangeAfter)
353       break;
354
355     assert(CompRes == RangeOverlap);
356     VisitedAtLeastOnce = true;
357
358     if (isa<ObjCContainerDecl>(D)) {
359       FileDI_current = &DIt;
360       FileDE_current = DE;
361     } else {
362       FileDI_current = nullptr;
363     }
364
365     if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
366       return true; // visitation break.
367   }
368
369   if (VisitedAtLeastOnce)
370     return false;
371
372   // No Decls overlapped with the range. Move up the lexical context until there
373   // is a context that contains the range or we reach the translation unit
374   // level.
375   DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
376                                          : (*(DIt-1))->getLexicalDeclContext();
377
378   while (DC && !DC->isTranslationUnit()) {
379     Decl *D = cast<Decl>(DC);
380     SourceRange CurDeclRange = D->getSourceRange();
381     if (CurDeclRange.isInvalid())
382       break;
383
384     if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
385       if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
386         return true; // visitation break.
387     }
388
389     DC = D->getLexicalDeclContext();
390   }
391
392   return false;
393 }
394
395 bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
396   if (!AU->getPreprocessor().getPreprocessingRecord())
397     return false;
398
399   PreprocessingRecord &PPRec
400     = *AU->getPreprocessor().getPreprocessingRecord();
401   SourceManager &SM = AU->getSourceManager();
402   
403   if (RegionOfInterest.isValid()) {
404     SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
405     SourceLocation B = MappedRange.getBegin();
406     SourceLocation E = MappedRange.getEnd();
407
408     if (AU->isInPreambleFileID(B)) {
409       if (SM.isLoadedSourceLocation(E))
410         return visitPreprocessedEntitiesInRange(SourceRange(B, E),
411                                                  PPRec, *this);
412
413       // Beginning of range lies in the preamble but it also extends beyond
414       // it into the main file. Split the range into 2 parts, one covering
415       // the preamble and another covering the main file. This allows subsequent
416       // calls to visitPreprocessedEntitiesInRange to accept a source range that
417       // lies in the same FileID, allowing it to skip preprocessed entities that
418       // do not come from the same FileID.
419       bool breaked =
420         visitPreprocessedEntitiesInRange(
421                                    SourceRange(B, AU->getEndOfPreambleFileID()),
422                                           PPRec, *this);
423       if (breaked) return true;
424       return visitPreprocessedEntitiesInRange(
425                                     SourceRange(AU->getStartOfMainFileID(), E),
426                                         PPRec, *this);
427     }
428
429     return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
430   }
431
432   bool OnlyLocalDecls
433     = !AU->isMainFileAST() && AU->getOnlyLocalDecls(); 
434   
435   if (OnlyLocalDecls)
436     return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
437                                      PPRec);
438
439   return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
440 }
441
442 template<typename InputIterator>
443 bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
444                                               InputIterator Last,
445                                               PreprocessingRecord &PPRec,
446                                               FileID FID) {
447   for (; First != Last; ++First) {
448     if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
449       continue;
450
451     PreprocessedEntity *PPE = *First;
452     if (!PPE)
453       continue;
454
455     if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
456       if (Visit(MakeMacroExpansionCursor(ME, TU)))
457         return true;
458
459       continue;
460     }
461
462     if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
463       if (Visit(MakeMacroDefinitionCursor(MD, TU)))
464         return true;
465
466       continue;
467     }
468     
469     if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
470       if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
471         return true;
472       
473       continue;
474     }
475   }
476
477   return false;
478 }
479
480 /// \brief Visit the children of the given cursor.
481 /// 
482 /// \returns true if the visitation should be aborted, false if it
483 /// should continue.
484 bool CursorVisitor::VisitChildren(CXCursor Cursor) {
485   if (clang_isReference(Cursor.kind) && 
486       Cursor.kind != CXCursor_CXXBaseSpecifier) {
487     // By definition, references have no children.
488     return false;
489   }
490
491   // Set the Parent field to Cursor, then back to its old value once we're
492   // done.
493   SetParentRAII SetParent(Parent, StmtParent, Cursor);
494
495   if (clang_isDeclaration(Cursor.kind)) {
496     Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
497     if (!D)
498       return false;
499
500     return VisitAttributes(D) || Visit(D);
501   }
502
503   if (clang_isStatement(Cursor.kind)) {
504     if (const Stmt *S = getCursorStmt(Cursor))
505       return Visit(S);
506
507     return false;
508   }
509
510   if (clang_isExpression(Cursor.kind)) {
511     if (const Expr *E = getCursorExpr(Cursor))
512       return Visit(E);
513
514     return false;
515   }
516
517   if (clang_isTranslationUnit(Cursor.kind)) {
518     CXTranslationUnit TU = getCursorTU(Cursor);
519     ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
520     
521     int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
522     for (unsigned I = 0; I != 2; ++I) {
523       if (VisitOrder[I]) {
524         if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
525             RegionOfInterest.isInvalid()) {
526           for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
527                                         TLEnd = CXXUnit->top_level_end();
528                TL != TLEnd; ++TL) {
529             if (Visit(MakeCXCursor(*TL, TU, RegionOfInterest), true))
530               return true;
531           }
532         } else if (VisitDeclContext(
533                                 CXXUnit->getASTContext().getTranslationUnitDecl()))
534           return true;
535         continue;
536       }
537
538       // Walk the preprocessing record.
539       if (CXXUnit->getPreprocessor().getPreprocessingRecord())
540         visitPreprocessedEntitiesInRegion();
541     }
542     
543     return false;
544   }
545
546   if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
547     if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
548       if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
549         return Visit(BaseTSInfo->getTypeLoc());
550       }
551     }
552   }
553
554   if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
555     const IBOutletCollectionAttr *A =
556       cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
557     if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
558       return Visit(cxcursor::MakeCursorObjCClassRef(
559           ObjT->getInterface(),
560           A->getInterfaceLoc()->getTypeLoc().getLocStart(), TU));
561   }
562
563   // If pointing inside a macro definition, check if the token is an identifier
564   // that was ever defined as a macro. In such a case, create a "pseudo" macro
565   // expansion cursor for that token.
566   SourceLocation BeginLoc = RegionOfInterest.getBegin();
567   if (Cursor.kind == CXCursor_MacroDefinition &&
568       BeginLoc == RegionOfInterest.getEnd()) {
569     SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
570     const MacroInfo *MI =
571         getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
572     if (MacroDefinitionRecord *MacroDef =
573             checkForMacroInMacroDefinition(MI, Loc, TU))
574       return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
575   }
576
577   // Nothing to visit at the moment.
578   return false;
579 }
580
581 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
582   if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
583     if (Visit(TSInfo->getTypeLoc()))
584         return true;
585
586   if (Stmt *Body = B->getBody())
587     return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
588
589   return false;
590 }
591
592 Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
593   if (RegionOfInterest.isValid()) {
594     SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
595     if (Range.isInvalid())
596       return None;
597     
598     switch (CompareRegionOfInterest(Range)) {
599     case RangeBefore:
600       // This declaration comes before the region of interest; skip it.
601       return None;
602
603     case RangeAfter:
604       // This declaration comes after the region of interest; we're done.
605       return false;
606
607     case RangeOverlap:
608       // This declaration overlaps the region of interest; visit it.
609       break;
610     }
611   }
612   return true;
613 }
614
615 bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
616   DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
617
618   // FIXME: Eventually remove.  This part of a hack to support proper
619   // iteration over all Decls contained lexically within an ObjC container.
620   SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
621   SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
622
623   for ( ; I != E; ++I) {
624     Decl *D = *I;
625     if (D->getLexicalDeclContext() != DC)
626       continue;
627     CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
628
629     // Ignore synthesized ivars here, otherwise if we have something like:
630     //   @synthesize prop = _prop;
631     // and '_prop' is not declared, we will encounter a '_prop' ivar before
632     // encountering the 'prop' synthesize declaration and we will think that
633     // we passed the region-of-interest.
634     if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
635       if (ivarD->getSynthesize())
636         continue;
637     }
638
639     // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
640     // declarations is a mismatch with the compiler semantics.
641     if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
642       ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
643       if (!ID->isThisDeclarationADefinition())
644         Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
645
646     } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
647       ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
648       if (!PD->isThisDeclarationADefinition())
649         Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
650     }
651
652     const Optional<bool> &V = shouldVisitCursor(Cursor);
653     if (!V.hasValue())
654       continue;
655     if (!V.getValue())
656       return false;
657     if (Visit(Cursor, true))
658       return true;
659   }
660   return false;
661 }
662
663 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
664   llvm_unreachable("Translation units are visited directly by Visit()");
665 }
666
667 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
668   if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
669     return Visit(TSInfo->getTypeLoc());
670
671   return false;
672 }
673
674 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
675   if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
676     return Visit(TSInfo->getTypeLoc());
677
678   return false;
679 }
680
681 bool CursorVisitor::VisitTagDecl(TagDecl *D) {
682   return VisitDeclContext(D);
683 }
684
685 bool CursorVisitor::VisitClassTemplateSpecializationDecl(
686                                           ClassTemplateSpecializationDecl *D) {
687   bool ShouldVisitBody = false;
688   switch (D->getSpecializationKind()) {
689   case TSK_Undeclared:
690   case TSK_ImplicitInstantiation:
691     // Nothing to visit
692     return false;
693       
694   case TSK_ExplicitInstantiationDeclaration:
695   case TSK_ExplicitInstantiationDefinition:
696     break;
697       
698   case TSK_ExplicitSpecialization:
699     ShouldVisitBody = true;
700     break;
701   }
702   
703   // Visit the template arguments used in the specialization.
704   if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
705     TypeLoc TL = SpecType->getTypeLoc();
706     if (TemplateSpecializationTypeLoc TSTLoc =
707             TL.getAs<TemplateSpecializationTypeLoc>()) {
708       for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
709         if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
710           return true;
711     }
712   }
713   
714   if (ShouldVisitBody && VisitCXXRecordDecl(D))
715     return true;
716   
717   return false;
718 }
719
720 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
721                                    ClassTemplatePartialSpecializationDecl *D) {
722   // FIXME: Visit the "outer" template parameter lists on the TagDecl
723   // before visiting these template parameters.
724   if (VisitTemplateParameters(D->getTemplateParameters()))
725     return true;
726
727   // Visit the partial specialization arguments.
728   const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
729   const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
730   for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
731     if (VisitTemplateArgumentLoc(TemplateArgs[I]))
732       return true;
733   
734   return VisitCXXRecordDecl(D);
735 }
736
737 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
738   // Visit the default argument.
739   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
740     if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
741       if (Visit(DefArg->getTypeLoc()))
742         return true;
743   
744   return false;
745 }
746
747 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
748   if (Expr *Init = D->getInitExpr())
749     return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
750   return false;
751 }
752
753 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
754   unsigned NumParamList = DD->getNumTemplateParameterLists();
755   for (unsigned i = 0; i < NumParamList; i++) {
756     TemplateParameterList* Params = DD->getTemplateParameterList(i);
757     if (VisitTemplateParameters(Params))
758       return true;
759   }
760
761   if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
762     if (Visit(TSInfo->getTypeLoc()))
763       return true;
764
765   // Visit the nested-name-specifier, if present.
766   if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
767     if (VisitNestedNameSpecifierLoc(QualifierLoc))
768       return true;
769
770   return false;
771 }
772
773 /// \brief Compare two base or member initializers based on their source order.
774 static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
775                                       CXXCtorInitializer *const *Y) {
776   return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
777 }
778
779 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
780   unsigned NumParamList = ND->getNumTemplateParameterLists();
781   for (unsigned i = 0; i < NumParamList; i++) {
782     TemplateParameterList* Params = ND->getTemplateParameterList(i);
783     if (VisitTemplateParameters(Params))
784       return true;
785   }
786
787   if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
788     // Visit the function declaration's syntactic components in the order
789     // written. This requires a bit of work.
790     TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
791     FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
792     
793     // If we have a function declared directly (without the use of a typedef),
794     // visit just the return type. Otherwise, just visit the function's type
795     // now.
796     if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL.getReturnLoc())) ||
797         (!FTL && Visit(TL)))
798       return true;
799     
800     // Visit the nested-name-specifier, if present.
801     if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
802       if (VisitNestedNameSpecifierLoc(QualifierLoc))
803         return true;
804     
805     // Visit the declaration name.
806     if (!isa<CXXDestructorDecl>(ND))
807       if (VisitDeclarationNameInfo(ND->getNameInfo()))
808         return true;
809     
810     // FIXME: Visit explicitly-specified template arguments!
811     
812     // Visit the function parameters, if we have a function type.
813     if (FTL && VisitFunctionTypeLoc(FTL, true))
814       return true;
815     
816     // FIXME: Attributes?
817   }
818   
819   if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
820     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
821       // Find the initializers that were written in the source.
822       SmallVector<CXXCtorInitializer *, 4> WrittenInits;
823       for (auto *I : Constructor->inits()) {
824         if (!I->isWritten())
825           continue;
826       
827         WrittenInits.push_back(I);
828       }
829       
830       // Sort the initializers in source order
831       llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
832                            &CompareCXXCtorInitializers);
833       
834       // Visit the initializers in source order
835       for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
836         CXXCtorInitializer *Init = WrittenInits[I];
837         if (Init->isAnyMemberInitializer()) {
838           if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
839                                         Init->getMemberLocation(), TU)))
840             return true;
841         } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
842           if (Visit(TInfo->getTypeLoc()))
843             return true;
844         }
845         
846         // Visit the initializer value.
847         if (Expr *Initializer = Init->getInit())
848           if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
849             return true;
850       } 
851     }
852     
853     if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
854       return true;
855   }
856
857   return false;
858 }
859
860 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
861   if (VisitDeclaratorDecl(D))
862     return true;
863
864   if (Expr *BitWidth = D->getBitWidth())
865     return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
866
867   return false;
868 }
869
870 bool CursorVisitor::VisitVarDecl(VarDecl *D) {
871   if (VisitDeclaratorDecl(D))
872     return true;
873
874   if (Expr *Init = D->getInit())
875     return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
876
877   return false;
878 }
879
880 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
881   if (VisitDeclaratorDecl(D))
882     return true;
883   
884   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
885     if (Expr *DefArg = D->getDefaultArgument())
886       return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
887   
888   return false;  
889 }
890
891 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
892   // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
893   // before visiting these template parameters.
894   if (VisitTemplateParameters(D->getTemplateParameters()))
895     return true;
896   
897   return VisitFunctionDecl(D->getTemplatedDecl());
898 }
899
900 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
901   // FIXME: Visit the "outer" template parameter lists on the TagDecl
902   // before visiting these template parameters.
903   if (VisitTemplateParameters(D->getTemplateParameters()))
904     return true;
905   
906   return VisitCXXRecordDecl(D->getTemplatedDecl());
907 }
908
909 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
910   if (VisitTemplateParameters(D->getTemplateParameters()))
911     return true;
912   
913   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
914       VisitTemplateArgumentLoc(D->getDefaultArgument()))
915     return true;
916   
917   return false;
918 }
919
920 bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
921   // Visit the bound, if it's explicit.
922   if (D->hasExplicitBound()) {
923     if (auto TInfo = D->getTypeSourceInfo()) {
924       if (Visit(TInfo->getTypeLoc()))
925         return true;
926     }
927   }
928
929   return false;
930 }
931
932 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
933   if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
934     if (Visit(TSInfo->getTypeLoc()))
935       return true;
936
937   for (const auto *P : ND->params()) {
938     if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
939       return true;
940   }
941
942   if (ND->isThisDeclarationADefinition() &&
943       Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
944     return true;
945
946   return false;
947 }
948
949 template <typename DeclIt>
950 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
951                                       SourceManager &SM, SourceLocation EndLoc,
952                                       SmallVectorImpl<Decl *> &Decls) {
953   DeclIt next = *DI_current;
954   while (++next != DE_current) {
955     Decl *D_next = *next;
956     if (!D_next)
957       break;
958     SourceLocation L = D_next->getLocStart();
959     if (!L.isValid())
960       break;
961     if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
962       *DI_current = next;
963       Decls.push_back(D_next);
964       continue;
965     }
966     break;
967   }
968 }
969
970 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
971   // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
972   // an @implementation can lexically contain Decls that are not properly
973   // nested in the AST.  When we identify such cases, we need to retrofit
974   // this nesting here.
975   if (!DI_current && !FileDI_current)
976     return VisitDeclContext(D);
977
978   // Scan the Decls that immediately come after the container
979   // in the current DeclContext.  If any fall within the
980   // container's lexical region, stash them into a vector
981   // for later processing.
982   SmallVector<Decl *, 24> DeclsInContainer;
983   SourceLocation EndLoc = D->getSourceRange().getEnd();
984   SourceManager &SM = AU->getSourceManager();
985   if (EndLoc.isValid()) {
986     if (DI_current) {
987       addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
988                                 DeclsInContainer);
989     } else {
990       addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
991                                 DeclsInContainer);
992     }
993   }
994
995   // The common case.
996   if (DeclsInContainer.empty())
997     return VisitDeclContext(D);
998
999   // Get all the Decls in the DeclContext, and sort them with the
1000   // additional ones we've collected.  Then visit them.
1001   for (auto *SubDecl : D->decls()) {
1002     if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1003         SubDecl->getLocStart().isInvalid())
1004       continue;
1005     DeclsInContainer.push_back(SubDecl);
1006   }
1007
1008   // Now sort the Decls so that they appear in lexical order.
1009   std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
1010             [&SM](Decl *A, Decl *B) {
1011     SourceLocation L_A = A->getLocStart();
1012     SourceLocation L_B = B->getLocStart();
1013     assert(L_A.isValid() && L_B.isValid());
1014     return SM.isBeforeInTranslationUnit(L_A, L_B);
1015   });
1016
1017   // Now visit the decls.
1018   for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1019          E = DeclsInContainer.end(); I != E; ++I) {
1020     CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1021     const Optional<bool> &V = shouldVisitCursor(Cursor);
1022     if (!V.hasValue())
1023       continue;
1024     if (!V.getValue())
1025       return false;
1026     if (Visit(Cursor, true))
1027       return true;
1028   }
1029   return false;
1030 }
1031
1032 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1033   if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1034                                    TU)))
1035     return true;
1036
1037   if (VisitObjCTypeParamList(ND->getTypeParamList()))
1038     return true;
1039
1040   ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1041   for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1042          E = ND->protocol_end(); I != E; ++I, ++PL)
1043     if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1044       return true;
1045
1046   return VisitObjCContainerDecl(ND);
1047 }
1048
1049 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1050   if (!PID->isThisDeclarationADefinition())
1051     return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1052   
1053   ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1054   for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1055        E = PID->protocol_end(); I != E; ++I, ++PL)
1056     if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1057       return true;
1058
1059   return VisitObjCContainerDecl(PID);
1060 }
1061
1062 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1063   if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1064     return true;
1065
1066   // FIXME: This implements a workaround with @property declarations also being
1067   // installed in the DeclContext for the @interface.  Eventually this code
1068   // should be removed.
1069   ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1070   if (!CDecl || !CDecl->IsClassExtension())
1071     return false;
1072
1073   ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1074   if (!ID)
1075     return false;
1076
1077   IdentifierInfo *PropertyId = PD->getIdentifier();
1078   ObjCPropertyDecl *prevDecl =
1079     ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1080
1081   if (!prevDecl)
1082     return false;
1083
1084   // Visit synthesized methods since they will be skipped when visiting
1085   // the @interface.
1086   if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1087     if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1088       if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1089         return true;
1090
1091   if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1092     if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1093       if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1094         return true;
1095
1096   return false;
1097 }
1098
1099 bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1100   if (!typeParamList)
1101     return false;
1102
1103   for (auto *typeParam : *typeParamList) {
1104     // Visit the type parameter.
1105     if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1106       return true;
1107   }
1108
1109   return false;
1110 }
1111
1112 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1113   if (!D->isThisDeclarationADefinition()) {
1114     // Forward declaration is treated like a reference.
1115     return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1116   }
1117
1118   // Objective-C type parameters.
1119   if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1120     return true;
1121
1122   // Issue callbacks for super class.
1123   if (D->getSuperClass() &&
1124       Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1125                                         D->getSuperClassLoc(),
1126                                         TU)))
1127     return true;
1128
1129   if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1130     if (Visit(SuperClassTInfo->getTypeLoc()))
1131       return true;
1132
1133   ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1134   for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1135          E = D->protocol_end(); I != E; ++I, ++PL)
1136     if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1137       return true;
1138
1139   return VisitObjCContainerDecl(D);
1140 }
1141
1142 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1143   return VisitObjCContainerDecl(D);
1144 }
1145
1146 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1147   // 'ID' could be null when dealing with invalid code.
1148   if (ObjCInterfaceDecl *ID = D->getClassInterface())
1149     if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1150       return true;
1151
1152   return VisitObjCImplDecl(D);
1153 }
1154
1155 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1156 #if 0
1157   // Issue callbacks for super class.
1158   // FIXME: No source location information!
1159   if (D->getSuperClass() &&
1160       Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1161                                         D->getSuperClassLoc(),
1162                                         TU)))
1163     return true;
1164 #endif
1165
1166   return VisitObjCImplDecl(D);
1167 }
1168
1169 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1170   if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1171     if (PD->isIvarNameSpecified())
1172       return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1173   
1174   return false;
1175 }
1176
1177 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1178   return VisitDeclContext(D);
1179 }
1180
1181 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1182   // Visit nested-name-specifier.
1183   if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1184     if (VisitNestedNameSpecifierLoc(QualifierLoc))
1185       return true;
1186   
1187   return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(), 
1188                                       D->getTargetNameLoc(), TU));
1189 }
1190
1191 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1192   // Visit nested-name-specifier.
1193   if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1194     if (VisitNestedNameSpecifierLoc(QualifierLoc))
1195       return true;
1196   }
1197   
1198   if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1199     return true;
1200     
1201   return VisitDeclarationNameInfo(D->getNameInfo());
1202 }
1203
1204 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1205   // Visit nested-name-specifier.
1206   if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1207     if (VisitNestedNameSpecifierLoc(QualifierLoc))
1208       return true;
1209
1210   return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1211                                       D->getIdentLocation(), TU));
1212 }
1213
1214 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1215   // Visit nested-name-specifier.
1216   if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1217     if (VisitNestedNameSpecifierLoc(QualifierLoc))
1218       return true;
1219   }
1220
1221   return VisitDeclarationNameInfo(D->getNameInfo());
1222 }
1223
1224 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1225                                                UnresolvedUsingTypenameDecl *D) {
1226   // Visit nested-name-specifier.
1227   if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1228     if (VisitNestedNameSpecifierLoc(QualifierLoc))
1229       return true;
1230   
1231   return false;
1232 }
1233
1234 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1235   switch (Name.getName().getNameKind()) {
1236   case clang::DeclarationName::Identifier:
1237   case clang::DeclarationName::CXXLiteralOperatorName:
1238   case clang::DeclarationName::CXXOperatorName:
1239   case clang::DeclarationName::CXXUsingDirective:
1240     return false;
1241       
1242   case clang::DeclarationName::CXXConstructorName:
1243   case clang::DeclarationName::CXXDestructorName:
1244   case clang::DeclarationName::CXXConversionFunctionName:
1245     if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1246       return Visit(TSInfo->getTypeLoc());
1247     return false;
1248
1249   case clang::DeclarationName::ObjCZeroArgSelector:
1250   case clang::DeclarationName::ObjCOneArgSelector:
1251   case clang::DeclarationName::ObjCMultiArgSelector:
1252     // FIXME: Per-identifier location info?
1253     return false;
1254   }
1255
1256   llvm_unreachable("Invalid DeclarationName::Kind!");
1257 }
1258
1259 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS, 
1260                                              SourceRange Range) {
1261   // FIXME: This whole routine is a hack to work around the lack of proper
1262   // source information in nested-name-specifiers (PR5791). Since we do have
1263   // a beginning source location, we can visit the first component of the
1264   // nested-name-specifier, if it's a single-token component.
1265   if (!NNS)
1266     return false;
1267   
1268   // Get the first component in the nested-name-specifier.
1269   while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1270     NNS = Prefix;
1271   
1272   switch (NNS->getKind()) {
1273   case NestedNameSpecifier::Namespace:
1274     return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1275                                         TU));
1276
1277   case NestedNameSpecifier::NamespaceAlias:
1278     return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 
1279                                         Range.getBegin(), TU));
1280
1281   case NestedNameSpecifier::TypeSpec: {
1282     // If the type has a form where we know that the beginning of the source
1283     // range matches up with a reference cursor. Visit the appropriate reference
1284     // cursor.
1285     const Type *T = NNS->getAsType();
1286     if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1287       return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1288     if (const TagType *Tag = dyn_cast<TagType>(T))
1289       return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1290     if (const TemplateSpecializationType *TST
1291                                       = dyn_cast<TemplateSpecializationType>(T))
1292       return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1293     break;
1294   }
1295       
1296   case NestedNameSpecifier::TypeSpecWithTemplate:
1297   case NestedNameSpecifier::Global:
1298   case NestedNameSpecifier::Identifier:
1299   case NestedNameSpecifier::Super:
1300     break;      
1301   }
1302   
1303   return false;
1304 }
1305
1306 bool 
1307 CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1308   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1309   for (; Qualifier; Qualifier = Qualifier.getPrefix())
1310     Qualifiers.push_back(Qualifier);
1311   
1312   while (!Qualifiers.empty()) {
1313     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1314     NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1315     switch (NNS->getKind()) {
1316     case NestedNameSpecifier::Namespace:
1317       if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), 
1318                                        Q.getLocalBeginLoc(),
1319                                        TU)))
1320         return true;
1321         
1322       break;
1323       
1324     case NestedNameSpecifier::NamespaceAlias:
1325       if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 
1326                                        Q.getLocalBeginLoc(),
1327                                        TU)))
1328         return true;
1329         
1330       break;
1331         
1332     case NestedNameSpecifier::TypeSpec:
1333     case NestedNameSpecifier::TypeSpecWithTemplate:
1334       if (Visit(Q.getTypeLoc()))
1335         return true;
1336         
1337       break;
1338         
1339     case NestedNameSpecifier::Global:
1340     case NestedNameSpecifier::Identifier:
1341     case NestedNameSpecifier::Super:
1342       break;              
1343     }
1344   }
1345   
1346   return false;
1347 }
1348
1349 bool CursorVisitor::VisitTemplateParameters(
1350                                           const TemplateParameterList *Params) {
1351   if (!Params)
1352     return false;
1353   
1354   for (TemplateParameterList::const_iterator P = Params->begin(),
1355                                           PEnd = Params->end();
1356        P != PEnd; ++P) {
1357     if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1358       return true;
1359   }
1360   
1361   return false;
1362 }
1363
1364 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1365   switch (Name.getKind()) {
1366   case TemplateName::Template:
1367     return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1368
1369   case TemplateName::OverloadedTemplate:
1370     // Visit the overloaded template set.
1371     if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1372       return true;
1373
1374     return false;
1375
1376   case TemplateName::DependentTemplate:
1377     // FIXME: Visit nested-name-specifier.
1378     return false;
1379       
1380   case TemplateName::QualifiedTemplate:
1381     // FIXME: Visit nested-name-specifier.
1382     return Visit(MakeCursorTemplateRef(
1383                                   Name.getAsQualifiedTemplateName()->getDecl(), 
1384                                        Loc, TU));
1385
1386   case TemplateName::SubstTemplateTemplateParm:
1387     return Visit(MakeCursorTemplateRef(
1388                          Name.getAsSubstTemplateTemplateParm()->getParameter(),
1389                                        Loc, TU));
1390       
1391   case TemplateName::SubstTemplateTemplateParmPack:
1392     return Visit(MakeCursorTemplateRef(
1393                   Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1394                                        Loc, TU));
1395   }
1396
1397   llvm_unreachable("Invalid TemplateName::Kind!");
1398 }
1399
1400 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1401   switch (TAL.getArgument().getKind()) {
1402   case TemplateArgument::Null:
1403   case TemplateArgument::Integral:
1404   case TemplateArgument::Pack:
1405     return false;
1406       
1407   case TemplateArgument::Type:
1408     if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1409       return Visit(TSInfo->getTypeLoc());
1410     return false;
1411       
1412   case TemplateArgument::Declaration:
1413     if (Expr *E = TAL.getSourceDeclExpression())
1414       return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1415     return false;
1416
1417   case TemplateArgument::NullPtr:
1418     if (Expr *E = TAL.getSourceNullPtrExpression())
1419       return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1420     return false;
1421
1422   case TemplateArgument::Expression:
1423     if (Expr *E = TAL.getSourceExpression())
1424       return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1425     return false;
1426   
1427   case TemplateArgument::Template:
1428   case TemplateArgument::TemplateExpansion:
1429     if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1430       return true;
1431       
1432     return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(), 
1433                              TAL.getTemplateNameLoc());
1434   }
1435
1436   llvm_unreachable("Invalid TemplateArgument::Kind!");
1437 }
1438
1439 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1440   return VisitDeclContext(D);
1441 }
1442
1443 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1444   return Visit(TL.getUnqualifiedLoc());
1445 }
1446
1447 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1448   ASTContext &Context = AU->getASTContext();
1449
1450   // Some builtin types (such as Objective-C's "id", "sel", and
1451   // "Class") have associated declarations. Create cursors for those.
1452   QualType VisitType;
1453   switch (TL.getTypePtr()->getKind()) {
1454
1455   case BuiltinType::Void:
1456   case BuiltinType::NullPtr:
1457   case BuiltinType::Dependent:
1458   case BuiltinType::OCLImage1d:
1459   case BuiltinType::OCLImage1dArray:
1460   case BuiltinType::OCLImage1dBuffer:
1461   case BuiltinType::OCLImage2d:
1462   case BuiltinType::OCLImage2dArray:
1463   case BuiltinType::OCLImage2dDepth:
1464   case BuiltinType::OCLImage2dArrayDepth:
1465   case BuiltinType::OCLImage2dMSAA:
1466   case BuiltinType::OCLImage2dArrayMSAA:
1467   case BuiltinType::OCLImage2dMSAADepth:
1468   case BuiltinType::OCLImage2dArrayMSAADepth:
1469   case BuiltinType::OCLImage3d:
1470   case BuiltinType::OCLSampler:
1471   case BuiltinType::OCLEvent:
1472   case BuiltinType::OCLClkEvent:
1473   case BuiltinType::OCLQueue:
1474   case BuiltinType::OCLNDRange:
1475   case BuiltinType::OCLReserveID:
1476 #define BUILTIN_TYPE(Id, SingletonId)
1477 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1478 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1479 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1480 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1481 #include "clang/AST/BuiltinTypes.def"
1482     break;
1483
1484   case BuiltinType::ObjCId:
1485     VisitType = Context.getObjCIdType();
1486     break;
1487
1488   case BuiltinType::ObjCClass:
1489     VisitType = Context.getObjCClassType();
1490     break;
1491
1492   case BuiltinType::ObjCSel:
1493     VisitType = Context.getObjCSelType();
1494     break;
1495   }
1496
1497   if (!VisitType.isNull()) {
1498     if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1499       return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1500                                      TU));
1501   }
1502
1503   return false;
1504 }
1505
1506 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1507   return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1508 }
1509
1510 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1511   return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1512 }
1513
1514 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1515   if (TL.isDefinition())
1516     return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1517
1518   return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1519 }
1520
1521 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1522   return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1523 }
1524
1525 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1526   if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1527     return true;
1528
1529   return false;
1530 }
1531
1532 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1533   if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1534     return true;
1535
1536   for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1537     if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1538       return true;
1539   }
1540
1541   for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1542     if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1543                                         TU)))
1544       return true;
1545   }
1546
1547   return false;
1548 }
1549
1550 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1551   return Visit(TL.getPointeeLoc());
1552 }
1553
1554 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1555   return Visit(TL.getInnerLoc());
1556 }
1557
1558 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1559   return Visit(TL.getPointeeLoc());
1560 }
1561
1562 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1563   return Visit(TL.getPointeeLoc());
1564 }
1565
1566 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1567   return Visit(TL.getPointeeLoc());
1568 }
1569
1570 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1571   return Visit(TL.getPointeeLoc());
1572 }
1573
1574 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1575   return Visit(TL.getPointeeLoc());
1576 }
1577
1578 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1579   return Visit(TL.getModifiedLoc());
1580 }
1581
1582 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL, 
1583                                          bool SkipResultType) {
1584   if (!SkipResultType && Visit(TL.getReturnLoc()))
1585     return true;
1586
1587   for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1588     if (Decl *D = TL.getParam(I))
1589       if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1590         return true;
1591
1592   return false;
1593 }
1594
1595 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1596   if (Visit(TL.getElementLoc()))
1597     return true;
1598
1599   if (Expr *Size = TL.getSizeExpr())
1600     return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1601
1602   return false;
1603 }
1604
1605 bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1606   return Visit(TL.getOriginalLoc());
1607 }
1608
1609 bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1610   return Visit(TL.getOriginalLoc());
1611 }
1612
1613 bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1614                                              TemplateSpecializationTypeLoc TL) {
1615   // Visit the template name.
1616   if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 
1617                         TL.getTemplateNameLoc()))
1618     return true;
1619   
1620   // Visit the template arguments.
1621   for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1622     if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1623       return true;
1624   
1625   return false;
1626 }
1627
1628 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1629   return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1630 }
1631
1632 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1633   if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1634     return Visit(TSInfo->getTypeLoc());
1635
1636   return false;
1637 }
1638
1639 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1640   if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1641     return Visit(TSInfo->getTypeLoc());
1642
1643   return false;
1644 }
1645
1646 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1647   if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1648     return true;
1649   
1650   return false;
1651 }
1652
1653 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1654                                     DependentTemplateSpecializationTypeLoc TL) {
1655   // Visit the nested-name-specifier, if there is one.
1656   if (TL.getQualifierLoc() &&
1657       VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1658     return true;
1659   
1660   // Visit the template arguments.
1661   for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1662     if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1663       return true;
1664
1665   return false;
1666 }
1667
1668 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1669   if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1670     return true;
1671   
1672   return Visit(TL.getNamedTypeLoc());
1673 }
1674
1675 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1676   return Visit(TL.getPatternLoc());
1677 }
1678
1679 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1680   if (Expr *E = TL.getUnderlyingExpr())
1681     return Visit(MakeCXCursor(E, StmtParent, TU));
1682
1683   return false;
1684 }
1685
1686 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1687   return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1688 }
1689
1690 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1691   return Visit(TL.getValueLoc());
1692 }
1693
1694 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1695 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1696   return Visit##PARENT##Loc(TL); \
1697 }
1698
1699 DEFAULT_TYPELOC_IMPL(Complex, Type)
1700 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1701 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1702 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1703 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1704 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1705 DEFAULT_TYPELOC_IMPL(Vector, Type)
1706 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1707 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1708 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1709 DEFAULT_TYPELOC_IMPL(Record, TagType)
1710 DEFAULT_TYPELOC_IMPL(Enum, TagType)
1711 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1712 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1713 DEFAULT_TYPELOC_IMPL(Auto, Type)
1714
1715 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1716   // Visit the nested-name-specifier, if present.
1717   if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1718     if (VisitNestedNameSpecifierLoc(QualifierLoc))
1719       return true;
1720
1721   if (D->isCompleteDefinition()) {
1722     for (const auto &I : D->bases()) {
1723       if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1724         return true;
1725     }
1726   }
1727
1728   return VisitTagDecl(D);
1729 }
1730
1731 bool CursorVisitor::VisitAttributes(Decl *D) {
1732   for (const auto *I : D->attrs())
1733     if (Visit(MakeCXCursor(I, D, TU)))
1734         return true;
1735
1736   return false;
1737 }
1738
1739 //===----------------------------------------------------------------------===//
1740 // Data-recursive visitor methods.
1741 //===----------------------------------------------------------------------===//
1742
1743 namespace {
1744 #define DEF_JOB(NAME, DATA, KIND)\
1745 class NAME : public VisitorJob {\
1746 public:\
1747   NAME(const DATA *d, CXCursor parent) : \
1748       VisitorJob(parent, VisitorJob::KIND, d) {} \
1749   static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1750   const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
1751 };
1752
1753 DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1754 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1755 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1756 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1757 DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo, 
1758         ExplicitTemplateArgsVisitKind)
1759 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1760 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1761 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1762 #undef DEF_JOB
1763
1764 class DeclVisit : public VisitorJob {
1765 public:
1766   DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
1767     VisitorJob(parent, VisitorJob::DeclVisitKind,
1768                D, isFirst ? (void*) 1 : (void*) nullptr) {}
1769   static bool classof(const VisitorJob *VJ) {
1770     return VJ->getKind() == DeclVisitKind;
1771   }
1772   const Decl *get() const { return static_cast<const Decl *>(data[0]); }
1773   bool isFirst() const { return data[1] != nullptr; }
1774 };
1775 class TypeLocVisit : public VisitorJob {
1776 public:
1777   TypeLocVisit(TypeLoc tl, CXCursor parent) :
1778     VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1779                tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1780
1781   static bool classof(const VisitorJob *VJ) {
1782     return VJ->getKind() == TypeLocVisitKind;
1783   }
1784
1785   TypeLoc get() const { 
1786     QualType T = QualType::getFromOpaquePtr(data[0]);
1787     return TypeLoc(T, const_cast<void *>(data[1]));
1788   }
1789 };
1790
1791 class LabelRefVisit : public VisitorJob {
1792 public:
1793   LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1794     : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1795                  labelLoc.getPtrEncoding()) {}
1796   
1797   static bool classof(const VisitorJob *VJ) {
1798     return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1799   }
1800   const LabelDecl *get() const {
1801     return static_cast<const LabelDecl *>(data[0]);
1802   }
1803   SourceLocation getLoc() const { 
1804     return SourceLocation::getFromPtrEncoding(data[1]); }
1805 };
1806   
1807 class NestedNameSpecifierLocVisit : public VisitorJob {
1808 public:
1809   NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1810     : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1811                  Qualifier.getNestedNameSpecifier(),
1812                  Qualifier.getOpaqueData()) { }
1813   
1814   static bool classof(const VisitorJob *VJ) {
1815     return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1816   }
1817   
1818   NestedNameSpecifierLoc get() const {
1819     return NestedNameSpecifierLoc(
1820             const_cast<NestedNameSpecifier *>(
1821               static_cast<const NestedNameSpecifier *>(data[0])),
1822             const_cast<void *>(data[1]));
1823   }
1824 };
1825   
1826 class DeclarationNameInfoVisit : public VisitorJob {
1827 public:
1828   DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
1829     : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1830   static bool classof(const VisitorJob *VJ) {
1831     return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1832   }
1833   DeclarationNameInfo get() const {
1834     const Stmt *S = static_cast<const Stmt *>(data[0]);
1835     switch (S->getStmtClass()) {
1836     default:
1837       llvm_unreachable("Unhandled Stmt");
1838     case clang::Stmt::MSDependentExistsStmtClass:
1839       return cast<MSDependentExistsStmt>(S)->getNameInfo();
1840     case Stmt::CXXDependentScopeMemberExprClass:
1841       return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1842     case Stmt::DependentScopeDeclRefExprClass:
1843       return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1844     case Stmt::OMPCriticalDirectiveClass:
1845       return cast<OMPCriticalDirective>(S)->getDirectiveName();
1846     }
1847   }
1848 };
1849 class MemberRefVisit : public VisitorJob {
1850 public:
1851   MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
1852     : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1853                  L.getPtrEncoding()) {}
1854   static bool classof(const VisitorJob *VJ) {
1855     return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1856   }
1857   const FieldDecl *get() const {
1858     return static_cast<const FieldDecl *>(data[0]);
1859   }
1860   SourceLocation getLoc() const {
1861     return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1862   }
1863 };
1864 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
1865   friend class OMPClauseEnqueue;
1866   VisitorWorkList &WL;
1867   CXCursor Parent;
1868 public:
1869   EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1870     : WL(wl), Parent(parent) {}
1871
1872   void VisitAddrLabelExpr(const AddrLabelExpr *E);
1873   void VisitBlockExpr(const BlockExpr *B);
1874   void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1875   void VisitCompoundStmt(const CompoundStmt *S);
1876   void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1877   void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1878   void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1879   void VisitCXXNewExpr(const CXXNewExpr *E);
1880   void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1881   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1882   void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1883   void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1884   void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1885   void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1886   void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1887   void VisitCXXCatchStmt(const CXXCatchStmt *S);
1888   void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
1889   void VisitDeclRefExpr(const DeclRefExpr *D);
1890   void VisitDeclStmt(const DeclStmt *S);
1891   void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1892   void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1893   void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1894   void VisitForStmt(const ForStmt *FS);
1895   void VisitGotoStmt(const GotoStmt *GS);
1896   void VisitIfStmt(const IfStmt *If);
1897   void VisitInitListExpr(const InitListExpr *IE);
1898   void VisitMemberExpr(const MemberExpr *M);
1899   void VisitOffsetOfExpr(const OffsetOfExpr *E);
1900   void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1901   void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1902   void VisitOverloadExpr(const OverloadExpr *E);
1903   void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1904   void VisitStmt(const Stmt *S);
1905   void VisitSwitchStmt(const SwitchStmt *S);
1906   void VisitWhileStmt(const WhileStmt *W);
1907   void VisitTypeTraitExpr(const TypeTraitExpr *E);
1908   void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1909   void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1910   void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1911   void VisitVAArgExpr(const VAArgExpr *E);
1912   void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1913   void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
1914   void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
1915   void VisitLambdaExpr(const LambdaExpr *E);
1916   void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
1917   void VisitOMPLoopDirective(const OMPLoopDirective *D);
1918   void VisitOMPParallelDirective(const OMPParallelDirective *D);
1919   void VisitOMPSimdDirective(const OMPSimdDirective *D);
1920   void VisitOMPForDirective(const OMPForDirective *D);
1921   void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
1922   void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
1923   void VisitOMPSectionDirective(const OMPSectionDirective *D);
1924   void VisitOMPSingleDirective(const OMPSingleDirective *D);
1925   void VisitOMPMasterDirective(const OMPMasterDirective *D);
1926   void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
1927   void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
1928   void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
1929   void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
1930   void VisitOMPTaskDirective(const OMPTaskDirective *D);
1931   void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
1932   void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
1933   void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
1934   void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
1935   void
1936   VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
1937   void VisitOMPCancelDirective(const OMPCancelDirective *D);
1938   void VisitOMPFlushDirective(const OMPFlushDirective *D);
1939   void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
1940   void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
1941   void VisitOMPTargetDirective(const OMPTargetDirective *D);
1942   void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
1943   void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
1944
1945 private:
1946   void AddDeclarationNameInfo(const Stmt *S);
1947   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1948   void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1949   void AddMemberRef(const FieldDecl *D, SourceLocation L);
1950   void AddStmt(const Stmt *S);
1951   void AddDecl(const Decl *D, bool isFirst = true);
1952   void AddTypeLoc(TypeSourceInfo *TI);
1953   void EnqueueChildren(const Stmt *S);
1954   void EnqueueChildren(const OMPClause *S);
1955 };
1956 } // end anonyous namespace
1957
1958 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
1959   // 'S' should always be non-null, since it comes from the
1960   // statement we are visiting.
1961   WL.push_back(DeclarationNameInfoVisit(S, Parent));
1962 }
1963
1964 void 
1965 EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1966   if (Qualifier)
1967     WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1968 }
1969
1970 void EnqueueVisitor::AddStmt(const Stmt *S) {
1971   if (S)
1972     WL.push_back(StmtVisit(S, Parent));
1973 }
1974 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
1975   if (D)
1976     WL.push_back(DeclVisit(D, Parent, isFirst));
1977 }
1978 void EnqueueVisitor::
1979   AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1980   if (A)
1981     WL.push_back(ExplicitTemplateArgsVisit(A, Parent));
1982 }
1983 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
1984   if (D)
1985     WL.push_back(MemberRefVisit(D, L, Parent));
1986 }
1987 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1988   if (TI)
1989     WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1990  }
1991 void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
1992   unsigned size = WL.size();
1993   for (const Stmt *SubStmt : S->children()) {
1994     AddStmt(SubStmt);
1995   }
1996   if (size == WL.size())
1997     return;
1998   // Now reverse the entries we just added.  This will match the DFS
1999   // ordering performed by the worklist.
2000   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2001   std::reverse(I, E);
2002 }
2003 namespace {
2004 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2005   EnqueueVisitor *Visitor;
2006   /// \brief Process clauses with list of variables.
2007   template <typename T>
2008   void VisitOMPClauseList(T *Node);
2009 public:
2010   OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2011 #define OPENMP_CLAUSE(Name, Class)                                             \
2012   void Visit##Class(const Class *C);
2013 #include "clang/Basic/OpenMPKinds.def"
2014 };
2015
2016 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2017   Visitor->AddStmt(C->getCondition());
2018 }
2019
2020 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2021   Visitor->AddStmt(C->getCondition());
2022 }
2023
2024 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2025   Visitor->AddStmt(C->getNumThreads());
2026 }
2027
2028 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2029   Visitor->AddStmt(C->getSafelen());
2030 }
2031
2032 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2033   Visitor->AddStmt(C->getSimdlen());
2034 }
2035
2036 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2037   Visitor->AddStmt(C->getNumForLoops());
2038 }
2039
2040 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
2041
2042 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2043
2044 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2045   Visitor->AddStmt(C->getChunkSize());
2046   Visitor->AddStmt(C->getHelperChunkSize());
2047 }
2048
2049 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2050   Visitor->AddStmt(C->getNumForLoops());
2051 }
2052
2053 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2054
2055 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2056
2057 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2058
2059 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2060
2061 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2062
2063 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2064
2065 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2066
2067 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2068
2069 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2070   Visitor->AddStmt(C->getDevice());
2071 }
2072
2073 template<typename T>
2074 void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2075   for (const auto *I : Node->varlists()) {
2076     Visitor->AddStmt(I);
2077   }
2078 }
2079
2080 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2081   VisitOMPClauseList(C);
2082   for (const auto *E : C->private_copies()) {
2083     Visitor->AddStmt(E);
2084   }
2085 }
2086 void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2087                                         const OMPFirstprivateClause *C) {
2088   VisitOMPClauseList(C);
2089 }
2090 void OMPClauseEnqueue::VisitOMPLastprivateClause(
2091                                         const OMPLastprivateClause *C) {
2092   VisitOMPClauseList(C);
2093   for (auto *E : C->private_copies()) {
2094     Visitor->AddStmt(E);
2095   }
2096   for (auto *E : C->source_exprs()) {
2097     Visitor->AddStmt(E);
2098   }
2099   for (auto *E : C->destination_exprs()) {
2100     Visitor->AddStmt(E);
2101   }
2102   for (auto *E : C->assignment_ops()) {
2103     Visitor->AddStmt(E);
2104   }
2105 }
2106 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2107   VisitOMPClauseList(C);
2108 }
2109 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2110   VisitOMPClauseList(C);
2111   for (auto *E : C->lhs_exprs()) {
2112     Visitor->AddStmt(E);
2113   }
2114   for (auto *E : C->rhs_exprs()) {
2115     Visitor->AddStmt(E);
2116   }
2117   for (auto *E : C->reduction_ops()) {
2118     Visitor->AddStmt(E);
2119   }
2120 }
2121 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2122   VisitOMPClauseList(C);
2123   for (const auto *E : C->privates()) {
2124     Visitor->AddStmt(E);
2125   }
2126   for (const auto *E : C->inits()) {
2127     Visitor->AddStmt(E);
2128   }
2129   for (const auto *E : C->updates()) {
2130     Visitor->AddStmt(E);
2131   }
2132   for (const auto *E : C->finals()) {
2133     Visitor->AddStmt(E);
2134   }
2135   Visitor->AddStmt(C->getStep());
2136   Visitor->AddStmt(C->getCalcStep());
2137 }
2138 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2139   VisitOMPClauseList(C);
2140   Visitor->AddStmt(C->getAlignment());
2141 }
2142 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2143   VisitOMPClauseList(C);
2144   for (auto *E : C->source_exprs()) {
2145     Visitor->AddStmt(E);
2146   }
2147   for (auto *E : C->destination_exprs()) {
2148     Visitor->AddStmt(E);
2149   }
2150   for (auto *E : C->assignment_ops()) {
2151     Visitor->AddStmt(E);
2152   }
2153 }
2154 void
2155 OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2156   VisitOMPClauseList(C);
2157   for (auto *E : C->source_exprs()) {
2158     Visitor->AddStmt(E);
2159   }
2160   for (auto *E : C->destination_exprs()) {
2161     Visitor->AddStmt(E);
2162   }
2163   for (auto *E : C->assignment_ops()) {
2164     Visitor->AddStmt(E);
2165   }
2166 }
2167 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2168   VisitOMPClauseList(C);
2169 }
2170 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2171   VisitOMPClauseList(C);
2172 }
2173 }
2174
2175 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2176   unsigned size = WL.size();
2177   OMPClauseEnqueue Visitor(this);
2178   Visitor.Visit(S);
2179   if (size == WL.size())
2180     return;
2181   // Now reverse the entries we just added.  This will match the DFS
2182   // ordering performed by the worklist.
2183   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2184   std::reverse(I, E);
2185 }
2186 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2187   WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2188 }
2189 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2190   AddDecl(B->getBlockDecl());
2191 }
2192 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2193   EnqueueChildren(E);
2194   AddTypeLoc(E->getTypeSourceInfo());
2195 }
2196 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2197   for (auto &I : llvm::reverse(S->body()))
2198     AddStmt(I);
2199 }
2200 void EnqueueVisitor::
2201 VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
2202   AddStmt(S->getSubStmt());
2203   AddDeclarationNameInfo(S);
2204   if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2205     AddNestedNameSpecifierLoc(QualifierLoc);
2206 }
2207
2208 void EnqueueVisitor::
2209 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
2210   AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2211   AddDeclarationNameInfo(E);
2212   if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2213     AddNestedNameSpecifierLoc(QualifierLoc);
2214   if (!E->isImplicitAccess())
2215     AddStmt(E->getBase());
2216 }
2217 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2218   // Enqueue the initializer , if any.
2219   AddStmt(E->getInitializer());
2220   // Enqueue the array size, if any.
2221   AddStmt(E->getArraySize());
2222   // Enqueue the allocated type.
2223   AddTypeLoc(E->getAllocatedTypeSourceInfo());
2224   // Enqueue the placement arguments.
2225   for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2226     AddStmt(E->getPlacementArg(I-1));
2227 }
2228 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2229   for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2230     AddStmt(CE->getArg(I-1));
2231   AddStmt(CE->getCallee());
2232   AddStmt(CE->getArg(0));
2233 }
2234 void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2235                                         const CXXPseudoDestructorExpr *E) {
2236   // Visit the name of the type being destroyed.
2237   AddTypeLoc(E->getDestroyedTypeInfo());
2238   // Visit the scope type that looks disturbingly like the nested-name-specifier
2239   // but isn't.
2240   AddTypeLoc(E->getScopeTypeInfo());
2241   // Visit the nested-name-specifier.
2242   if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2243     AddNestedNameSpecifierLoc(QualifierLoc);
2244   // Visit base expression.
2245   AddStmt(E->getBase());
2246 }
2247 void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2248                                         const CXXScalarValueInitExpr *E) {
2249   AddTypeLoc(E->getTypeSourceInfo());
2250 }
2251 void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2252                                         const CXXTemporaryObjectExpr *E) {
2253   EnqueueChildren(E);
2254   AddTypeLoc(E->getTypeSourceInfo());
2255 }
2256 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2257   EnqueueChildren(E);
2258   if (E->isTypeOperand())
2259     AddTypeLoc(E->getTypeOperandSourceInfo());
2260 }
2261
2262 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2263                                         const CXXUnresolvedConstructExpr *E) {
2264   EnqueueChildren(E);
2265   AddTypeLoc(E->getTypeSourceInfo());
2266 }
2267 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2268   EnqueueChildren(E);
2269   if (E->isTypeOperand())
2270     AddTypeLoc(E->getTypeOperandSourceInfo());
2271 }
2272
2273 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2274   EnqueueChildren(S);
2275   AddDecl(S->getExceptionDecl());
2276 }
2277
2278 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2279   AddStmt(S->getBody());
2280   AddStmt(S->getRangeInit());
2281   AddDecl(S->getLoopVariable());
2282 }
2283
2284 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2285   if (DR->hasExplicitTemplateArgs()) {
2286     AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
2287   }
2288   WL.push_back(DeclRefExprParts(DR, Parent));
2289 }
2290 void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2291                                         const DependentScopeDeclRefExpr *E) {
2292   AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2293   AddDeclarationNameInfo(E);
2294   AddNestedNameSpecifierLoc(E->getQualifierLoc());
2295 }
2296 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2297   unsigned size = WL.size();
2298   bool isFirst = true;
2299   for (const auto *D : S->decls()) {
2300     AddDecl(D, isFirst);
2301     isFirst = false;
2302   }
2303   if (size == WL.size())
2304     return;
2305   // Now reverse the entries we just added.  This will match the DFS
2306   // ordering performed by the worklist.
2307   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2308   std::reverse(I, E);
2309 }
2310 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2311   AddStmt(E->getInit());
2312   for (DesignatedInitExpr::const_reverse_designators_iterator
2313          D = E->designators_rbegin(), DEnd = E->designators_rend();
2314          D != DEnd; ++D) {
2315     if (D->isFieldDesignator()) {
2316       if (FieldDecl *Field = D->getField())
2317         AddMemberRef(Field, D->getFieldLoc());
2318       continue;
2319     }
2320     if (D->isArrayDesignator()) {
2321       AddStmt(E->getArrayIndex(*D));
2322       continue;
2323     }
2324     assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2325     AddStmt(E->getArrayRangeEnd(*D));
2326     AddStmt(E->getArrayRangeStart(*D));
2327   }
2328 }
2329 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2330   EnqueueChildren(E);
2331   AddTypeLoc(E->getTypeInfoAsWritten());
2332 }
2333 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2334   AddStmt(FS->getBody());
2335   AddStmt(FS->getInc());
2336   AddStmt(FS->getCond());
2337   AddDecl(FS->getConditionVariable());
2338   AddStmt(FS->getInit());
2339 }
2340 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2341   WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2342 }
2343 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2344   AddStmt(If->getElse());
2345   AddStmt(If->getThen());
2346   AddStmt(If->getCond());
2347   AddDecl(If->getConditionVariable());
2348 }
2349 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2350   // We care about the syntactic form of the initializer list, only.
2351   if (InitListExpr *Syntactic = IE->getSyntacticForm())
2352     IE = Syntactic;
2353   EnqueueChildren(IE);
2354 }
2355 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2356   WL.push_back(MemberExprParts(M, Parent));
2357   
2358   // If the base of the member access expression is an implicit 'this', don't
2359   // visit it.
2360   // FIXME: If we ever want to show these implicit accesses, this will be
2361   // unfortunate. However, clang_getCursor() relies on this behavior.
2362   if (M->isImplicitAccess())
2363     return;
2364
2365   // Ignore base anonymous struct/union fields, otherwise they will shadow the
2366   // real field that that we are interested in.
2367   if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2368     if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2369       if (FD->isAnonymousStructOrUnion()) {
2370         AddStmt(SubME->getBase());
2371         return;
2372       }
2373     }
2374   }
2375
2376   AddStmt(M->getBase());
2377 }
2378 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2379   AddTypeLoc(E->getEncodedTypeSourceInfo());
2380 }
2381 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2382   EnqueueChildren(M);
2383   AddTypeLoc(M->getClassReceiverTypeInfo());
2384 }
2385 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2386   // Visit the components of the offsetof expression.
2387   for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2388     typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2389     const OffsetOfNode &Node = E->getComponent(I-1);
2390     switch (Node.getKind()) {
2391     case OffsetOfNode::Array:
2392       AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2393       break;
2394     case OffsetOfNode::Field:
2395       AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2396       break;
2397     case OffsetOfNode::Identifier:
2398     case OffsetOfNode::Base:
2399       continue;
2400     }
2401   }
2402   // Visit the type into which we're computing the offset.
2403   AddTypeLoc(E->getTypeSourceInfo());
2404 }
2405 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2406   AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2407   WL.push_back(OverloadExprParts(E, Parent));
2408 }
2409 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2410                                         const UnaryExprOrTypeTraitExpr *E) {
2411   EnqueueChildren(E);
2412   if (E->isArgumentType())
2413     AddTypeLoc(E->getArgumentTypeInfo());
2414 }
2415 void EnqueueVisitor::VisitStmt(const Stmt *S) {
2416   EnqueueChildren(S);
2417 }
2418 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2419   AddStmt(S->getBody());
2420   AddStmt(S->getCond());
2421   AddDecl(S->getConditionVariable());
2422 }
2423
2424 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2425   AddStmt(W->getBody());
2426   AddStmt(W->getCond());
2427   AddDecl(W->getConditionVariable());
2428 }
2429
2430 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2431   for (unsigned I = E->getNumArgs(); I > 0; --I)
2432     AddTypeLoc(E->getArg(I-1));
2433 }
2434
2435 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2436   AddTypeLoc(E->getQueriedTypeSourceInfo());
2437 }
2438
2439 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2440   EnqueueChildren(E);
2441 }
2442
2443 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2444   VisitOverloadExpr(U);
2445   if (!U->isImplicitAccess())
2446     AddStmt(U->getBase());
2447 }
2448 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2449   AddStmt(E->getSubExpr());
2450   AddTypeLoc(E->getWrittenTypeInfo());
2451 }
2452 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2453   WL.push_back(SizeOfPackExprParts(E, Parent));
2454 }
2455 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2456   // If the opaque value has a source expression, just transparently
2457   // visit that.  This is useful for (e.g.) pseudo-object expressions.
2458   if (Expr *SourceExpr = E->getSourceExpr())
2459     return Visit(SourceExpr);
2460 }
2461 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2462   AddStmt(E->getBody());
2463   WL.push_back(LambdaExprParts(E, Parent));
2464 }
2465 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2466   // Treat the expression like its syntactic form.
2467   Visit(E->getSyntacticForm());
2468 }
2469
2470 void EnqueueVisitor::VisitOMPExecutableDirective(
2471   const OMPExecutableDirective *D) {
2472   EnqueueChildren(D);
2473   for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2474                                        E = D->clauses().end();
2475        I != E; ++I)
2476     EnqueueChildren(*I);
2477 }
2478
2479 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2480   VisitOMPExecutableDirective(D);
2481 }
2482
2483 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2484   VisitOMPExecutableDirective(D);
2485 }
2486
2487 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2488   VisitOMPLoopDirective(D);
2489 }
2490
2491 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2492   VisitOMPLoopDirective(D);
2493 }
2494
2495 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2496   VisitOMPLoopDirective(D);
2497 }
2498
2499 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2500   VisitOMPExecutableDirective(D);
2501 }
2502
2503 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2504   VisitOMPExecutableDirective(D);
2505 }
2506
2507 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2508   VisitOMPExecutableDirective(D);
2509 }
2510
2511 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2512   VisitOMPExecutableDirective(D);
2513 }
2514
2515 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2516   VisitOMPExecutableDirective(D);
2517   AddDeclarationNameInfo(D);
2518 }
2519
2520 void
2521 EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
2522   VisitOMPLoopDirective(D);
2523 }
2524
2525 void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2526     const OMPParallelForSimdDirective *D) {
2527   VisitOMPLoopDirective(D);
2528 }
2529
2530 void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2531     const OMPParallelSectionsDirective *D) {
2532   VisitOMPExecutableDirective(D);
2533 }
2534
2535 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2536   VisitOMPExecutableDirective(D);
2537 }
2538
2539 void
2540 EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2541   VisitOMPExecutableDirective(D);
2542 }
2543
2544 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2545   VisitOMPExecutableDirective(D);
2546 }
2547
2548 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2549   VisitOMPExecutableDirective(D);
2550 }
2551
2552 void EnqueueVisitor::VisitOMPTaskgroupDirective(
2553     const OMPTaskgroupDirective *D) {
2554   VisitOMPExecutableDirective(D);
2555 }
2556
2557 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2558   VisitOMPExecutableDirective(D);
2559 }
2560
2561 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2562   VisitOMPExecutableDirective(D);
2563 }
2564
2565 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2566   VisitOMPExecutableDirective(D);
2567 }
2568
2569 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2570   VisitOMPExecutableDirective(D);
2571 }
2572
2573 void EnqueueVisitor::VisitOMPTargetDataDirective(const 
2574                                                  OMPTargetDataDirective *D) {
2575   VisitOMPExecutableDirective(D);
2576 }
2577
2578 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2579   VisitOMPExecutableDirective(D);
2580 }
2581
2582 void EnqueueVisitor::VisitOMPCancellationPointDirective(
2583     const OMPCancellationPointDirective *D) {
2584   VisitOMPExecutableDirective(D);
2585 }
2586
2587 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2588   VisitOMPExecutableDirective(D);
2589 }
2590
2591 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
2592   EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2593 }
2594
2595 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2596   if (RegionOfInterest.isValid()) {
2597     SourceRange Range = getRawCursorExtent(C);
2598     if (Range.isInvalid() || CompareRegionOfInterest(Range))
2599       return false;
2600   }
2601   return true;
2602 }
2603
2604 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2605   while (!WL.empty()) {
2606     // Dequeue the worklist item.
2607     VisitorJob LI = WL.pop_back_val();
2608
2609     // Set the Parent field, then back to its old value once we're done.
2610     SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2611   
2612     switch (LI.getKind()) {
2613       case VisitorJob::DeclVisitKind: {
2614         const Decl *D = cast<DeclVisit>(&LI)->get();
2615         if (!D)
2616           continue;
2617
2618         // For now, perform default visitation for Decls.
2619         if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2620                                cast<DeclVisit>(&LI)->isFirst())))
2621             return true;
2622
2623         continue;
2624       }
2625       case VisitorJob::ExplicitTemplateArgsVisitKind: {
2626         const ASTTemplateArgumentListInfo *ArgList =
2627           cast<ExplicitTemplateArgsVisit>(&LI)->get();
2628         for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2629                *ArgEnd = Arg + ArgList->NumTemplateArgs;
2630                Arg != ArgEnd; ++Arg) {
2631           if (VisitTemplateArgumentLoc(*Arg))
2632             return true;
2633         }
2634         continue;
2635       }
2636       case VisitorJob::TypeLocVisitKind: {
2637         // Perform default visitation for TypeLocs.
2638         if (Visit(cast<TypeLocVisit>(&LI)->get()))
2639           return true;
2640         continue;
2641       }
2642       case VisitorJob::LabelRefVisitKind: {
2643         const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2644         if (LabelStmt *stmt = LS->getStmt()) {
2645           if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2646                                        TU))) {
2647             return true;
2648           }
2649         }
2650         continue;
2651       }
2652
2653       case VisitorJob::NestedNameSpecifierLocVisitKind: {
2654         NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2655         if (VisitNestedNameSpecifierLoc(V->get()))
2656           return true;
2657         continue;
2658       }
2659         
2660       case VisitorJob::DeclarationNameInfoVisitKind: {
2661         if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2662                                      ->get()))
2663           return true;
2664         continue;
2665       }
2666       case VisitorJob::MemberRefVisitKind: {
2667         MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2668         if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2669           return true;
2670         continue;
2671       }
2672       case VisitorJob::StmtVisitKind: {
2673         const Stmt *S = cast<StmtVisit>(&LI)->get();
2674         if (!S)
2675           continue;
2676
2677         // Update the current cursor.
2678         CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2679         if (!IsInRegionOfInterest(Cursor))
2680           continue;
2681         switch (Visitor(Cursor, Parent, ClientData)) {
2682           case CXChildVisit_Break: return true;
2683           case CXChildVisit_Continue: break;
2684           case CXChildVisit_Recurse:
2685             if (PostChildrenVisitor)
2686               WL.push_back(PostChildrenVisit(nullptr, Cursor));
2687             EnqueueWorkList(WL, S);
2688             break;
2689         }
2690         continue;
2691       }
2692       case VisitorJob::MemberExprPartsKind: {
2693         // Handle the other pieces in the MemberExpr besides the base.
2694         const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2695         
2696         // Visit the nested-name-specifier
2697         if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2698           if (VisitNestedNameSpecifierLoc(QualifierLoc))
2699             return true;
2700         
2701         // Visit the declaration name.
2702         if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2703           return true;
2704         
2705         // Visit the explicitly-specified template arguments, if any.
2706         if (M->hasExplicitTemplateArgs()) {
2707           for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2708                *ArgEnd = Arg + M->getNumTemplateArgs();
2709                Arg != ArgEnd; ++Arg) {
2710             if (VisitTemplateArgumentLoc(*Arg))
2711               return true;
2712           }
2713         }
2714         continue;
2715       }
2716       case VisitorJob::DeclRefExprPartsKind: {
2717         const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2718         // Visit nested-name-specifier, if present.
2719         if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2720           if (VisitNestedNameSpecifierLoc(QualifierLoc))
2721             return true;
2722         // Visit declaration name.
2723         if (VisitDeclarationNameInfo(DR->getNameInfo()))
2724           return true;
2725         continue;
2726       }
2727       case VisitorJob::OverloadExprPartsKind: {
2728         const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2729         // Visit the nested-name-specifier.
2730         if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2731           if (VisitNestedNameSpecifierLoc(QualifierLoc))
2732             return true;
2733         // Visit the declaration name.
2734         if (VisitDeclarationNameInfo(O->getNameInfo()))
2735           return true;
2736         // Visit the overloaded declaration reference.
2737         if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2738           return true;
2739         continue;
2740       }
2741       case VisitorJob::SizeOfPackExprPartsKind: {
2742         const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2743         NamedDecl *Pack = E->getPack();
2744         if (isa<TemplateTypeParmDecl>(Pack)) {
2745           if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2746                                       E->getPackLoc(), TU)))
2747             return true;
2748           
2749           continue;
2750         }
2751           
2752         if (isa<TemplateTemplateParmDecl>(Pack)) {
2753           if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2754                                           E->getPackLoc(), TU)))
2755             return true;
2756           
2757           continue;
2758         }
2759         
2760         // Non-type template parameter packs and function parameter packs are
2761         // treated like DeclRefExpr cursors.
2762         continue;
2763       }
2764         
2765       case VisitorJob::LambdaExprPartsKind: {
2766         // Visit captures.
2767         const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2768         for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2769                                        CEnd = E->explicit_capture_end();
2770              C != CEnd; ++C) {
2771           // FIXME: Lambda init-captures.
2772           if (!C->capturesVariable())
2773             continue;
2774
2775           if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2776                                           C->getLocation(),
2777                                           TU)))
2778             return true;
2779         }
2780         
2781         // Visit parameters and return type, if present.
2782         if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2783           TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2784           if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2785             // Visit the whole type.
2786             if (Visit(TL))
2787               return true;
2788           } else if (FunctionProtoTypeLoc Proto =
2789                          TL.getAs<FunctionProtoTypeLoc>()) {
2790             if (E->hasExplicitParameters()) {
2791               // Visit parameters.
2792               for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
2793                 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
2794                   return true;
2795             } else {
2796               // Visit result type.
2797               if (Visit(Proto.getReturnLoc()))
2798                 return true;
2799             }
2800           }
2801         }
2802         break;
2803       }
2804
2805       case VisitorJob::PostChildrenVisitKind:
2806         if (PostChildrenVisitor(Parent, ClientData))
2807           return true;
2808         break;
2809     }
2810   }
2811   return false;
2812 }
2813
2814 bool CursorVisitor::Visit(const Stmt *S) {
2815   VisitorWorkList *WL = nullptr;
2816   if (!WorkListFreeList.empty()) {
2817     WL = WorkListFreeList.back();
2818     WL->clear();
2819     WorkListFreeList.pop_back();
2820   }
2821   else {
2822     WL = new VisitorWorkList();
2823     WorkListCache.push_back(WL);
2824   }
2825   EnqueueWorkList(*WL, S);
2826   bool result = RunVisitorWorkList(*WL);
2827   WorkListFreeList.push_back(WL);
2828   return result;
2829 }
2830
2831 namespace {
2832 typedef SmallVector<SourceRange, 4> RefNamePieces;
2833 RefNamePieces
2834 buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2835             const DeclarationNameInfo &NI, const SourceRange &QLoc,
2836             const ASTTemplateArgumentListInfo *TemplateArgs = nullptr) {
2837   const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2838   const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2839   const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2840   
2841   const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2842   
2843   RefNamePieces Pieces;
2844
2845   if (WantQualifier && QLoc.isValid())
2846     Pieces.push_back(QLoc);
2847   
2848   if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2849     Pieces.push_back(NI.getLoc());
2850   
2851   if (WantTemplateArgs && TemplateArgs)
2852     Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2853                                  TemplateArgs->RAngleLoc));
2854   
2855   if (Kind == DeclarationName::CXXOperatorName) {
2856     Pieces.push_back(SourceLocation::getFromRawEncoding(
2857                        NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2858     Pieces.push_back(SourceLocation::getFromRawEncoding(
2859                        NI.getInfo().CXXOperatorName.EndOpNameLoc));
2860   }
2861   
2862   if (WantSinglePiece) {
2863     SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2864     Pieces.clear();
2865     Pieces.push_back(R);
2866   }  
2867
2868   return Pieces;  
2869 }
2870 }
2871
2872 //===----------------------------------------------------------------------===//
2873 // Misc. API hooks.
2874 //===----------------------------------------------------------------------===//               
2875
2876 static void fatal_error_handler(void *user_data, const std::string& reason,
2877                                 bool gen_crash_diag) {
2878   // Write the result out to stderr avoiding errs() because raw_ostreams can
2879   // call report_fatal_error.
2880   fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2881   ::abort();
2882 }
2883
2884 namespace {
2885 struct RegisterFatalErrorHandler {
2886   RegisterFatalErrorHandler() {
2887     llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
2888   }
2889 };
2890 }
2891
2892 static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
2893
2894 extern "C" {
2895 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2896                           int displayDiagnostics) {
2897   // We use crash recovery to make some of our APIs more reliable, implicitly
2898   // enable it.
2899   if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
2900     llvm::CrashRecoveryContext::Enable();
2901
2902   // Look through the managed static to trigger construction of the managed
2903   // static which registers our fatal error handler. This ensures it is only
2904   // registered once.
2905   (void)*RegisterFatalErrorHandlerOnce;
2906
2907   // Initialize targets for clang module support.
2908   llvm::InitializeAllTargets();
2909   llvm::InitializeAllTargetMCs();
2910   llvm::InitializeAllAsmPrinters();
2911   llvm::InitializeAllAsmParsers();
2912
2913   CIndexer *CIdxr = new CIndexer();
2914
2915   if (excludeDeclarationsFromPCH)
2916     CIdxr->setOnlyLocalDecls();
2917   if (displayDiagnostics)
2918     CIdxr->setDisplayDiagnostics();
2919
2920   if (getenv("LIBCLANG_BGPRIO_INDEX"))
2921     CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2922                                CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2923   if (getenv("LIBCLANG_BGPRIO_EDIT"))
2924     CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2925                                CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2926
2927   return CIdxr;
2928 }
2929
2930 void clang_disposeIndex(CXIndex CIdx) {
2931   if (CIdx)
2932     delete static_cast<CIndexer *>(CIdx);
2933 }
2934
2935 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2936   if (CIdx)
2937     static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2938 }
2939
2940 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2941   if (CIdx)
2942     return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2943   return 0;
2944 }
2945
2946 void clang_toggleCrashRecovery(unsigned isEnabled) {
2947   if (isEnabled)
2948     llvm::CrashRecoveryContext::Enable();
2949   else
2950     llvm::CrashRecoveryContext::Disable();
2951 }
2952
2953 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2954                                               const char *ast_filename) {
2955   CXTranslationUnit TU;
2956   enum CXErrorCode Result =
2957       clang_createTranslationUnit2(CIdx, ast_filename, &TU);
2958   (void)Result;
2959   assert((TU && Result == CXError_Success) ||
2960          (!TU && Result != CXError_Success));
2961   return TU;
2962 }
2963
2964 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
2965                                               const char *ast_filename,
2966                                               CXTranslationUnit *out_TU) {
2967   if (out_TU)
2968     *out_TU = nullptr;
2969
2970   if (!CIdx || !ast_filename || !out_TU)
2971     return CXError_InvalidArguments;
2972
2973   LOG_FUNC_SECTION {
2974     *Log << ast_filename;
2975   }
2976
2977   CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2978   FileSystemOptions FileSystemOpts;
2979
2980   IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
2981       CompilerInstance::createDiagnostics(new DiagnosticOptions());
2982   std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
2983       ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), Diags,
2984       FileSystemOpts, /*UseDebugInfo=*/false,
2985       CXXIdx->getOnlyLocalDecls(), None,
2986       /*CaptureDiagnostics=*/true,
2987       /*AllowPCHWithCompilerErrors=*/true,
2988       /*UserFilesAreVolatile=*/true);
2989   *out_TU = MakeCXTranslationUnit(CXXIdx, AU.release());
2990   return *out_TU ? CXError_Success : CXError_Failure;
2991 }
2992
2993 unsigned clang_defaultEditingTranslationUnitOptions() {
2994   return CXTranslationUnit_PrecompiledPreamble | 
2995          CXTranslationUnit_CacheCompletionResults;
2996 }
2997
2998 CXTranslationUnit
2999 clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3000                                           const char *source_filename,
3001                                           int num_command_line_args,
3002                                           const char * const *command_line_args,
3003                                           unsigned num_unsaved_files,
3004                                           struct CXUnsavedFile *unsaved_files) {
3005   unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3006   return clang_parseTranslationUnit(CIdx, source_filename,
3007                                     command_line_args, num_command_line_args,
3008                                     unsaved_files, num_unsaved_files,
3009                                     Options);
3010 }
3011
3012 static CXErrorCode
3013 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3014                                 const char *const *command_line_args,
3015                                 int num_command_line_args,
3016                                 ArrayRef<CXUnsavedFile> unsaved_files,
3017                                 unsigned options, CXTranslationUnit *out_TU) {
3018   // Set up the initial return values.
3019   if (out_TU)
3020     *out_TU = nullptr;
3021
3022   // Check arguments.
3023   if (!CIdx || !out_TU)
3024     return CXError_InvalidArguments;
3025
3026   CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3027
3028   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3029     setThreadBackgroundPriority();
3030
3031   bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3032   // FIXME: Add a flag for modules.
3033   TranslationUnitKind TUKind
3034     = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
3035   bool CacheCodeCompletionResults
3036     = options & CXTranslationUnit_CacheCompletionResults;
3037   bool IncludeBriefCommentsInCodeCompletion
3038     = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3039   bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
3040   bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3041
3042   // Configure the diagnostics.
3043   IntrusiveRefCntPtr<DiagnosticsEngine>
3044     Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
3045
3046   // Recover resources if we crash before exiting this function.
3047   llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3048     llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
3049     DiagCleanup(Diags.get());
3050
3051   std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3052       new std::vector<ASTUnit::RemappedFile>());
3053
3054   // Recover resources if we crash before exiting this function.
3055   llvm::CrashRecoveryContextCleanupRegistrar<
3056     std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3057
3058   for (auto &UF : unsaved_files) {
3059     std::unique_ptr<llvm::MemoryBuffer> MB =
3060         llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3061     RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3062   }
3063
3064   std::unique_ptr<std::vector<const char *>> Args(
3065       new std::vector<const char *>());
3066
3067   // Recover resources if we crash before exiting this method.
3068   llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3069     ArgsCleanup(Args.get());
3070
3071   // Since the Clang C library is primarily used by batch tools dealing with
3072   // (often very broken) source code, where spell-checking can have a
3073   // significant negative impact on performance (particularly when 
3074   // precompiled headers are involved), we disable it by default.
3075   // Only do this if we haven't found a spell-checking-related argument.
3076   bool FoundSpellCheckingArgument = false;
3077   for (int I = 0; I != num_command_line_args; ++I) {
3078     if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3079         strcmp(command_line_args[I], "-fspell-checking") == 0) {
3080       FoundSpellCheckingArgument = true;
3081       break;
3082     }
3083   }
3084   if (!FoundSpellCheckingArgument)
3085     Args->push_back("-fno-spell-checking");
3086   
3087   Args->insert(Args->end(), command_line_args,
3088                command_line_args + num_command_line_args);
3089
3090   // The 'source_filename' argument is optional.  If the caller does not
3091   // specify it then it is assumed that the source file is specified
3092   // in the actual argument list.
3093   // Put the source file after command_line_args otherwise if '-x' flag is
3094   // present it will be unused.
3095   if (source_filename)
3096     Args->push_back(source_filename);
3097
3098   // Do we need the detailed preprocessing record?
3099   if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3100     Args->push_back("-Xclang");
3101     Args->push_back("-detailed-preprocessing-record");
3102   }
3103   
3104   unsigned NumErrors = Diags->getClient()->getNumErrors();
3105   std::unique_ptr<ASTUnit> ErrUnit;
3106   std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3107       Args->data(), Args->data() + Args->size(),
3108       CXXIdx->getPCHContainerOperations(), Diags,
3109       CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3110       /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
3111       /*RemappedFilesKeepOriginalName=*/true, PrecompilePreamble, TUKind,
3112       CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3113       /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies,
3114       /*UserFilesAreVolatile=*/true, ForSerialization, &ErrUnit));
3115
3116   // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3117   if (!Unit && !ErrUnit)
3118     return CXError_ASTReadError;
3119
3120   if (NumErrors != Diags->getClient()->getNumErrors()) {
3121     // Make sure to check that 'Unit' is non-NULL.
3122     if (CXXIdx->getDisplayDiagnostics())
3123       printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3124   }
3125
3126   if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3127     return CXError_ASTReadError;
3128
3129   *out_TU = MakeCXTranslationUnit(CXXIdx, Unit.release());
3130   return *out_TU ? CXError_Success : CXError_Failure;
3131 }
3132
3133 CXTranslationUnit
3134 clang_parseTranslationUnit(CXIndex CIdx,
3135                            const char *source_filename,
3136                            const char *const *command_line_args,
3137                            int num_command_line_args,
3138                            struct CXUnsavedFile *unsaved_files,
3139                            unsigned num_unsaved_files,
3140                            unsigned options) {
3141   CXTranslationUnit TU;
3142   enum CXErrorCode Result = clang_parseTranslationUnit2(
3143       CIdx, source_filename, command_line_args, num_command_line_args,
3144       unsaved_files, num_unsaved_files, options, &TU);
3145   (void)Result;
3146   assert((TU && Result == CXError_Success) ||
3147          (!TU && Result != CXError_Success));
3148   return TU;
3149 }
3150
3151 enum CXErrorCode clang_parseTranslationUnit2(
3152     CXIndex CIdx,
3153     const char *source_filename,
3154     const char *const *command_line_args,
3155     int num_command_line_args,
3156     struct CXUnsavedFile *unsaved_files,
3157     unsigned num_unsaved_files,
3158     unsigned options,
3159     CXTranslationUnit *out_TU) {
3160   LOG_FUNC_SECTION {
3161     *Log << source_filename << ": ";
3162     for (int i = 0; i != num_command_line_args; ++i)
3163       *Log << command_line_args[i] << " ";
3164   }
3165
3166   if (num_unsaved_files && !unsaved_files)
3167     return CXError_InvalidArguments;
3168
3169   CXErrorCode result = CXError_Failure;
3170   auto ParseTranslationUnitImpl = [=, &result] {
3171     result = clang_parseTranslationUnit_Impl(
3172         CIdx, source_filename, command_line_args, num_command_line_args,
3173         llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3174   };
3175   llvm::CrashRecoveryContext CRC;
3176
3177   if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3178     fprintf(stderr, "libclang: crash detected during parsing: {\n");
3179     fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
3180     fprintf(stderr, "  'command_line_args' : [");
3181     for (int i = 0; i != num_command_line_args; ++i) {
3182       if (i)
3183         fprintf(stderr, ", ");
3184       fprintf(stderr, "'%s'", command_line_args[i]);
3185     }
3186     fprintf(stderr, "],\n");
3187     fprintf(stderr, "  'unsaved_files' : [");
3188     for (unsigned i = 0; i != num_unsaved_files; ++i) {
3189       if (i)
3190         fprintf(stderr, ", ");
3191       fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3192               unsaved_files[i].Length);
3193     }
3194     fprintf(stderr, "],\n");
3195     fprintf(stderr, "  'options' : %d,\n", options);
3196     fprintf(stderr, "}\n");
3197
3198     return CXError_Crashed;
3199   } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3200     if (CXTranslationUnit *TU = out_TU)
3201       PrintLibclangResourceUsage(*TU);
3202   }
3203
3204   return result;
3205 }
3206
3207 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3208   return CXSaveTranslationUnit_None;
3209 }  
3210
3211 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3212                                                   const char *FileName,
3213                                                   unsigned options) {
3214   CIndexer *CXXIdx = TU->CIdx;
3215   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3216     setThreadBackgroundPriority();
3217
3218   bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3219   return hadError ? CXSaveError_Unknown : CXSaveError_None;
3220 }
3221
3222 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3223                               unsigned options) {
3224   LOG_FUNC_SECTION {
3225     *Log << TU << ' ' << FileName;
3226   }
3227
3228   if (isNotUsableTU(TU)) {
3229     LOG_BAD_TU(TU);
3230     return CXSaveError_InvalidTU;
3231   }
3232
3233   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3234   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3235   if (!CXXUnit->hasSema())
3236     return CXSaveError_InvalidTU;
3237
3238   CXSaveError result;
3239   auto SaveTranslationUnitImpl = [=, &result]() {
3240     result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3241   };
3242
3243   if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
3244       getenv("LIBCLANG_NOTHREADS")) {
3245     SaveTranslationUnitImpl();
3246
3247     if (getenv("LIBCLANG_RESOURCE_USAGE"))
3248       PrintLibclangResourceUsage(TU);
3249
3250     return result;
3251   }
3252
3253   // We have an AST that has invalid nodes due to compiler errors.
3254   // Use a crash recovery thread for protection.
3255
3256   llvm::CrashRecoveryContext CRC;
3257
3258   if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
3259     fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3260     fprintf(stderr, "  'filename' : '%s'\n", FileName);
3261     fprintf(stderr, "  'options' : %d,\n", options);
3262     fprintf(stderr, "}\n");
3263
3264     return CXSaveError_Unknown;
3265
3266   } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3267     PrintLibclangResourceUsage(TU);
3268   }
3269
3270   return result;
3271 }
3272
3273 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
3274   if (CTUnit) {
3275     // If the translation unit has been marked as unsafe to free, just discard
3276     // it.
3277     ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3278     if (Unit && Unit->isUnsafeToFree())
3279       return;
3280
3281     delete cxtu::getASTUnit(CTUnit);
3282     delete CTUnit->StringPool;
3283     delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
3284     disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
3285     delete CTUnit->CommentToXML;
3286     delete CTUnit;
3287   }
3288 }
3289
3290 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
3291   return CXReparse_None;
3292 }
3293
3294 static CXErrorCode
3295 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
3296                                   ArrayRef<CXUnsavedFile> unsaved_files,
3297                                   unsigned options) {
3298   // Check arguments.
3299   if (isNotUsableTU(TU)) {
3300     LOG_BAD_TU(TU);
3301     return CXError_InvalidArguments;
3302   }
3303
3304   // Reset the associated diagnostics.
3305   delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
3306   TU->Diagnostics = nullptr;
3307
3308   CIndexer *CXXIdx = TU->CIdx;
3309   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
3310     setThreadBackgroundPriority();
3311
3312   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3313   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3314
3315   std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3316       new std::vector<ASTUnit::RemappedFile>());
3317
3318   // Recover resources if we crash before exiting this function.
3319   llvm::CrashRecoveryContextCleanupRegistrar<
3320     std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3321
3322   for (auto &UF : unsaved_files) {
3323     std::unique_ptr<llvm::MemoryBuffer> MB =
3324         llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3325     RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3326   }
3327
3328   if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
3329                         *RemappedFiles.get()))
3330     return CXError_Success;
3331   if (isASTReadError(CXXUnit))
3332     return CXError_ASTReadError;
3333   return CXError_Failure;
3334 }
3335
3336 int clang_reparseTranslationUnit(CXTranslationUnit TU,
3337                                  unsigned num_unsaved_files,
3338                                  struct CXUnsavedFile *unsaved_files,
3339                                  unsigned options) {
3340   LOG_FUNC_SECTION {
3341     *Log << TU;
3342   }
3343
3344   if (num_unsaved_files && !unsaved_files)
3345     return CXError_InvalidArguments;
3346
3347   CXErrorCode result;
3348   auto ReparseTranslationUnitImpl = [=, &result]() {
3349     result = clang_reparseTranslationUnit_Impl(
3350         TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
3351   };
3352
3353   if (getenv("LIBCLANG_NOTHREADS")) {
3354     ReparseTranslationUnitImpl();
3355     return result;
3356   }
3357
3358   llvm::CrashRecoveryContext CRC;
3359
3360   if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
3361     fprintf(stderr, "libclang: crash detected during reparsing\n");
3362     cxtu::getASTUnit(TU)->setUnsafeToFree(true);
3363     return CXError_Crashed;
3364   } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
3365     PrintLibclangResourceUsage(TU);
3366
3367   return result;
3368 }
3369
3370
3371 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
3372   if (isNotUsableTU(CTUnit)) {
3373     LOG_BAD_TU(CTUnit);
3374     return cxstring::createEmpty();
3375   }
3376
3377   ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
3378   return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
3379 }
3380
3381 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
3382   if (isNotUsableTU(TU)) {
3383     LOG_BAD_TU(TU);
3384     return clang_getNullCursor();
3385   }
3386
3387   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3388   return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
3389 }
3390
3391 } // end: extern "C"
3392
3393 //===----------------------------------------------------------------------===//
3394 // CXFile Operations.
3395 //===----------------------------------------------------------------------===//
3396
3397 extern "C" {
3398 CXString clang_getFileName(CXFile SFile) {
3399   if (!SFile)
3400     return cxstring::createNull();
3401
3402   FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3403   return cxstring::createRef(FEnt->getName());
3404 }
3405
3406 time_t clang_getFileTime(CXFile SFile) {
3407   if (!SFile)
3408     return 0;
3409
3410   FileEntry *FEnt = static_cast<FileEntry *>(SFile);
3411   return FEnt->getModificationTime();
3412 }
3413
3414 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
3415   if (isNotUsableTU(TU)) {
3416     LOG_BAD_TU(TU);
3417     return nullptr;
3418   }
3419
3420   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3421
3422   FileManager &FMgr = CXXUnit->getFileManager();
3423   return const_cast<FileEntry *>(FMgr.getFile(file_name));
3424 }
3425
3426 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
3427                                             CXFile file) {
3428   if (isNotUsableTU(TU)) {
3429     LOG_BAD_TU(TU);
3430     return 0;
3431   }
3432
3433   if (!file)
3434     return 0;
3435
3436   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3437   FileEntry *FEnt = static_cast<FileEntry *>(file);
3438   return CXXUnit->getPreprocessor().getHeaderSearchInfo()
3439                                           .isFileMultipleIncludeGuarded(FEnt);
3440 }
3441
3442 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
3443   if (!file || !outID)
3444     return 1;
3445
3446   FileEntry *FEnt = static_cast<FileEntry *>(file);
3447   const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
3448   outID->data[0] = ID.getDevice();
3449   outID->data[1] = ID.getFile();
3450   outID->data[2] = FEnt->getModificationTime();
3451   return 0;
3452 }
3453
3454 int clang_File_isEqual(CXFile file1, CXFile file2) {
3455   if (file1 == file2)
3456     return true;
3457
3458   if (!file1 || !file2)
3459     return false;
3460
3461   FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
3462   FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
3463   return FEnt1->getUniqueID() == FEnt2->getUniqueID();
3464 }
3465
3466 } // end: extern "C"
3467
3468 //===----------------------------------------------------------------------===//
3469 // CXCursor Operations.
3470 //===----------------------------------------------------------------------===//
3471
3472 static const Decl *getDeclFromExpr(const Stmt *E) {
3473   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3474     return getDeclFromExpr(CE->getSubExpr());
3475
3476   if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
3477     return RefExpr->getDecl();
3478   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
3479     return ME->getMemberDecl();
3480   if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
3481     return RE->getDecl();
3482   if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
3483     if (PRE->isExplicitProperty())
3484       return PRE->getExplicitProperty();
3485     // It could be messaging both getter and setter as in:
3486     // ++myobj.myprop;
3487     // in which case prefer to associate the setter since it is less obvious
3488     // from inspecting the source that the setter is going to get called.
3489     if (PRE->isMessagingSetter())
3490       return PRE->getImplicitPropertySetter();
3491     return PRE->getImplicitPropertyGetter();
3492   }
3493   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
3494     return getDeclFromExpr(POE->getSyntacticForm());
3495   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
3496     if (Expr *Src = OVE->getSourceExpr())
3497       return getDeclFromExpr(Src);
3498       
3499   if (const CallExpr *CE = dyn_cast<CallExpr>(E))
3500     return getDeclFromExpr(CE->getCallee());
3501   if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
3502     if (!CE->isElidable())
3503     return CE->getConstructor();
3504   if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
3505     return OME->getMethodDecl();
3506
3507   if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
3508     return PE->getProtocol();
3509   if (const SubstNonTypeTemplateParmPackExpr *NTTP
3510                               = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
3511     return NTTP->getParameterPack();
3512   if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3513     if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) || 
3514         isa<ParmVarDecl>(SizeOfPack->getPack()))
3515       return SizeOfPack->getPack();
3516
3517   return nullptr;
3518 }
3519
3520 static SourceLocation getLocationFromExpr(const Expr *E) {
3521   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
3522     return getLocationFromExpr(CE->getSubExpr());
3523
3524   if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3525     return /*FIXME:*/Msg->getLeftLoc();
3526   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3527     return DRE->getLocation();
3528   if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
3529     return Member->getMemberLoc();
3530   if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3531     return Ivar->getLocation();
3532   if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3533     return SizeOfPack->getPackLoc();
3534   if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
3535     return PropRef->getLocation();
3536   
3537   return E->getLocStart();
3538 }
3539
3540 extern "C" {
3541
3542 unsigned clang_visitChildren(CXCursor parent,
3543                              CXCursorVisitor visitor,
3544                              CXClientData client_data) {
3545   CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3546                           /*VisitPreprocessorLast=*/false);
3547   return CursorVis.VisitChildren(parent);
3548 }
3549
3550 #ifndef __has_feature
3551 #define __has_feature(x) 0
3552 #endif
3553 #if __has_feature(blocks)
3554 typedef enum CXChildVisitResult 
3555      (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3556
3557 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3558     CXClientData client_data) {
3559   CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3560   return block(cursor, parent);
3561 }
3562 #else
3563 // If we are compiled with a compiler that doesn't have native blocks support,
3564 // define and call the block manually, so the 
3565 typedef struct _CXChildVisitResult
3566 {
3567         void *isa;
3568         int flags;
3569         int reserved;
3570         enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3571                                          CXCursor);
3572 } *CXCursorVisitorBlock;
3573
3574 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3575     CXClientData client_data) {
3576   CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3577   return block->invoke(block, cursor, parent);
3578 }
3579 #endif
3580
3581
3582 unsigned clang_visitChildrenWithBlock(CXCursor parent,
3583                                       CXCursorVisitorBlock block) {
3584   return clang_visitChildren(parent, visitWithBlock, block);
3585 }
3586
3587 static CXString getDeclSpelling(const Decl *D) {
3588   if (!D)
3589     return cxstring::createEmpty();
3590
3591   const NamedDecl *ND = dyn_cast<NamedDecl>(D);
3592   if (!ND) {
3593     if (const ObjCPropertyImplDecl *PropImpl =
3594             dyn_cast<ObjCPropertyImplDecl>(D))
3595       if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3596         return cxstring::createDup(Property->getIdentifier()->getName());
3597     
3598     if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
3599       if (Module *Mod = ImportD->getImportedModule())
3600         return cxstring::createDup(Mod->getFullModuleName());
3601
3602     return cxstring::createEmpty();
3603   }
3604   
3605   if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3606     return cxstring::createDup(OMD->getSelector().getAsString());
3607
3608   if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3609     // No, this isn't the same as the code below. getIdentifier() is non-virtual
3610     // and returns different names. NamedDecl returns the class name and
3611     // ObjCCategoryImplDecl returns the category name.
3612     return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
3613
3614   if (isa<UsingDirectiveDecl>(D))
3615     return cxstring::createEmpty();
3616   
3617   SmallString<1024> S;
3618   llvm::raw_svector_ostream os(S);
3619   ND->printName(os);
3620   
3621   return cxstring::createDup(os.str());
3622 }
3623
3624 CXString clang_getCursorSpelling(CXCursor C) {
3625   if (clang_isTranslationUnit(C.kind))
3626     return clang_getTranslationUnitSpelling(getCursorTU(C));
3627
3628   if (clang_isReference(C.kind)) {
3629     switch (C.kind) {
3630     case CXCursor_ObjCSuperClassRef: {
3631       const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3632       return cxstring::createRef(Super->getIdentifier()->getNameStart());
3633     }
3634     case CXCursor_ObjCClassRef: {
3635       const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3636       return cxstring::createRef(Class->getIdentifier()->getNameStart());
3637     }
3638     case CXCursor_ObjCProtocolRef: {
3639       const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3640       assert(OID && "getCursorSpelling(): Missing protocol decl");
3641       return cxstring::createRef(OID->getIdentifier()->getNameStart());
3642     }
3643     case CXCursor_CXXBaseSpecifier: {
3644       const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3645       return cxstring::createDup(B->getType().getAsString());
3646     }
3647     case CXCursor_TypeRef: {
3648       const TypeDecl *Type = getCursorTypeRef(C).first;
3649       assert(Type && "Missing type decl");
3650
3651       return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
3652                               getAsString());
3653     }
3654     case CXCursor_TemplateRef: {
3655       const TemplateDecl *Template = getCursorTemplateRef(C).first;
3656       assert(Template && "Missing template decl");
3657       
3658       return cxstring::createDup(Template->getNameAsString());
3659     }
3660         
3661     case CXCursor_NamespaceRef: {
3662       const NamedDecl *NS = getCursorNamespaceRef(C).first;
3663       assert(NS && "Missing namespace decl");
3664       
3665       return cxstring::createDup(NS->getNameAsString());
3666     }
3667
3668     case CXCursor_MemberRef: {
3669       const FieldDecl *Field = getCursorMemberRef(C).first;
3670       assert(Field && "Missing member decl");
3671       
3672       return cxstring::createDup(Field->getNameAsString());
3673     }
3674
3675     case CXCursor_LabelRef: {
3676       const LabelStmt *Label = getCursorLabelRef(C).first;
3677       assert(Label && "Missing label");
3678       
3679       return cxstring::createRef(Label->getName());
3680     }
3681
3682     case CXCursor_OverloadedDeclRef: {
3683       OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3684       if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
3685         if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3686           return cxstring::createDup(ND->getNameAsString());
3687         return cxstring::createEmpty();
3688       }
3689       if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
3690         return cxstring::createDup(E->getName().getAsString());
3691       OverloadedTemplateStorage *Ovl
3692         = Storage.get<OverloadedTemplateStorage*>();
3693       if (Ovl->size() == 0)
3694         return cxstring::createEmpty();
3695       return cxstring::createDup((*Ovl->begin())->getNameAsString());
3696     }
3697         
3698     case CXCursor_VariableRef: {
3699       const VarDecl *Var = getCursorVariableRef(C).first;
3700       assert(Var && "Missing variable decl");
3701       
3702       return cxstring::createDup(Var->getNameAsString());
3703     }
3704         
3705     default:
3706       return cxstring::createRef("<not implemented>");
3707     }
3708   }
3709
3710   if (clang_isExpression(C.kind)) {
3711     const Expr *E = getCursorExpr(C);
3712
3713     if (C.kind == CXCursor_ObjCStringLiteral ||
3714         C.kind == CXCursor_StringLiteral) {
3715       const StringLiteral *SLit;
3716       if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
3717         SLit = OSL->getString();
3718       } else {
3719         SLit = cast<StringLiteral>(E);
3720       }
3721       SmallString<256> Buf;
3722       llvm::raw_svector_ostream OS(Buf);
3723       SLit->outputString(OS);
3724       return cxstring::createDup(OS.str());
3725     }
3726
3727     const Decl *D = getDeclFromExpr(getCursorExpr(C));
3728     if (D)
3729       return getDeclSpelling(D);
3730     return cxstring::createEmpty();
3731   }
3732
3733   if (clang_isStatement(C.kind)) {
3734     const Stmt *S = getCursorStmt(C);
3735     if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3736       return cxstring::createRef(Label->getName());
3737
3738     return cxstring::createEmpty();
3739   }
3740   
3741   if (C.kind == CXCursor_MacroExpansion)
3742     return cxstring::createRef(getCursorMacroExpansion(C).getName()
3743                                                            ->getNameStart());
3744
3745   if (C.kind == CXCursor_MacroDefinition)
3746     return cxstring::createRef(getCursorMacroDefinition(C)->getName()
3747                                                            ->getNameStart());
3748
3749   if (C.kind == CXCursor_InclusionDirective)
3750     return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
3751       
3752   if (clang_isDeclaration(C.kind))
3753     return getDeclSpelling(getCursorDecl(C));
3754
3755   if (C.kind == CXCursor_AnnotateAttr) {
3756     const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3757     return cxstring::createDup(AA->getAnnotation());
3758   }
3759
3760   if (C.kind == CXCursor_AsmLabelAttr) {
3761     const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3762     return cxstring::createDup(AA->getLabel());
3763   }
3764
3765   if (C.kind == CXCursor_PackedAttr) {
3766     return cxstring::createRef("packed");
3767   }
3768
3769   if (C.kind == CXCursor_VisibilityAttr) {
3770     const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
3771     switch (AA->getVisibility()) {
3772     case VisibilityAttr::VisibilityType::Default:
3773       return cxstring::createRef("default");
3774     case VisibilityAttr::VisibilityType::Hidden:
3775       return cxstring::createRef("hidden");
3776     case VisibilityAttr::VisibilityType::Protected:
3777       return cxstring::createRef("protected");
3778     }
3779     llvm_unreachable("unknown visibility type");
3780   }
3781
3782   return cxstring::createEmpty();
3783 }
3784
3785 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3786                                                 unsigned pieceIndex,
3787                                                 unsigned options) {
3788   if (clang_Cursor_isNull(C))
3789     return clang_getNullRange();
3790
3791   ASTContext &Ctx = getCursorContext(C);
3792
3793   if (clang_isStatement(C.kind)) {
3794     const Stmt *S = getCursorStmt(C);
3795     if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3796       if (pieceIndex > 0)
3797         return clang_getNullRange();
3798       return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3799     }
3800
3801     return clang_getNullRange();
3802   }
3803
3804   if (C.kind == CXCursor_ObjCMessageExpr) {
3805     if (const ObjCMessageExpr *
3806           ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3807       if (pieceIndex >= ME->getNumSelectorLocs())
3808         return clang_getNullRange();
3809       return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3810     }
3811   }
3812
3813   if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3814       C.kind == CXCursor_ObjCClassMethodDecl) {
3815     if (const ObjCMethodDecl *
3816           MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3817       if (pieceIndex >= MD->getNumSelectorLocs())
3818         return clang_getNullRange();
3819       return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3820     }
3821   }
3822
3823   if (C.kind == CXCursor_ObjCCategoryDecl ||
3824       C.kind == CXCursor_ObjCCategoryImplDecl) {
3825     if (pieceIndex > 0)
3826       return clang_getNullRange();
3827     if (const ObjCCategoryDecl *
3828           CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3829       return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3830     if (const ObjCCategoryImplDecl *
3831           CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3832       return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3833   }
3834
3835   if (C.kind == CXCursor_ModuleImportDecl) {
3836     if (pieceIndex > 0)
3837       return clang_getNullRange();
3838     if (const ImportDecl *ImportD =
3839             dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
3840       ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
3841       if (!Locs.empty())
3842         return cxloc::translateSourceRange(Ctx,
3843                                          SourceRange(Locs.front(), Locs.back()));
3844     }
3845     return clang_getNullRange();
3846   }
3847
3848   if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
3849       C.kind == CXCursor_ConversionFunction) {
3850     if (pieceIndex > 0)
3851       return clang_getNullRange();
3852     if (const FunctionDecl *FD =
3853             dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
3854       DeclarationNameInfo FunctionName = FD->getNameInfo();
3855       return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
3856     }
3857     return clang_getNullRange();
3858   }
3859
3860   // FIXME: A CXCursor_InclusionDirective should give the location of the
3861   // filename, but we don't keep track of this.
3862
3863   // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3864   // but we don't keep track of this.
3865
3866   // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3867   // but we don't keep track of this.
3868
3869   // Default handling, give the location of the cursor.
3870
3871   if (pieceIndex > 0)
3872     return clang_getNullRange();
3873
3874   CXSourceLocation CXLoc = clang_getCursorLocation(C);
3875   SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3876   return cxloc::translateSourceRange(Ctx, Loc);
3877 }
3878
3879 CXString clang_Cursor_getMangling(CXCursor C) {
3880   if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
3881     return cxstring::createEmpty();
3882
3883   // Mangling only works for functions and variables.
3884   const Decl *D = getCursorDecl(C);
3885   if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
3886     return cxstring::createEmpty();
3887
3888   // First apply frontend mangling.
3889   const NamedDecl *ND = cast<NamedDecl>(D);
3890   ASTContext &Ctx = ND->getASTContext();
3891   std::unique_ptr<MangleContext> MC(Ctx.createMangleContext());
3892
3893   std::string FrontendBuf;
3894   llvm::raw_string_ostream FrontendBufOS(FrontendBuf);
3895   MC->mangleName(ND, FrontendBufOS);
3896
3897   // Now apply backend mangling.
3898   std::unique_ptr<llvm::DataLayout> DL(
3899       new llvm::DataLayout(Ctx.getTargetInfo().getDataLayoutString()));
3900
3901   std::string FinalBuf;
3902   llvm::raw_string_ostream FinalBufOS(FinalBuf);
3903   llvm::Mangler::getNameWithPrefix(FinalBufOS, llvm::Twine(FrontendBufOS.str()),
3904                                    *DL);
3905
3906   return cxstring::createDup(FinalBufOS.str());
3907 }
3908
3909 CXString clang_getCursorDisplayName(CXCursor C) {
3910   if (!clang_isDeclaration(C.kind))
3911     return clang_getCursorSpelling(C);
3912   
3913   const Decl *D = getCursorDecl(C);
3914   if (!D)
3915     return cxstring::createEmpty();
3916
3917   PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
3918   if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3919     D = FunTmpl->getTemplatedDecl();
3920   
3921   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3922     SmallString<64> Str;
3923     llvm::raw_svector_ostream OS(Str);
3924     OS << *Function;
3925     if (Function->getPrimaryTemplate())
3926       OS << "<>";
3927     OS << "(";
3928     for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3929       if (I)
3930         OS << ", ";
3931       OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3932     }
3933     
3934     if (Function->isVariadic()) {
3935       if (Function->getNumParams())
3936         OS << ", ";
3937       OS << "...";
3938     }
3939     OS << ")";
3940     return cxstring::createDup(OS.str());
3941   }
3942   
3943   if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3944     SmallString<64> Str;
3945     llvm::raw_svector_ostream OS(Str);
3946     OS << *ClassTemplate;
3947     OS << "<";
3948     TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3949     for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3950       if (I)
3951         OS << ", ";
3952       
3953       NamedDecl *Param = Params->getParam(I);
3954       if (Param->getIdentifier()) {
3955         OS << Param->getIdentifier()->getName();
3956         continue;
3957       }
3958       
3959       // There is no parameter name, which makes this tricky. Try to come up
3960       // with something useful that isn't too long.
3961       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3962         OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3963       else if (NonTypeTemplateParmDecl *NTTP
3964                                     = dyn_cast<NonTypeTemplateParmDecl>(Param))
3965         OS << NTTP->getType().getAsString(Policy);
3966       else
3967         OS << "template<...> class";
3968     }
3969     
3970     OS << ">";
3971     return cxstring::createDup(OS.str());
3972   }
3973   
3974   if (const ClassTemplateSpecializationDecl *ClassSpec
3975                               = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3976     // If the type was explicitly written, use that.
3977     if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3978       return cxstring::createDup(TSInfo->getType().getAsString(Policy));
3979     
3980     SmallString<128> Str;
3981     llvm::raw_svector_ostream OS(Str);
3982     OS << *ClassSpec;
3983     TemplateSpecializationType::PrintTemplateArgumentList(OS,
3984                                       ClassSpec->getTemplateArgs().data(),
3985                                       ClassSpec->getTemplateArgs().size(),
3986                                                                 Policy);
3987     return cxstring::createDup(OS.str());
3988   }
3989   
3990   return clang_getCursorSpelling(C);
3991 }
3992   
3993 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
3994   switch (Kind) {
3995   case CXCursor_FunctionDecl:
3996       return cxstring::createRef("FunctionDecl");
3997   case CXCursor_TypedefDecl:
3998       return cxstring::createRef("TypedefDecl");
3999   case CXCursor_EnumDecl:
4000       return cxstring::createRef("EnumDecl");
4001   case CXCursor_EnumConstantDecl:
4002       return cxstring::createRef("EnumConstantDecl");
4003   case CXCursor_StructDecl:
4004       return cxstring::createRef("StructDecl");
4005   case CXCursor_UnionDecl:
4006       return cxstring::createRef("UnionDecl");
4007   case CXCursor_ClassDecl:
4008       return cxstring::createRef("ClassDecl");
4009   case CXCursor_FieldDecl:
4010       return cxstring::createRef("FieldDecl");
4011   case CXCursor_VarDecl:
4012       return cxstring::createRef("VarDecl");
4013   case CXCursor_ParmDecl:
4014       return cxstring::createRef("ParmDecl");
4015   case CXCursor_ObjCInterfaceDecl:
4016       return cxstring::createRef("ObjCInterfaceDecl");
4017   case CXCursor_ObjCCategoryDecl:
4018       return cxstring::createRef("ObjCCategoryDecl");
4019   case CXCursor_ObjCProtocolDecl:
4020       return cxstring::createRef("ObjCProtocolDecl");
4021   case CXCursor_ObjCPropertyDecl:
4022       return cxstring::createRef("ObjCPropertyDecl");
4023   case CXCursor_ObjCIvarDecl:
4024       return cxstring::createRef("ObjCIvarDecl");
4025   case CXCursor_ObjCInstanceMethodDecl:
4026       return cxstring::createRef("ObjCInstanceMethodDecl");
4027   case CXCursor_ObjCClassMethodDecl:
4028       return cxstring::createRef("ObjCClassMethodDecl");
4029   case CXCursor_ObjCImplementationDecl:
4030       return cxstring::createRef("ObjCImplementationDecl");
4031   case CXCursor_ObjCCategoryImplDecl:
4032       return cxstring::createRef("ObjCCategoryImplDecl");
4033   case CXCursor_CXXMethod:
4034       return cxstring::createRef("CXXMethod");
4035   case CXCursor_UnexposedDecl:
4036       return cxstring::createRef("UnexposedDecl");
4037   case CXCursor_ObjCSuperClassRef:
4038       return cxstring::createRef("ObjCSuperClassRef");
4039   case CXCursor_ObjCProtocolRef:
4040       return cxstring::createRef("ObjCProtocolRef");
4041   case CXCursor_ObjCClassRef:
4042       return cxstring::createRef("ObjCClassRef");
4043   case CXCursor_TypeRef:
4044       return cxstring::createRef("TypeRef");
4045   case CXCursor_TemplateRef:
4046       return cxstring::createRef("TemplateRef");
4047   case CXCursor_NamespaceRef:
4048     return cxstring::createRef("NamespaceRef");
4049   case CXCursor_MemberRef:
4050     return cxstring::createRef("MemberRef");
4051   case CXCursor_LabelRef:
4052     return cxstring::createRef("LabelRef");
4053   case CXCursor_OverloadedDeclRef:
4054     return cxstring::createRef("OverloadedDeclRef");
4055   case CXCursor_VariableRef:
4056     return cxstring::createRef("VariableRef");
4057   case CXCursor_IntegerLiteral:
4058       return cxstring::createRef("IntegerLiteral");
4059   case CXCursor_FloatingLiteral:
4060       return cxstring::createRef("FloatingLiteral");
4061   case CXCursor_ImaginaryLiteral:
4062       return cxstring::createRef("ImaginaryLiteral");
4063   case CXCursor_StringLiteral:
4064       return cxstring::createRef("StringLiteral");
4065   case CXCursor_CharacterLiteral:
4066       return cxstring::createRef("CharacterLiteral");
4067   case CXCursor_ParenExpr:
4068       return cxstring::createRef("ParenExpr");
4069   case CXCursor_UnaryOperator:
4070       return cxstring::createRef("UnaryOperator");
4071   case CXCursor_ArraySubscriptExpr:
4072       return cxstring::createRef("ArraySubscriptExpr");
4073   case CXCursor_OMPArraySectionExpr:
4074       return cxstring::createRef("OMPArraySectionExpr");
4075   case CXCursor_BinaryOperator:
4076       return cxstring::createRef("BinaryOperator");
4077   case CXCursor_CompoundAssignOperator:
4078       return cxstring::createRef("CompoundAssignOperator");
4079   case CXCursor_ConditionalOperator:
4080       return cxstring::createRef("ConditionalOperator");
4081   case CXCursor_CStyleCastExpr:
4082       return cxstring::createRef("CStyleCastExpr");
4083   case CXCursor_CompoundLiteralExpr:
4084       return cxstring::createRef("CompoundLiteralExpr");
4085   case CXCursor_InitListExpr:
4086       return cxstring::createRef("InitListExpr");
4087   case CXCursor_AddrLabelExpr:
4088       return cxstring::createRef("AddrLabelExpr");
4089   case CXCursor_StmtExpr:
4090       return cxstring::createRef("StmtExpr");
4091   case CXCursor_GenericSelectionExpr:
4092       return cxstring::createRef("GenericSelectionExpr");
4093   case CXCursor_GNUNullExpr:
4094       return cxstring::createRef("GNUNullExpr");
4095   case CXCursor_CXXStaticCastExpr:
4096       return cxstring::createRef("CXXStaticCastExpr");
4097   case CXCursor_CXXDynamicCastExpr:
4098       return cxstring::createRef("CXXDynamicCastExpr");
4099   case CXCursor_CXXReinterpretCastExpr:
4100       return cxstring::createRef("CXXReinterpretCastExpr");
4101   case CXCursor_CXXConstCastExpr:
4102       return cxstring::createRef("CXXConstCastExpr");
4103   case CXCursor_CXXFunctionalCastExpr:
4104       return cxstring::createRef("CXXFunctionalCastExpr");
4105   case CXCursor_CXXTypeidExpr:
4106       return cxstring::createRef("CXXTypeidExpr");
4107   case CXCursor_CXXBoolLiteralExpr:
4108       return cxstring::createRef("CXXBoolLiteralExpr");
4109   case CXCursor_CXXNullPtrLiteralExpr:
4110       return cxstring::createRef("CXXNullPtrLiteralExpr");
4111   case CXCursor_CXXThisExpr:
4112       return cxstring::createRef("CXXThisExpr");
4113   case CXCursor_CXXThrowExpr:
4114       return cxstring::createRef("CXXThrowExpr");
4115   case CXCursor_CXXNewExpr:
4116       return cxstring::createRef("CXXNewExpr");
4117   case CXCursor_CXXDeleteExpr:
4118       return cxstring::createRef("CXXDeleteExpr");
4119   case CXCursor_UnaryExpr:
4120       return cxstring::createRef("UnaryExpr");
4121   case CXCursor_ObjCStringLiteral:
4122       return cxstring::createRef("ObjCStringLiteral");
4123   case CXCursor_ObjCBoolLiteralExpr:
4124       return cxstring::createRef("ObjCBoolLiteralExpr");
4125   case CXCursor_ObjCSelfExpr:
4126       return cxstring::createRef("ObjCSelfExpr");
4127   case CXCursor_ObjCEncodeExpr:
4128       return cxstring::createRef("ObjCEncodeExpr");
4129   case CXCursor_ObjCSelectorExpr:
4130       return cxstring::createRef("ObjCSelectorExpr");
4131   case CXCursor_ObjCProtocolExpr:
4132       return cxstring::createRef("ObjCProtocolExpr");
4133   case CXCursor_ObjCBridgedCastExpr:
4134       return cxstring::createRef("ObjCBridgedCastExpr");
4135   case CXCursor_BlockExpr:
4136       return cxstring::createRef("BlockExpr");
4137   case CXCursor_PackExpansionExpr:
4138       return cxstring::createRef("PackExpansionExpr");
4139   case CXCursor_SizeOfPackExpr:
4140       return cxstring::createRef("SizeOfPackExpr");
4141   case CXCursor_LambdaExpr:
4142     return cxstring::createRef("LambdaExpr");
4143   case CXCursor_UnexposedExpr:
4144       return cxstring::createRef("UnexposedExpr");
4145   case CXCursor_DeclRefExpr:
4146       return cxstring::createRef("DeclRefExpr");
4147   case CXCursor_MemberRefExpr:
4148       return cxstring::createRef("MemberRefExpr");
4149   case CXCursor_CallExpr:
4150       return cxstring::createRef("CallExpr");
4151   case CXCursor_ObjCMessageExpr:
4152       return cxstring::createRef("ObjCMessageExpr");
4153   case CXCursor_UnexposedStmt:
4154       return cxstring::createRef("UnexposedStmt");
4155   case CXCursor_DeclStmt:
4156       return cxstring::createRef("DeclStmt");
4157   case CXCursor_LabelStmt:
4158       return cxstring::createRef("LabelStmt");
4159   case CXCursor_CompoundStmt:
4160       return cxstring::createRef("CompoundStmt");
4161   case CXCursor_CaseStmt:
4162       return cxstring::createRef("CaseStmt");
4163   case CXCursor_DefaultStmt:
4164       return cxstring::createRef("DefaultStmt");
4165   case CXCursor_IfStmt:
4166       return cxstring::createRef("IfStmt");
4167   case CXCursor_SwitchStmt:
4168       return cxstring::createRef("SwitchStmt");
4169   case CXCursor_WhileStmt:
4170       return cxstring::createRef("WhileStmt");
4171   case CXCursor_DoStmt:
4172       return cxstring::createRef("DoStmt");
4173   case CXCursor_ForStmt:
4174       return cxstring::createRef("ForStmt");
4175   case CXCursor_GotoStmt:
4176       return cxstring::createRef("GotoStmt");
4177   case CXCursor_IndirectGotoStmt:
4178       return cxstring::createRef("IndirectGotoStmt");
4179   case CXCursor_ContinueStmt:
4180       return cxstring::createRef("ContinueStmt");
4181   case CXCursor_BreakStmt:
4182       return cxstring::createRef("BreakStmt");
4183   case CXCursor_ReturnStmt:
4184       return cxstring::createRef("ReturnStmt");
4185   case CXCursor_GCCAsmStmt:
4186       return cxstring::createRef("GCCAsmStmt");
4187   case CXCursor_MSAsmStmt:
4188       return cxstring::createRef("MSAsmStmt");
4189   case CXCursor_ObjCAtTryStmt:
4190       return cxstring::createRef("ObjCAtTryStmt");
4191   case CXCursor_ObjCAtCatchStmt:
4192       return cxstring::createRef("ObjCAtCatchStmt");
4193   case CXCursor_ObjCAtFinallyStmt:
4194       return cxstring::createRef("ObjCAtFinallyStmt");
4195   case CXCursor_ObjCAtThrowStmt:
4196       return cxstring::createRef("ObjCAtThrowStmt");
4197   case CXCursor_ObjCAtSynchronizedStmt:
4198       return cxstring::createRef("ObjCAtSynchronizedStmt");
4199   case CXCursor_ObjCAutoreleasePoolStmt:
4200       return cxstring::createRef("ObjCAutoreleasePoolStmt");
4201   case CXCursor_ObjCForCollectionStmt:
4202       return cxstring::createRef("ObjCForCollectionStmt");
4203   case CXCursor_CXXCatchStmt:
4204       return cxstring::createRef("CXXCatchStmt");
4205   case CXCursor_CXXTryStmt:
4206       return cxstring::createRef("CXXTryStmt");
4207   case CXCursor_CXXForRangeStmt:
4208       return cxstring::createRef("CXXForRangeStmt");
4209   case CXCursor_SEHTryStmt:
4210       return cxstring::createRef("SEHTryStmt");
4211   case CXCursor_SEHExceptStmt:
4212       return cxstring::createRef("SEHExceptStmt");
4213   case CXCursor_SEHFinallyStmt:
4214       return cxstring::createRef("SEHFinallyStmt");
4215   case CXCursor_SEHLeaveStmt:
4216       return cxstring::createRef("SEHLeaveStmt");
4217   case CXCursor_NullStmt:
4218       return cxstring::createRef("NullStmt");
4219   case CXCursor_InvalidFile:
4220       return cxstring::createRef("InvalidFile");
4221   case CXCursor_InvalidCode:
4222     return cxstring::createRef("InvalidCode");
4223   case CXCursor_NoDeclFound:
4224       return cxstring::createRef("NoDeclFound");
4225   case CXCursor_NotImplemented:
4226       return cxstring::createRef("NotImplemented");
4227   case CXCursor_TranslationUnit:
4228       return cxstring::createRef("TranslationUnit");
4229   case CXCursor_UnexposedAttr:
4230       return cxstring::createRef("UnexposedAttr");
4231   case CXCursor_IBActionAttr:
4232       return cxstring::createRef("attribute(ibaction)");
4233   case CXCursor_IBOutletAttr:
4234      return cxstring::createRef("attribute(iboutlet)");
4235   case CXCursor_IBOutletCollectionAttr:
4236       return cxstring::createRef("attribute(iboutletcollection)");
4237   case CXCursor_CXXFinalAttr:
4238       return cxstring::createRef("attribute(final)");
4239   case CXCursor_CXXOverrideAttr:
4240       return cxstring::createRef("attribute(override)");
4241   case CXCursor_AnnotateAttr:
4242     return cxstring::createRef("attribute(annotate)");
4243   case CXCursor_AsmLabelAttr:
4244     return cxstring::createRef("asm label");
4245   case CXCursor_PackedAttr:
4246     return cxstring::createRef("attribute(packed)");
4247   case CXCursor_PureAttr:
4248     return cxstring::createRef("attribute(pure)");
4249   case CXCursor_ConstAttr:
4250     return cxstring::createRef("attribute(const)");
4251   case CXCursor_NoDuplicateAttr:
4252     return cxstring::createRef("attribute(noduplicate)");
4253   case CXCursor_CUDAConstantAttr:
4254     return cxstring::createRef("attribute(constant)");
4255   case CXCursor_CUDADeviceAttr:
4256     return cxstring::createRef("attribute(device)");
4257   case CXCursor_CUDAGlobalAttr:
4258     return cxstring::createRef("attribute(global)");
4259   case CXCursor_CUDAHostAttr:
4260     return cxstring::createRef("attribute(host)");
4261   case CXCursor_CUDASharedAttr:
4262     return cxstring::createRef("attribute(shared)");
4263   case CXCursor_VisibilityAttr:
4264     return cxstring::createRef("attribute(visibility)");
4265   case CXCursor_PreprocessingDirective:
4266     return cxstring::createRef("preprocessing directive");
4267   case CXCursor_MacroDefinition:
4268     return cxstring::createRef("macro definition");
4269   case CXCursor_MacroExpansion:
4270     return cxstring::createRef("macro expansion");
4271   case CXCursor_InclusionDirective:
4272     return cxstring::createRef("inclusion directive");
4273   case CXCursor_Namespace:
4274     return cxstring::createRef("Namespace");
4275   case CXCursor_LinkageSpec:
4276     return cxstring::createRef("LinkageSpec");
4277   case CXCursor_CXXBaseSpecifier:
4278     return cxstring::createRef("C++ base class specifier");
4279   case CXCursor_Constructor:
4280     return cxstring::createRef("CXXConstructor");
4281   case CXCursor_Destructor:
4282     return cxstring::createRef("CXXDestructor");
4283   case CXCursor_ConversionFunction:
4284     return cxstring::createRef("CXXConversion");
4285   case CXCursor_TemplateTypeParameter:
4286     return cxstring::createRef("TemplateTypeParameter");
4287   case CXCursor_NonTypeTemplateParameter:
4288     return cxstring::createRef("NonTypeTemplateParameter");
4289   case CXCursor_TemplateTemplateParameter:
4290     return cxstring::createRef("TemplateTemplateParameter");
4291   case CXCursor_FunctionTemplate:
4292     return cxstring::createRef("FunctionTemplate");
4293   case CXCursor_ClassTemplate:
4294     return cxstring::createRef("ClassTemplate");
4295   case CXCursor_ClassTemplatePartialSpecialization:
4296     return cxstring::createRef("ClassTemplatePartialSpecialization");
4297   case CXCursor_NamespaceAlias:
4298     return cxstring::createRef("NamespaceAlias");
4299   case CXCursor_UsingDirective:
4300     return cxstring::createRef("UsingDirective");
4301   case CXCursor_UsingDeclaration:
4302     return cxstring::createRef("UsingDeclaration");
4303   case CXCursor_TypeAliasDecl:
4304     return cxstring::createRef("TypeAliasDecl");
4305   case CXCursor_ObjCSynthesizeDecl:
4306     return cxstring::createRef("ObjCSynthesizeDecl");
4307   case CXCursor_ObjCDynamicDecl:
4308     return cxstring::createRef("ObjCDynamicDecl");
4309   case CXCursor_CXXAccessSpecifier:
4310     return cxstring::createRef("CXXAccessSpecifier");
4311   case CXCursor_ModuleImportDecl:
4312     return cxstring::createRef("ModuleImport");
4313   case CXCursor_OMPParallelDirective:
4314     return cxstring::createRef("OMPParallelDirective");
4315   case CXCursor_OMPSimdDirective:
4316     return cxstring::createRef("OMPSimdDirective");
4317   case CXCursor_OMPForDirective:
4318     return cxstring::createRef("OMPForDirective");
4319   case CXCursor_OMPForSimdDirective:
4320     return cxstring::createRef("OMPForSimdDirective");
4321   case CXCursor_OMPSectionsDirective:
4322     return cxstring::createRef("OMPSectionsDirective");
4323   case CXCursor_OMPSectionDirective:
4324     return cxstring::createRef("OMPSectionDirective");
4325   case CXCursor_OMPSingleDirective:
4326     return cxstring::createRef("OMPSingleDirective");
4327   case CXCursor_OMPMasterDirective:
4328     return cxstring::createRef("OMPMasterDirective");
4329   case CXCursor_OMPCriticalDirective:
4330     return cxstring::createRef("OMPCriticalDirective");
4331   case CXCursor_OMPParallelForDirective:
4332     return cxstring::createRef("OMPParallelForDirective");
4333   case CXCursor_OMPParallelForSimdDirective:
4334     return cxstring::createRef("OMPParallelForSimdDirective");
4335   case CXCursor_OMPParallelSectionsDirective:
4336     return cxstring::createRef("OMPParallelSectionsDirective");
4337   case CXCursor_OMPTaskDirective:
4338     return cxstring::createRef("OMPTaskDirective");
4339   case CXCursor_OMPTaskyieldDirective:
4340     return cxstring::createRef("OMPTaskyieldDirective");
4341   case CXCursor_OMPBarrierDirective:
4342     return cxstring::createRef("OMPBarrierDirective");
4343   case CXCursor_OMPTaskwaitDirective:
4344     return cxstring::createRef("OMPTaskwaitDirective");
4345   case CXCursor_OMPTaskgroupDirective:
4346     return cxstring::createRef("OMPTaskgroupDirective");
4347   case CXCursor_OMPFlushDirective:
4348     return cxstring::createRef("OMPFlushDirective");
4349   case CXCursor_OMPOrderedDirective:
4350     return cxstring::createRef("OMPOrderedDirective");
4351   case CXCursor_OMPAtomicDirective:
4352     return cxstring::createRef("OMPAtomicDirective");
4353   case CXCursor_OMPTargetDirective:
4354     return cxstring::createRef("OMPTargetDirective");
4355   case CXCursor_OMPTargetDataDirective:
4356     return cxstring::createRef("OMPTargetDataDirective");
4357   case CXCursor_OMPTeamsDirective:
4358     return cxstring::createRef("OMPTeamsDirective");
4359   case CXCursor_OMPCancellationPointDirective:
4360     return cxstring::createRef("OMPCancellationPointDirective");
4361   case CXCursor_OMPCancelDirective:
4362     return cxstring::createRef("OMPCancelDirective");
4363   case CXCursor_OverloadCandidate:
4364       return cxstring::createRef("OverloadCandidate");
4365   }
4366
4367   llvm_unreachable("Unhandled CXCursorKind");
4368 }
4369
4370 struct GetCursorData {
4371   SourceLocation TokenBeginLoc;
4372   bool PointsAtMacroArgExpansion;
4373   bool VisitedObjCPropertyImplDecl;
4374   SourceLocation VisitedDeclaratorDeclStartLoc;
4375   CXCursor &BestCursor;
4376
4377   GetCursorData(SourceManager &SM,
4378                 SourceLocation tokenBegin, CXCursor &outputCursor)
4379     : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
4380     PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
4381     VisitedObjCPropertyImplDecl = false;
4382   }
4383 };
4384
4385 static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
4386                                                 CXCursor parent,
4387                                                 CXClientData client_data) {
4388   GetCursorData *Data = static_cast<GetCursorData *>(client_data);
4389   CXCursor *BestCursor = &Data->BestCursor;
4390
4391   // If we point inside a macro argument we should provide info of what the
4392   // token is so use the actual cursor, don't replace it with a macro expansion
4393   // cursor.
4394   if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
4395     return CXChildVisit_Recurse;
4396   
4397   if (clang_isDeclaration(cursor.kind)) {
4398     // Avoid having the implicit methods override the property decls.
4399     if (const ObjCMethodDecl *MD
4400           = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4401       if (MD->isImplicit())
4402         return CXChildVisit_Break;
4403
4404     } else if (const ObjCInterfaceDecl *ID
4405                  = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
4406       // Check that when we have multiple @class references in the same line,
4407       // that later ones do not override the previous ones.
4408       // If we have:
4409       // @class Foo, Bar;
4410       // source ranges for both start at '@', so 'Bar' will end up overriding
4411       // 'Foo' even though the cursor location was at 'Foo'.
4412       if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
4413           BestCursor->kind == CXCursor_ObjCClassRef)
4414         if (const ObjCInterfaceDecl *PrevID
4415              = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
4416          if (PrevID != ID &&
4417              !PrevID->isThisDeclarationADefinition() &&
4418              !ID->isThisDeclarationADefinition())
4419            return CXChildVisit_Break;
4420         }
4421
4422     } else if (const DeclaratorDecl *DD
4423                     = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
4424       SourceLocation StartLoc = DD->getSourceRange().getBegin();
4425       // Check that when we have multiple declarators in the same line,
4426       // that later ones do not override the previous ones.
4427       // If we have:
4428       // int Foo, Bar;
4429       // source ranges for both start at 'int', so 'Bar' will end up overriding
4430       // 'Foo' even though the cursor location was at 'Foo'.
4431       if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
4432         return CXChildVisit_Break;
4433       Data->VisitedDeclaratorDeclStartLoc = StartLoc;
4434
4435     } else if (const ObjCPropertyImplDecl *PropImp
4436               = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
4437       (void)PropImp;
4438       // Check that when we have multiple @synthesize in the same line,
4439       // that later ones do not override the previous ones.
4440       // If we have:
4441       // @synthesize Foo, Bar;
4442       // source ranges for both start at '@', so 'Bar' will end up overriding
4443       // 'Foo' even though the cursor location was at 'Foo'.
4444       if (Data->VisitedObjCPropertyImplDecl)
4445         return CXChildVisit_Break;
4446       Data->VisitedObjCPropertyImplDecl = true;
4447     }
4448   }
4449
4450   if (clang_isExpression(cursor.kind) &&
4451       clang_isDeclaration(BestCursor->kind)) {
4452     if (const Decl *D = getCursorDecl(*BestCursor)) {
4453       // Avoid having the cursor of an expression replace the declaration cursor
4454       // when the expression source range overlaps the declaration range.
4455       // This can happen for C++ constructor expressions whose range generally
4456       // include the variable declaration, e.g.:
4457       //  MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
4458       if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
4459           D->getLocation() == Data->TokenBeginLoc)
4460         return CXChildVisit_Break;
4461     }
4462   }
4463
4464   // If our current best cursor is the construction of a temporary object, 
4465   // don't replace that cursor with a type reference, because we want 
4466   // clang_getCursor() to point at the constructor.
4467   if (clang_isExpression(BestCursor->kind) &&
4468       isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
4469       cursor.kind == CXCursor_TypeRef) {
4470     // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
4471     // as having the actual point on the type reference.
4472     *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
4473     return CXChildVisit_Recurse;
4474   }
4475
4476   // If we already have an Objective-C superclass reference, don't
4477   // update it further.
4478   if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
4479     return CXChildVisit_Break;
4480
4481   *BestCursor = cursor;
4482   return CXChildVisit_Recurse;
4483 }
4484
4485 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
4486   if (isNotUsableTU(TU)) {
4487     LOG_BAD_TU(TU);
4488     return clang_getNullCursor();
4489   }
4490
4491   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4492   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4493
4494   SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
4495   CXCursor Result = cxcursor::getCursor(TU, SLoc);
4496
4497   LOG_FUNC_SECTION {
4498     CXFile SearchFile;
4499     unsigned SearchLine, SearchColumn;
4500     CXFile ResultFile;
4501     unsigned ResultLine, ResultColumn;
4502     CXString SearchFileName, ResultFileName, KindSpelling, USR;
4503     const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
4504     CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
4505
4506     clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
4507                           nullptr);
4508     clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
4509                           &ResultColumn, nullptr);
4510     SearchFileName = clang_getFileName(SearchFile);
4511     ResultFileName = clang_getFileName(ResultFile);
4512     KindSpelling = clang_getCursorKindSpelling(Result.kind);
4513     USR = clang_getCursorUSR(Result);
4514     *Log << llvm::format("(%s:%d:%d) = %s",
4515                    clang_getCString(SearchFileName), SearchLine, SearchColumn,
4516                    clang_getCString(KindSpelling))
4517         << llvm::format("(%s:%d:%d):%s%s",
4518                      clang_getCString(ResultFileName), ResultLine, ResultColumn,
4519                      clang_getCString(USR), IsDef);
4520     clang_disposeString(SearchFileName);
4521     clang_disposeString(ResultFileName);
4522     clang_disposeString(KindSpelling);
4523     clang_disposeString(USR);
4524     
4525     CXCursor Definition = clang_getCursorDefinition(Result);
4526     if (!clang_equalCursors(Definition, clang_getNullCursor())) {
4527       CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
4528       CXString DefinitionKindSpelling
4529                                 = clang_getCursorKindSpelling(Definition.kind);
4530       CXFile DefinitionFile;
4531       unsigned DefinitionLine, DefinitionColumn;
4532       clang_getFileLocation(DefinitionLoc, &DefinitionFile,
4533                             &DefinitionLine, &DefinitionColumn, nullptr);
4534       CXString DefinitionFileName = clang_getFileName(DefinitionFile);
4535       *Log << llvm::format("  -> %s(%s:%d:%d)",
4536                      clang_getCString(DefinitionKindSpelling),
4537                      clang_getCString(DefinitionFileName),
4538                      DefinitionLine, DefinitionColumn);
4539       clang_disposeString(DefinitionFileName);
4540       clang_disposeString(DefinitionKindSpelling);
4541     }
4542   }
4543
4544   return Result;
4545 }
4546
4547 CXCursor clang_getNullCursor(void) {
4548   return MakeCXCursorInvalid(CXCursor_InvalidFile);
4549 }
4550
4551 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
4552   // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
4553   // can't set consistently. For example, when visiting a DeclStmt we will set
4554   // it but we don't set it on the result of clang_getCursorDefinition for
4555   // a reference of the same declaration.
4556   // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
4557   // when visiting a DeclStmt currently, the AST should be enhanced to be able
4558   // to provide that kind of info.
4559   if (clang_isDeclaration(X.kind))
4560     X.data[1] = nullptr;
4561   if (clang_isDeclaration(Y.kind))
4562     Y.data[1] = nullptr;
4563
4564   return X == Y;
4565 }
4566
4567 unsigned clang_hashCursor(CXCursor C) {
4568   unsigned Index = 0;
4569   if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
4570     Index = 1;
4571   
4572   return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
4573                                         std::make_pair(C.kind, C.data[Index]));
4574 }
4575
4576 unsigned clang_isInvalid(enum CXCursorKind K) {
4577   return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
4578 }
4579
4580 unsigned clang_isDeclaration(enum CXCursorKind K) {
4581   return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
4582          (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
4583 }
4584
4585 unsigned clang_isReference(enum CXCursorKind K) {
4586   return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
4587 }
4588
4589 unsigned clang_isExpression(enum CXCursorKind K) {
4590   return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
4591 }
4592
4593 unsigned clang_isStatement(enum CXCursorKind K) {
4594   return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
4595 }
4596
4597 unsigned clang_isAttribute(enum CXCursorKind K) {
4598     return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
4599 }
4600
4601 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
4602   return K == CXCursor_TranslationUnit;
4603 }
4604
4605 unsigned clang_isPreprocessing(enum CXCursorKind K) {
4606   return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
4607 }
4608   
4609 unsigned clang_isUnexposed(enum CXCursorKind K) {
4610   switch (K) {
4611     case CXCursor_UnexposedDecl:
4612     case CXCursor_UnexposedExpr:
4613     case CXCursor_UnexposedStmt:
4614     case CXCursor_UnexposedAttr:
4615       return true;
4616     default:
4617       return false;
4618   }
4619 }
4620
4621 CXCursorKind clang_getCursorKind(CXCursor C) {
4622   return C.kind;
4623 }
4624
4625 CXSourceLocation clang_getCursorLocation(CXCursor C) {
4626   if (clang_isReference(C.kind)) {
4627     switch (C.kind) {
4628     case CXCursor_ObjCSuperClassRef: {
4629       std::pair<const ObjCInterfaceDecl *, SourceLocation> P
4630         = getCursorObjCSuperClassRef(C);
4631       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4632     }
4633
4634     case CXCursor_ObjCProtocolRef: {
4635       std::pair<const ObjCProtocolDecl *, SourceLocation> P
4636         = getCursorObjCProtocolRef(C);
4637       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4638     }
4639
4640     case CXCursor_ObjCClassRef: {
4641       std::pair<const ObjCInterfaceDecl *, SourceLocation> P
4642         = getCursorObjCClassRef(C);
4643       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4644     }
4645
4646     case CXCursor_TypeRef: {
4647       std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
4648       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4649     }
4650
4651     case CXCursor_TemplateRef: {
4652       std::pair<const TemplateDecl *, SourceLocation> P =
4653           getCursorTemplateRef(C);
4654       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4655     }
4656
4657     case CXCursor_NamespaceRef: {
4658       std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
4659       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4660     }
4661
4662     case CXCursor_MemberRef: {
4663       std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
4664       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4665     }
4666
4667     case CXCursor_VariableRef: {
4668       std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
4669       return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
4670     }
4671
4672     case CXCursor_CXXBaseSpecifier: {
4673       const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
4674       if (!BaseSpec)
4675         return clang_getNullLocation();
4676       
4677       if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
4678         return cxloc::translateSourceLocation(getCursorContext(C),
4679                                             TSInfo->getTypeLoc().getBeginLoc());
4680       
4681       return cxloc::translateSourceLocation(getCursorContext(C),
4682                                         BaseSpec->getLocStart());
4683     }
4684
4685     case CXCursor_LabelRef: {
4686       std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
4687       return cxloc::translateSourceLocation(getCursorContext(C), P.second);
4688     }
4689
4690     case CXCursor_OverloadedDeclRef:
4691       return cxloc::translateSourceLocation(getCursorContext(C),
4692                                           getCursorOverloadedDeclRef(C).second);
4693
4694     default:
4695       // FIXME: Need a way to enumerate all non-reference cases.
4696       llvm_unreachable("Missed a reference kind");
4697     }
4698   }
4699
4700   if (clang_isExpression(C.kind))
4701     return cxloc::translateSourceLocation(getCursorContext(C),
4702                                    getLocationFromExpr(getCursorExpr(C)));
4703
4704   if (clang_isStatement(C.kind))
4705     return cxloc::translateSourceLocation(getCursorContext(C),
4706                                           getCursorStmt(C)->getLocStart());
4707
4708   if (C.kind == CXCursor_PreprocessingDirective) {
4709     SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
4710     return cxloc::translateSourceLocation(getCursorContext(C), L);
4711   }
4712
4713   if (C.kind == CXCursor_MacroExpansion) {
4714     SourceLocation L
4715       = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
4716     return cxloc::translateSourceLocation(getCursorContext(C), L);
4717   }
4718
4719   if (C.kind == CXCursor_MacroDefinition) {
4720     SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
4721     return cxloc::translateSourceLocation(getCursorContext(C), L);
4722   }
4723
4724   if (C.kind == CXCursor_InclusionDirective) {
4725     SourceLocation L
4726       = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
4727     return cxloc::translateSourceLocation(getCursorContext(C), L);
4728   }
4729
4730   if (clang_isAttribute(C.kind)) {
4731     SourceLocation L
4732       = cxcursor::getCursorAttr(C)->getLocation();
4733     return cxloc::translateSourceLocation(getCursorContext(C), L);
4734   }
4735
4736   if (!clang_isDeclaration(C.kind))
4737     return clang_getNullLocation();
4738
4739   const Decl *D = getCursorDecl(C);
4740   if (!D)
4741     return clang_getNullLocation();
4742
4743   SourceLocation Loc = D->getLocation();
4744   // FIXME: Multiple variables declared in a single declaration
4745   // currently lack the information needed to correctly determine their
4746   // ranges when accounting for the type-specifier.  We use context
4747   // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4748   // and if so, whether it is the first decl.
4749   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4750     if (!cxcursor::isFirstInDeclGroup(C))
4751       Loc = VD->getLocation();
4752   }
4753
4754   // For ObjC methods, give the start location of the method name.
4755   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4756     Loc = MD->getSelectorStartLoc();
4757
4758   return cxloc::translateSourceLocation(getCursorContext(C), Loc);
4759 }
4760
4761 } // end extern "C"
4762
4763 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
4764   assert(TU);
4765
4766   // Guard against an invalid SourceLocation, or we may assert in one
4767   // of the following calls.
4768   if (SLoc.isInvalid())
4769     return clang_getNullCursor();
4770
4771   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4772
4773   // Translate the given source location to make it point at the beginning of
4774   // the token under the cursor.
4775   SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
4776                                     CXXUnit->getASTContext().getLangOpts());
4777   
4778   CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4779   if (SLoc.isValid()) {
4780     GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
4781     CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4782                             /*VisitPreprocessorLast=*/true, 
4783                             /*VisitIncludedEntities=*/false,
4784                             SourceLocation(SLoc));
4785     CursorVis.visitFileRegion();
4786   }
4787
4788   return Result;
4789 }
4790
4791 static SourceRange getRawCursorExtent(CXCursor C) {
4792   if (clang_isReference(C.kind)) {
4793     switch (C.kind) {
4794     case CXCursor_ObjCSuperClassRef:
4795       return  getCursorObjCSuperClassRef(C).second;
4796
4797     case CXCursor_ObjCProtocolRef:
4798       return getCursorObjCProtocolRef(C).second;
4799
4800     case CXCursor_ObjCClassRef:
4801       return getCursorObjCClassRef(C).second;
4802
4803     case CXCursor_TypeRef:
4804       return getCursorTypeRef(C).second;
4805
4806     case CXCursor_TemplateRef:
4807       return getCursorTemplateRef(C).second;
4808
4809     case CXCursor_NamespaceRef:
4810       return getCursorNamespaceRef(C).second;
4811
4812     case CXCursor_MemberRef:
4813       return getCursorMemberRef(C).second;
4814
4815     case CXCursor_CXXBaseSpecifier:
4816       return getCursorCXXBaseSpecifier(C)->getSourceRange();
4817
4818     case CXCursor_LabelRef:
4819       return getCursorLabelRef(C).second;
4820
4821     case CXCursor_OverloadedDeclRef:
4822       return getCursorOverloadedDeclRef(C).second;
4823
4824     case CXCursor_VariableRef:
4825       return getCursorVariableRef(C).second;
4826         
4827     default:
4828       // FIXME: Need a way to enumerate all non-reference cases.
4829       llvm_unreachable("Missed a reference kind");
4830     }
4831   }
4832
4833   if (clang_isExpression(C.kind))
4834     return getCursorExpr(C)->getSourceRange();
4835
4836   if (clang_isStatement(C.kind))
4837     return getCursorStmt(C)->getSourceRange();
4838
4839   if (clang_isAttribute(C.kind))
4840     return getCursorAttr(C)->getRange();
4841
4842   if (C.kind == CXCursor_PreprocessingDirective)
4843     return cxcursor::getCursorPreprocessingDirective(C);
4844
4845   if (C.kind == CXCursor_MacroExpansion) {
4846     ASTUnit *TU = getCursorASTUnit(C);
4847     SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
4848     return TU->mapRangeFromPreamble(Range);
4849   }
4850
4851   if (C.kind == CXCursor_MacroDefinition) {
4852     ASTUnit *TU = getCursorASTUnit(C);
4853     SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4854     return TU->mapRangeFromPreamble(Range);
4855   }
4856
4857   if (C.kind == CXCursor_InclusionDirective) {
4858     ASTUnit *TU = getCursorASTUnit(C);
4859     SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4860     return TU->mapRangeFromPreamble(Range);
4861   }
4862
4863   if (C.kind == CXCursor_TranslationUnit) {
4864     ASTUnit *TU = getCursorASTUnit(C);
4865     FileID MainID = TU->getSourceManager().getMainFileID();
4866     SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4867     SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4868     return SourceRange(Start, End);
4869   }
4870
4871   if (clang_isDeclaration(C.kind)) {
4872     const Decl *D = cxcursor::getCursorDecl(C);
4873     if (!D)
4874       return SourceRange();
4875
4876     SourceRange R = D->getSourceRange();
4877     // FIXME: Multiple variables declared in a single declaration
4878     // currently lack the information needed to correctly determine their
4879     // ranges when accounting for the type-specifier.  We use context
4880     // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4881     // and if so, whether it is the first decl.
4882     if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4883       if (!cxcursor::isFirstInDeclGroup(C))
4884         R.setBegin(VD->getLocation());
4885     }
4886     return R;
4887   }
4888   return SourceRange();
4889 }
4890
4891 /// \brief Retrieves the "raw" cursor extent, which is then extended to include
4892 /// the decl-specifier-seq for declarations.
4893 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4894   if (clang_isDeclaration(C.kind)) {
4895     const Decl *D = cxcursor::getCursorDecl(C);
4896     if (!D)
4897       return SourceRange();
4898
4899     SourceRange R = D->getSourceRange();
4900
4901     // Adjust the start of the location for declarations preceded by
4902     // declaration specifiers.
4903     SourceLocation StartLoc;
4904     if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4905       if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4906         StartLoc = TI->getTypeLoc().getLocStart();
4907     } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4908       if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4909         StartLoc = TI->getTypeLoc().getLocStart();
4910     }
4911
4912     if (StartLoc.isValid() && R.getBegin().isValid() &&
4913         SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4914       R.setBegin(StartLoc);
4915
4916     // FIXME: Multiple variables declared in a single declaration
4917     // currently lack the information needed to correctly determine their
4918     // ranges when accounting for the type-specifier.  We use context
4919     // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4920     // and if so, whether it is the first decl.
4921     if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
4922       if (!cxcursor::isFirstInDeclGroup(C))
4923         R.setBegin(VD->getLocation());
4924     }
4925
4926     return R;    
4927   }
4928   
4929   return getRawCursorExtent(C);
4930 }
4931
4932 extern "C" {
4933
4934 CXSourceRange clang_getCursorExtent(CXCursor C) {
4935   SourceRange R = getRawCursorExtent(C);
4936   if (R.isInvalid())
4937     return clang_getNullRange();
4938
4939   return cxloc::translateSourceRange(getCursorContext(C), R);
4940 }
4941
4942 CXCursor clang_getCursorReferenced(CXCursor C) {
4943   if (clang_isInvalid(C.kind))
4944     return clang_getNullCursor();
4945
4946   CXTranslationUnit tu = getCursorTU(C);
4947   if (clang_isDeclaration(C.kind)) {
4948     const Decl *D = getCursorDecl(C);
4949     if (!D)
4950       return clang_getNullCursor();
4951     if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
4952       return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
4953     if (const ObjCPropertyImplDecl *PropImpl =
4954             dyn_cast<ObjCPropertyImplDecl>(D))
4955       if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4956         return MakeCXCursor(Property, tu);
4957     
4958     return C;
4959   }
4960   
4961   if (clang_isExpression(C.kind)) {
4962     const Expr *E = getCursorExpr(C);
4963     const Decl *D = getDeclFromExpr(E);
4964     if (D) {
4965       CXCursor declCursor = MakeCXCursor(D, tu);
4966       declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4967                                                declCursor);
4968       return declCursor;
4969     }
4970     
4971     if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
4972       return MakeCursorOverloadedDeclRef(Ovl, tu);
4973         
4974     return clang_getNullCursor();
4975   }
4976
4977   if (clang_isStatement(C.kind)) {
4978     const Stmt *S = getCursorStmt(C);
4979     if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
4980       if (LabelDecl *label = Goto->getLabel())
4981         if (LabelStmt *labelS = label->getStmt())
4982         return MakeCXCursor(labelS, getCursorDecl(C), tu);
4983
4984     return clang_getNullCursor();
4985   }
4986
4987   if (C.kind == CXCursor_MacroExpansion) {
4988     if (const MacroDefinitionRecord *Def =
4989             getCursorMacroExpansion(C).getDefinition())
4990       return MakeMacroDefinitionCursor(Def, tu);
4991   }
4992
4993   if (!clang_isReference(C.kind))
4994     return clang_getNullCursor();
4995
4996   switch (C.kind) {
4997     case CXCursor_ObjCSuperClassRef:
4998       return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
4999
5000     case CXCursor_ObjCProtocolRef: {
5001       const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
5002       if (const ObjCProtocolDecl *Def = Prot->getDefinition())
5003         return MakeCXCursor(Def, tu);
5004
5005       return MakeCXCursor(Prot, tu);
5006     }
5007
5008     case CXCursor_ObjCClassRef: {
5009       const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5010       if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5011         return MakeCXCursor(Def, tu);
5012
5013       return MakeCXCursor(Class, tu);
5014     }
5015
5016     case CXCursor_TypeRef:
5017       return MakeCXCursor(getCursorTypeRef(C).first, tu );
5018
5019     case CXCursor_TemplateRef:
5020       return MakeCXCursor(getCursorTemplateRef(C).first, tu );
5021
5022     case CXCursor_NamespaceRef:
5023       return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
5024
5025     case CXCursor_MemberRef:
5026       return MakeCXCursor(getCursorMemberRef(C).first, tu );
5027
5028     case CXCursor_CXXBaseSpecifier: {
5029       const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
5030       return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
5031                                                          tu ));
5032     }
5033
5034     case CXCursor_LabelRef:
5035       // FIXME: We end up faking the "parent" declaration here because we
5036       // don't want to make CXCursor larger.
5037       return MakeCXCursor(getCursorLabelRef(C).first,
5038                           cxtu::getASTUnit(tu)->getASTContext()
5039                               .getTranslationUnitDecl(),
5040                           tu);
5041
5042     case CXCursor_OverloadedDeclRef:
5043       return C;
5044       
5045     case CXCursor_VariableRef:
5046       return MakeCXCursor(getCursorVariableRef(C).first, tu);
5047
5048     default:
5049       // We would prefer to enumerate all non-reference cursor kinds here.
5050       llvm_unreachable("Unhandled reference cursor kind");
5051   }
5052 }
5053
5054 CXCursor clang_getCursorDefinition(CXCursor C) {
5055   if (clang_isInvalid(C.kind))
5056     return clang_getNullCursor();
5057
5058   CXTranslationUnit TU = getCursorTU(C);
5059
5060   bool WasReference = false;
5061   if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
5062     C = clang_getCursorReferenced(C);
5063     WasReference = true;
5064   }
5065
5066   if (C.kind == CXCursor_MacroExpansion)
5067     return clang_getCursorReferenced(C);
5068
5069   if (!clang_isDeclaration(C.kind))
5070     return clang_getNullCursor();
5071
5072   const Decl *D = getCursorDecl(C);
5073   if (!D)
5074     return clang_getNullCursor();
5075
5076   switch (D->getKind()) {
5077   // Declaration kinds that don't really separate the notions of
5078   // declaration and definition.
5079   case Decl::Namespace:
5080   case Decl::Typedef:
5081   case Decl::TypeAlias:
5082   case Decl::TypeAliasTemplate:
5083   case Decl::TemplateTypeParm:
5084   case Decl::EnumConstant:
5085   case Decl::Field:
5086   case Decl::MSProperty:
5087   case Decl::IndirectField:
5088   case Decl::ObjCIvar:
5089   case Decl::ObjCAtDefsField:
5090   case Decl::ImplicitParam:
5091   case Decl::ParmVar:
5092   case Decl::NonTypeTemplateParm:
5093   case Decl::TemplateTemplateParm:
5094   case Decl::ObjCCategoryImpl:
5095   case Decl::ObjCImplementation:
5096   case Decl::AccessSpec:
5097   case Decl::LinkageSpec:
5098   case Decl::ObjCPropertyImpl:
5099   case Decl::FileScopeAsm:
5100   case Decl::StaticAssert:
5101   case Decl::Block:
5102   case Decl::Captured:
5103   case Decl::Label:  // FIXME: Is this right??
5104   case Decl::ClassScopeFunctionSpecialization:
5105   case Decl::Import:
5106   case Decl::OMPThreadPrivate:
5107   case Decl::ObjCTypeParam:
5108     return C;
5109
5110   // Declaration kinds that don't make any sense here, but are
5111   // nonetheless harmless.
5112   case Decl::Empty:
5113   case Decl::TranslationUnit:
5114   case Decl::ExternCContext:
5115     break;
5116
5117   // Declaration kinds for which the definition is not resolvable.
5118   case Decl::UnresolvedUsingTypename:
5119   case Decl::UnresolvedUsingValue:
5120     break;
5121
5122   case Decl::UsingDirective:
5123     return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
5124                         TU);
5125
5126   case Decl::NamespaceAlias:
5127     return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
5128
5129   case Decl::Enum:
5130   case Decl::Record:
5131   case Decl::CXXRecord:
5132   case Decl::ClassTemplateSpecialization:
5133   case Decl::ClassTemplatePartialSpecialization:
5134     if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
5135       return MakeCXCursor(Def, TU);
5136     return clang_getNullCursor();
5137
5138   case Decl::Function:
5139   case Decl::CXXMethod:
5140   case Decl::CXXConstructor:
5141   case Decl::CXXDestructor:
5142   case Decl::CXXConversion: {
5143     const FunctionDecl *Def = nullptr;
5144     if (cast<FunctionDecl>(D)->getBody(Def))
5145       return MakeCXCursor(Def, TU);
5146     return clang_getNullCursor();
5147   }
5148
5149   case Decl::Var:
5150   case Decl::VarTemplateSpecialization:
5151   case Decl::VarTemplatePartialSpecialization: {
5152     // Ask the variable if it has a definition.
5153     if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
5154       return MakeCXCursor(Def, TU);
5155     return clang_getNullCursor();
5156   }
5157
5158   case Decl::FunctionTemplate: {
5159     const FunctionDecl *Def = nullptr;
5160     if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
5161       return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
5162     return clang_getNullCursor();
5163   }
5164
5165   case Decl::ClassTemplate: {
5166     if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
5167                                                             ->getDefinition())
5168       return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
5169                           TU);
5170     return clang_getNullCursor();
5171   }
5172
5173   case Decl::VarTemplate: {
5174     if (VarDecl *Def =
5175             cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
5176       return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
5177     return clang_getNullCursor();
5178   }
5179
5180   case Decl::Using:
5181     return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), 
5182                                        D->getLocation(), TU);
5183
5184   case Decl::UsingShadow:
5185     return clang_getCursorDefinition(
5186                        MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
5187                                     TU));
5188
5189   case Decl::ObjCMethod: {
5190     const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
5191     if (Method->isThisDeclarationADefinition())
5192       return C;
5193
5194     // Dig out the method definition in the associated
5195     // @implementation, if we have it.
5196     // FIXME: The ASTs should make finding the definition easier.
5197     if (const ObjCInterfaceDecl *Class
5198                        = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
5199       if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
5200         if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
5201                                                   Method->isInstanceMethod()))
5202           if (Def->isThisDeclarationADefinition())
5203             return MakeCXCursor(Def, TU);
5204
5205     return clang_getNullCursor();
5206   }
5207
5208   case Decl::ObjCCategory:
5209     if (ObjCCategoryImplDecl *Impl
5210                                = cast<ObjCCategoryDecl>(D)->getImplementation())
5211       return MakeCXCursor(Impl, TU);
5212     return clang_getNullCursor();
5213
5214   case Decl::ObjCProtocol:
5215     if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
5216       return MakeCXCursor(Def, TU);
5217     return clang_getNullCursor();
5218
5219   case Decl::ObjCInterface: {
5220     // There are two notions of a "definition" for an Objective-C
5221     // class: the interface and its implementation. When we resolved a
5222     // reference to an Objective-C class, produce the @interface as
5223     // the definition; when we were provided with the interface,
5224     // produce the @implementation as the definition.
5225     const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
5226     if (WasReference) {
5227       if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
5228         return MakeCXCursor(Def, TU);
5229     } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5230       return MakeCXCursor(Impl, TU);
5231     return clang_getNullCursor();
5232   }
5233
5234   case Decl::ObjCProperty:
5235     // FIXME: We don't really know where to find the
5236     // ObjCPropertyImplDecls that implement this property.
5237     return clang_getNullCursor();
5238
5239   case Decl::ObjCCompatibleAlias:
5240     if (const ObjCInterfaceDecl *Class
5241           = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
5242       if (const ObjCInterfaceDecl *Def = Class->getDefinition())
5243         return MakeCXCursor(Def, TU);
5244
5245     return clang_getNullCursor();
5246
5247   case Decl::Friend:
5248     if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
5249       return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5250     return clang_getNullCursor();
5251
5252   case Decl::FriendTemplate:
5253     if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
5254       return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
5255     return clang_getNullCursor();
5256   }
5257
5258   return clang_getNullCursor();
5259 }
5260
5261 unsigned clang_isCursorDefinition(CXCursor C) {
5262   if (!clang_isDeclaration(C.kind))
5263     return 0;
5264
5265   return clang_getCursorDefinition(C) == C;
5266 }
5267
5268 CXCursor clang_getCanonicalCursor(CXCursor C) {
5269   if (!clang_isDeclaration(C.kind))
5270     return C;
5271   
5272   if (const Decl *D = getCursorDecl(C)) {
5273     if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
5274       if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
5275         return MakeCXCursor(CatD, getCursorTU(C));
5276
5277     if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5278       if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
5279         return MakeCXCursor(IFD, getCursorTU(C));
5280
5281     return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
5282   }
5283   
5284   return C;
5285 }
5286
5287 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
5288   return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
5289 }
5290   
5291 unsigned clang_getNumOverloadedDecls(CXCursor C) {
5292   if (C.kind != CXCursor_OverloadedDeclRef)
5293     return 0;
5294   
5295   OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
5296   if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5297     return E->getNumDecls();
5298   
5299   if (OverloadedTemplateStorage *S
5300                               = Storage.dyn_cast<OverloadedTemplateStorage*>())
5301     return S->size();
5302   
5303   const Decl *D = Storage.get<const Decl *>();
5304   if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
5305     return Using->shadow_size();
5306   
5307   return 0;
5308 }
5309
5310 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
5311   if (cursor.kind != CXCursor_OverloadedDeclRef)
5312     return clang_getNullCursor();
5313
5314   if (index >= clang_getNumOverloadedDecls(cursor))
5315     return clang_getNullCursor();
5316   
5317   CXTranslationUnit TU = getCursorTU(cursor);
5318   OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
5319   if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5320     return MakeCXCursor(E->decls_begin()[index], TU);
5321   
5322   if (OverloadedTemplateStorage *S
5323                               = Storage.dyn_cast<OverloadedTemplateStorage*>())
5324     return MakeCXCursor(S->begin()[index], TU);
5325   
5326   const Decl *D = Storage.get<const Decl *>();
5327   if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
5328     // FIXME: This is, unfortunately, linear time.
5329     UsingDecl::shadow_iterator Pos = Using->shadow_begin();
5330     std::advance(Pos, index);
5331     return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
5332   }
5333   
5334   return clang_getNullCursor();
5335 }
5336   
5337 void clang_getDefinitionSpellingAndExtent(CXCursor C,
5338                                           const char **startBuf,
5339                                           const char **endBuf,
5340                                           unsigned *startLine,
5341                                           unsigned *startColumn,
5342                                           unsigned *endLine,
5343                                           unsigned *endColumn) {
5344   assert(getCursorDecl(C) && "CXCursor has null decl");
5345   const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
5346   CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
5347
5348   SourceManager &SM = FD->getASTContext().getSourceManager();
5349   *startBuf = SM.getCharacterData(Body->getLBracLoc());
5350   *endBuf = SM.getCharacterData(Body->getRBracLoc());
5351   *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
5352   *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
5353   *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
5354   *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
5355 }
5356
5357
5358 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
5359                                                 unsigned PieceIndex) {
5360   RefNamePieces Pieces;
5361   
5362   switch (C.kind) {
5363   case CXCursor_MemberRefExpr:
5364     if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
5365       Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
5366                            E->getQualifierLoc().getSourceRange());
5367     break;
5368   
5369   case CXCursor_DeclRefExpr:
5370     if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
5371       Pieces = buildPieces(NameFlags, false, E->getNameInfo(), 
5372                            E->getQualifierLoc().getSourceRange(),
5373                            E->getOptionalExplicitTemplateArgs());
5374     break;
5375     
5376   case CXCursor_CallExpr:
5377     if (const CXXOperatorCallExpr *OCE = 
5378         dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
5379       const Expr *Callee = OCE->getCallee();
5380       if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
5381         Callee = ICE->getSubExpr();
5382
5383       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
5384         Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
5385                              DRE->getQualifierLoc().getSourceRange());
5386     }
5387     break;
5388     
5389   default:
5390     break;
5391   }
5392
5393   if (Pieces.empty()) {
5394     if (PieceIndex == 0)
5395       return clang_getCursorExtent(C);
5396   } else if (PieceIndex < Pieces.size()) {
5397       SourceRange R = Pieces[PieceIndex];
5398       if (R.isValid())
5399         return cxloc::translateSourceRange(getCursorContext(C), R);
5400   }
5401   
5402   return clang_getNullRange();
5403 }
5404
5405 void clang_enableStackTraces(void) {
5406   llvm::sys::PrintStackTraceOnErrorSignal();
5407 }
5408
5409 void clang_executeOnThread(void (*fn)(void*), void *user_data,
5410                            unsigned stack_size) {
5411   llvm::llvm_execute_on_thread(fn, user_data, stack_size);
5412 }
5413
5414 } // end: extern "C"
5415
5416 //===----------------------------------------------------------------------===//
5417 // Token-based Operations.
5418 //===----------------------------------------------------------------------===//
5419
5420 /* CXToken layout:
5421  *   int_data[0]: a CXTokenKind
5422  *   int_data[1]: starting token location
5423  *   int_data[2]: token length
5424  *   int_data[3]: reserved
5425  *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
5426  *   otherwise unused.
5427  */
5428 extern "C" {
5429
5430 CXTokenKind clang_getTokenKind(CXToken CXTok) {
5431   return static_cast<CXTokenKind>(CXTok.int_data[0]);
5432 }
5433
5434 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
5435   switch (clang_getTokenKind(CXTok)) {
5436   case CXToken_Identifier:
5437   case CXToken_Keyword:
5438     // We know we have an IdentifierInfo*, so use that.
5439     return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
5440                             ->getNameStart());
5441
5442   case CXToken_Literal: {
5443     // We have stashed the starting pointer in the ptr_data field. Use it.
5444     const char *Text = static_cast<const char *>(CXTok.ptr_data);
5445     return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
5446   }
5447
5448   case CXToken_Punctuation:
5449   case CXToken_Comment:
5450     break;
5451   }
5452
5453   if (isNotUsableTU(TU)) {
5454     LOG_BAD_TU(TU);
5455     return cxstring::createEmpty();
5456   }
5457
5458   // We have to find the starting buffer pointer the hard way, by
5459   // deconstructing the source location.
5460   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5461   if (!CXXUnit)
5462     return cxstring::createEmpty();
5463
5464   SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
5465   std::pair<FileID, unsigned> LocInfo
5466     = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
5467   bool Invalid = false;
5468   StringRef Buffer
5469     = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
5470   if (Invalid)
5471     return cxstring::createEmpty();
5472
5473   return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
5474 }
5475
5476 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
5477   if (isNotUsableTU(TU)) {
5478     LOG_BAD_TU(TU);
5479     return clang_getNullLocation();
5480   }
5481
5482   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5483   if (!CXXUnit)
5484     return clang_getNullLocation();
5485
5486   return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
5487                         SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5488 }
5489
5490 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
5491   if (isNotUsableTU(TU)) {
5492     LOG_BAD_TU(TU);
5493     return clang_getNullRange();
5494   }
5495
5496   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5497   if (!CXXUnit)
5498     return clang_getNullRange();
5499
5500   return cxloc::translateSourceRange(CXXUnit->getASTContext(),
5501                         SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
5502 }
5503
5504 static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
5505                       SmallVectorImpl<CXToken> &CXTokens) {
5506   SourceManager &SourceMgr = CXXUnit->getSourceManager();
5507   std::pair<FileID, unsigned> BeginLocInfo
5508     = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
5509   std::pair<FileID, unsigned> EndLocInfo
5510     = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
5511
5512   // Cannot tokenize across files.
5513   if (BeginLocInfo.first != EndLocInfo.first)
5514     return;
5515
5516   // Create a lexer
5517   bool Invalid = false;
5518   StringRef Buffer
5519     = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5520   if (Invalid)
5521     return;
5522   
5523   Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5524             CXXUnit->getASTContext().getLangOpts(),
5525             Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
5526   Lex.SetCommentRetentionState(true);
5527
5528   // Lex tokens until we hit the end of the range.
5529   const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
5530   Token Tok;
5531   bool previousWasAt = false;
5532   do {
5533     // Lex the next token
5534     Lex.LexFromRawLexer(Tok);
5535     if (Tok.is(tok::eof))
5536       break;
5537
5538     // Initialize the CXToken.
5539     CXToken CXTok;
5540
5541     //   - Common fields
5542     CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
5543     CXTok.int_data[2] = Tok.getLength();
5544     CXTok.int_data[3] = 0;
5545
5546     //   - Kind-specific fields
5547     if (Tok.isLiteral()) {
5548       CXTok.int_data[0] = CXToken_Literal;
5549       CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
5550     } else if (Tok.is(tok::raw_identifier)) {
5551       // Lookup the identifier to determine whether we have a keyword.
5552       IdentifierInfo *II
5553         = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
5554
5555       if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
5556         CXTok.int_data[0] = CXToken_Keyword;
5557       }
5558       else {
5559         CXTok.int_data[0] = Tok.is(tok::identifier)
5560           ? CXToken_Identifier
5561           : CXToken_Keyword;
5562       }
5563       CXTok.ptr_data = II;
5564     } else if (Tok.is(tok::comment)) {
5565       CXTok.int_data[0] = CXToken_Comment;
5566       CXTok.ptr_data = nullptr;
5567     } else {
5568       CXTok.int_data[0] = CXToken_Punctuation;
5569       CXTok.ptr_data = nullptr;
5570     }
5571     CXTokens.push_back(CXTok);
5572     previousWasAt = Tok.is(tok::at);
5573   } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
5574 }
5575
5576 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
5577                     CXToken **Tokens, unsigned *NumTokens) {
5578   LOG_FUNC_SECTION {
5579     *Log << TU << ' ' << Range;
5580   }
5581
5582   if (Tokens)
5583     *Tokens = nullptr;
5584   if (NumTokens)
5585     *NumTokens = 0;
5586
5587   if (isNotUsableTU(TU)) {
5588     LOG_BAD_TU(TU);
5589     return;
5590   }
5591
5592   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5593   if (!CXXUnit || !Tokens || !NumTokens)
5594     return;
5595
5596   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5597   
5598   SourceRange R = cxloc::translateCXSourceRange(Range);
5599   if (R.isInvalid())
5600     return;
5601
5602   SmallVector<CXToken, 32> CXTokens;
5603   getTokens(CXXUnit, R, CXTokens);
5604
5605   if (CXTokens.empty())
5606     return;
5607
5608   *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
5609   memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
5610   *NumTokens = CXTokens.size();
5611 }
5612
5613 void clang_disposeTokens(CXTranslationUnit TU,
5614                          CXToken *Tokens, unsigned NumTokens) {
5615   free(Tokens);
5616 }
5617
5618 } // end: extern "C"
5619
5620 //===----------------------------------------------------------------------===//
5621 // Token annotation APIs.
5622 //===----------------------------------------------------------------------===//
5623
5624 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5625                                                      CXCursor parent,
5626                                                      CXClientData client_data);
5627 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5628                                               CXClientData client_data);
5629
5630 namespace {
5631 class AnnotateTokensWorker {
5632   CXToken *Tokens;
5633   CXCursor *Cursors;
5634   unsigned NumTokens;
5635   unsigned TokIdx;
5636   unsigned PreprocessingTokIdx;
5637   CursorVisitor AnnotateVis;
5638   SourceManager &SrcMgr;
5639   bool HasContextSensitiveKeywords;
5640
5641   struct PostChildrenInfo {
5642     CXCursor Cursor;
5643     SourceRange CursorRange;
5644     unsigned BeforeReachingCursorIdx;
5645     unsigned BeforeChildrenTokenIdx;
5646   };
5647   SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
5648
5649   CXToken &getTok(unsigned Idx) {
5650     assert(Idx < NumTokens);
5651     return Tokens[Idx];
5652   }
5653   const CXToken &getTok(unsigned Idx) const {
5654     assert(Idx < NumTokens);
5655     return Tokens[Idx];
5656   }
5657   bool MoreTokens() const { return TokIdx < NumTokens; }
5658   unsigned NextToken() const { return TokIdx; }
5659   void AdvanceToken() { ++TokIdx; }
5660   SourceLocation GetTokenLoc(unsigned tokI) {
5661     return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
5662   }
5663   bool isFunctionMacroToken(unsigned tokI) const {
5664     return getTok(tokI).int_data[3] != 0;
5665   }
5666   SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
5667     return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
5668   }
5669
5670   void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
5671   bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
5672                                              SourceRange);
5673
5674 public:
5675   AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
5676                        CXTranslationUnit TU, SourceRange RegionOfInterest)
5677     : Tokens(tokens), Cursors(cursors),
5678       NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
5679       AnnotateVis(TU,
5680                   AnnotateTokensVisitor, this,
5681                   /*VisitPreprocessorLast=*/true,
5682                   /*VisitIncludedEntities=*/false,
5683                   RegionOfInterest,
5684                   /*VisitDeclsOnly=*/false,
5685                   AnnotateTokensPostChildrenVisitor),
5686       SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
5687       HasContextSensitiveKeywords(false) { }
5688
5689   void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
5690   enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
5691   bool postVisitChildren(CXCursor cursor);
5692   void AnnotateTokens();
5693   
5694   /// \brief Determine whether the annotator saw any cursors that have 
5695   /// context-sensitive keywords.
5696   bool hasContextSensitiveKeywords() const {
5697     return HasContextSensitiveKeywords;
5698   }
5699
5700   ~AnnotateTokensWorker() {
5701     assert(PostChildrenInfos.empty());
5702   }
5703 };
5704 }
5705
5706 void AnnotateTokensWorker::AnnotateTokens() {
5707   // Walk the AST within the region of interest, annotating tokens
5708   // along the way.
5709   AnnotateVis.visitFileRegion();
5710 }
5711
5712 static inline void updateCursorAnnotation(CXCursor &Cursor,
5713                                           const CXCursor &updateC) {
5714   if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
5715     return;
5716   Cursor = updateC;
5717 }
5718
5719 /// \brief It annotates and advances tokens with a cursor until the comparison
5720 //// between the cursor location and the source range is the same as
5721 /// \arg compResult.
5722 ///
5723 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
5724 /// Pass RangeOverlap to annotate tokens inside a range.
5725 void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
5726                                                RangeComparisonResult compResult,
5727                                                SourceRange range) {
5728   while (MoreTokens()) {
5729     const unsigned I = NextToken();
5730     if (isFunctionMacroToken(I))
5731       if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
5732         return;
5733
5734     SourceLocation TokLoc = GetTokenLoc(I);
5735     if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5736       updateCursorAnnotation(Cursors[I], updateC);
5737       AdvanceToken();
5738       continue;
5739     }
5740     break;
5741   }
5742 }
5743
5744 /// \brief Special annotation handling for macro argument tokens.
5745 /// \returns true if it advanced beyond all macro tokens, false otherwise.
5746 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
5747                                                CXCursor updateC,
5748                                                RangeComparisonResult compResult,
5749                                                SourceRange range) {
5750   assert(MoreTokens());
5751   assert(isFunctionMacroToken(NextToken()) &&
5752          "Should be called only for macro arg tokens");
5753
5754   // This works differently than annotateAndAdvanceTokens; because expanded
5755   // macro arguments can have arbitrary translation-unit source order, we do not
5756   // advance the token index one by one until a token fails the range test.
5757   // We only advance once past all of the macro arg tokens if all of them
5758   // pass the range test. If one of them fails we keep the token index pointing
5759   // at the start of the macro arg tokens so that the failing token will be
5760   // annotated by a subsequent annotation try.
5761
5762   bool atLeastOneCompFail = false;
5763   
5764   unsigned I = NextToken();
5765   for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
5766     SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
5767     if (TokLoc.isFileID())
5768       continue; // not macro arg token, it's parens or comma.
5769     if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5770       if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
5771         Cursors[I] = updateC;
5772     } else
5773       atLeastOneCompFail = true;
5774   }
5775
5776   if (atLeastOneCompFail)
5777     return false;
5778
5779   TokIdx = I; // All of the tokens were handled, advance beyond all of them.
5780   return true;
5781 }
5782
5783 enum CXChildVisitResult
5784 AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {  
5785   SourceRange cursorRange = getRawCursorExtent(cursor);
5786   if (cursorRange.isInvalid())
5787     return CXChildVisit_Recurse;
5788       
5789   if (!HasContextSensitiveKeywords) {
5790     // Objective-C properties can have context-sensitive keywords.
5791     if (cursor.kind == CXCursor_ObjCPropertyDecl) {
5792       if (const ObjCPropertyDecl *Property
5793                   = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
5794         HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
5795     }
5796     // Objective-C methods can have context-sensitive keywords.
5797     else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
5798              cursor.kind == CXCursor_ObjCClassMethodDecl) {
5799       if (const ObjCMethodDecl *Method
5800             = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5801         if (Method->getObjCDeclQualifier())
5802           HasContextSensitiveKeywords = true;
5803         else {
5804           for (const auto *P : Method->params()) {
5805             if (P->getObjCDeclQualifier()) {
5806               HasContextSensitiveKeywords = true;
5807               break;
5808             }
5809           }
5810         }
5811       }
5812     }    
5813     // C++ methods can have context-sensitive keywords.
5814     else if (cursor.kind == CXCursor_CXXMethod) {
5815       if (const CXXMethodDecl *Method
5816                   = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5817         if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5818           HasContextSensitiveKeywords = true;
5819       }
5820     }
5821     // C++ classes can have context-sensitive keywords.
5822     else if (cursor.kind == CXCursor_StructDecl ||
5823              cursor.kind == CXCursor_ClassDecl ||
5824              cursor.kind == CXCursor_ClassTemplate ||
5825              cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5826       if (const Decl *D = getCursorDecl(cursor))
5827         if (D->hasAttr<FinalAttr>())
5828           HasContextSensitiveKeywords = true;
5829     }
5830   }
5831
5832   // Don't override a property annotation with its getter/setter method.
5833   if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
5834       parent.kind == CXCursor_ObjCPropertyDecl)
5835     return CXChildVisit_Continue;
5836   
5837   if (clang_isPreprocessing(cursor.kind)) {    
5838     // Items in the preprocessing record are kept separate from items in
5839     // declarations, so we keep a separate token index.
5840     unsigned SavedTokIdx = TokIdx;
5841     TokIdx = PreprocessingTokIdx;
5842
5843     // Skip tokens up until we catch up to the beginning of the preprocessing
5844     // entry.
5845     while (MoreTokens()) {
5846       const unsigned I = NextToken();
5847       SourceLocation TokLoc = GetTokenLoc(I);
5848       switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5849       case RangeBefore:
5850         AdvanceToken();
5851         continue;
5852       case RangeAfter:
5853       case RangeOverlap:
5854         break;
5855       }
5856       break;
5857     }
5858     
5859     // Look at all of the tokens within this range.
5860     while (MoreTokens()) {
5861       const unsigned I = NextToken();
5862       SourceLocation TokLoc = GetTokenLoc(I);
5863       switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5864       case RangeBefore:
5865         llvm_unreachable("Infeasible");
5866       case RangeAfter:
5867         break;
5868       case RangeOverlap:
5869         // For macro expansions, just note where the beginning of the macro
5870         // expansion occurs.
5871         if (cursor.kind == CXCursor_MacroExpansion) {
5872           if (TokLoc == cursorRange.getBegin())
5873             Cursors[I] = cursor;
5874           AdvanceToken();
5875           break;
5876         }
5877         // We may have already annotated macro names inside macro definitions.
5878         if (Cursors[I].kind != CXCursor_MacroExpansion)
5879           Cursors[I] = cursor;
5880         AdvanceToken();
5881         continue;
5882       }
5883       break;
5884     }
5885
5886     // Save the preprocessing token index; restore the non-preprocessing
5887     // token index.
5888     PreprocessingTokIdx = TokIdx;
5889     TokIdx = SavedTokIdx;
5890     return CXChildVisit_Recurse;
5891   }
5892
5893   if (cursorRange.isInvalid())
5894     return CXChildVisit_Continue;
5895
5896   unsigned BeforeReachingCursorIdx = NextToken();
5897   const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5898   const enum CXCursorKind K = clang_getCursorKind(parent);
5899   const CXCursor updateC =
5900     (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
5901      // Attributes are annotated out-of-order, skip tokens until we reach it.
5902      clang_isAttribute(cursor.kind))
5903      ? clang_getNullCursor() : parent;
5904
5905   annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
5906
5907   // Avoid having the cursor of an expression "overwrite" the annotation of the
5908   // variable declaration that it belongs to.
5909   // This can happen for C++ constructor expressions whose range generally
5910   // include the variable declaration, e.g.:
5911   //  MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5912   if (clang_isExpression(cursorK) && MoreTokens()) {
5913     const Expr *E = getCursorExpr(cursor);
5914     if (const Decl *D = getCursorParentDecl(cursor)) {
5915       const unsigned I = NextToken();
5916       if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5917           E->getLocStart() == D->getLocation() &&
5918           E->getLocStart() == GetTokenLoc(I)) {
5919         updateCursorAnnotation(Cursors[I], updateC);
5920         AdvanceToken();
5921       }
5922     }
5923   }
5924
5925   // Before recursing into the children keep some state that we are going
5926   // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
5927   // extra work after the child nodes are visited.
5928   // Note that we don't call VisitChildren here to avoid traversing statements
5929   // code-recursively which can blow the stack.
5930
5931   PostChildrenInfo Info;
5932   Info.Cursor = cursor;
5933   Info.CursorRange = cursorRange;
5934   Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
5935   Info.BeforeChildrenTokenIdx = NextToken();
5936   PostChildrenInfos.push_back(Info);
5937
5938   return CXChildVisit_Recurse;
5939 }
5940
5941 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
5942   if (PostChildrenInfos.empty())
5943     return false;
5944   const PostChildrenInfo &Info = PostChildrenInfos.back();
5945   if (!clang_equalCursors(Info.Cursor, cursor))
5946     return false;
5947
5948   const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
5949   const unsigned AfterChildren = NextToken();
5950   SourceRange cursorRange = Info.CursorRange;
5951
5952   // Scan the tokens that are at the end of the cursor, but are not captured
5953   // but the child cursors.
5954   annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
5955
5956   // Scan the tokens that are at the beginning of the cursor, but are not
5957   // capture by the child cursors.
5958   for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5959     if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5960       break;
5961
5962     Cursors[I] = cursor;
5963   }
5964
5965   // Attributes are annotated out-of-order, rewind TokIdx to when we first
5966   // encountered the attribute cursor.
5967   if (clang_isAttribute(cursor.kind))
5968     TokIdx = Info.BeforeReachingCursorIdx;
5969
5970   PostChildrenInfos.pop_back();
5971   return false;
5972 }
5973
5974 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5975                                                      CXCursor parent,
5976                                                      CXClientData client_data) {
5977   return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5978 }
5979
5980 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5981                                               CXClientData client_data) {
5982   return static_cast<AnnotateTokensWorker*>(client_data)->
5983                                                       postVisitChildren(cursor);
5984 }
5985
5986 namespace {
5987
5988 /// \brief Uses the macro expansions in the preprocessing record to find
5989 /// and mark tokens that are macro arguments. This info is used by the
5990 /// AnnotateTokensWorker.
5991 class MarkMacroArgTokensVisitor {
5992   SourceManager &SM;
5993   CXToken *Tokens;
5994   unsigned NumTokens;
5995   unsigned CurIdx;
5996   
5997 public:
5998   MarkMacroArgTokensVisitor(SourceManager &SM,
5999                             CXToken *tokens, unsigned numTokens)
6000     : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
6001
6002   CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
6003     if (cursor.kind != CXCursor_MacroExpansion)
6004       return CXChildVisit_Continue;
6005
6006     SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
6007     if (macroRange.getBegin() == macroRange.getEnd())
6008       return CXChildVisit_Continue; // it's not a function macro.
6009
6010     for (; CurIdx < NumTokens; ++CurIdx) {
6011       if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
6012                                         macroRange.getBegin()))
6013         break;
6014     }
6015     
6016     if (CurIdx == NumTokens)
6017       return CXChildVisit_Break;
6018
6019     for (; CurIdx < NumTokens; ++CurIdx) {
6020       SourceLocation tokLoc = getTokenLoc(CurIdx);
6021       if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
6022         break;
6023
6024       setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
6025     }
6026
6027     if (CurIdx == NumTokens)
6028       return CXChildVisit_Break;
6029
6030     return CXChildVisit_Continue;
6031   }
6032
6033 private:
6034   CXToken &getTok(unsigned Idx) {
6035     assert(Idx < NumTokens);
6036     return Tokens[Idx];
6037   }
6038   const CXToken &getTok(unsigned Idx) const {
6039     assert(Idx < NumTokens);
6040     return Tokens[Idx];
6041   }
6042
6043   SourceLocation getTokenLoc(unsigned tokI) {
6044     return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6045   }
6046
6047   void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
6048     // The third field is reserved and currently not used. Use it here
6049     // to mark macro arg expanded tokens with their expanded locations.
6050     getTok(tokI).int_data[3] = loc.getRawEncoding();
6051   }
6052 };
6053
6054 } // end anonymous namespace
6055
6056 static CXChildVisitResult
6057 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
6058                                   CXClientData client_data) {
6059   return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
6060                                                                      parent);
6061 }
6062
6063 /// \brief Used by \c annotatePreprocessorTokens.
6064 /// \returns true if lexing was finished, false otherwise.
6065 static bool lexNext(Lexer &Lex, Token &Tok,
6066                    unsigned &NextIdx, unsigned NumTokens) {
6067   if (NextIdx >= NumTokens)
6068     return true;
6069
6070   ++NextIdx;
6071   Lex.LexFromRawLexer(Tok);
6072   if (Tok.is(tok::eof))
6073     return true;
6074
6075   return false;
6076 }
6077
6078 static void annotatePreprocessorTokens(CXTranslationUnit TU,
6079                                        SourceRange RegionOfInterest,
6080                                        CXCursor *Cursors,
6081                                        CXToken *Tokens,
6082                                        unsigned NumTokens) {
6083   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6084
6085   Preprocessor &PP = CXXUnit->getPreprocessor();
6086   SourceManager &SourceMgr = CXXUnit->getSourceManager();
6087   std::pair<FileID, unsigned> BeginLocInfo
6088     = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
6089   std::pair<FileID, unsigned> EndLocInfo
6090     = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
6091
6092   if (BeginLocInfo.first != EndLocInfo.first)
6093     return;
6094
6095   StringRef Buffer;
6096   bool Invalid = false;
6097   Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6098   if (Buffer.empty() || Invalid)
6099     return;
6100
6101   Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6102             CXXUnit->getASTContext().getLangOpts(),
6103             Buffer.begin(), Buffer.data() + BeginLocInfo.second,
6104             Buffer.end());
6105   Lex.SetCommentRetentionState(true);
6106   
6107   unsigned NextIdx = 0;
6108   // Lex tokens in raw mode until we hit the end of the range, to avoid
6109   // entering #includes or expanding macros.
6110   while (true) {
6111     Token Tok;
6112     if (lexNext(Lex, Tok, NextIdx, NumTokens))
6113       break;
6114     unsigned TokIdx = NextIdx-1;
6115     assert(Tok.getLocation() ==
6116              SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
6117     
6118   reprocess:
6119     if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
6120       // We have found a preprocessing directive. Annotate the tokens
6121       // appropriately.
6122       //
6123       // FIXME: Some simple tests here could identify macro definitions and
6124       // #undefs, to provide specific cursor kinds for those.
6125
6126       SourceLocation BeginLoc = Tok.getLocation();
6127       if (lexNext(Lex, Tok, NextIdx, NumTokens))
6128         break;
6129
6130       MacroInfo *MI = nullptr;
6131       if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
6132         if (lexNext(Lex, Tok, NextIdx, NumTokens))
6133           break;
6134
6135         if (Tok.is(tok::raw_identifier)) {
6136           IdentifierInfo &II =
6137               PP.getIdentifierTable().get(Tok.getRawIdentifier());
6138           SourceLocation MappedTokLoc =
6139               CXXUnit->mapLocationToPreamble(Tok.getLocation());
6140           MI = getMacroInfo(II, MappedTokLoc, TU);
6141         }
6142       }
6143
6144       bool finished = false;
6145       do {
6146         if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
6147           finished = true;
6148           break;
6149         }
6150         // If we are in a macro definition, check if the token was ever a
6151         // macro name and annotate it if that's the case.
6152         if (MI) {
6153           SourceLocation SaveLoc = Tok.getLocation();
6154           Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
6155           MacroDefinitionRecord *MacroDef =
6156               checkForMacroInMacroDefinition(MI, Tok, TU);
6157           Tok.setLocation(SaveLoc);
6158           if (MacroDef)
6159             Cursors[NextIdx - 1] =
6160                 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
6161         }
6162       } while (!Tok.isAtStartOfLine());
6163
6164       unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
6165       assert(TokIdx <= LastIdx);
6166       SourceLocation EndLoc =
6167           SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
6168       CXCursor Cursor =
6169           MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
6170
6171       for (; TokIdx <= LastIdx; ++TokIdx)
6172         updateCursorAnnotation(Cursors[TokIdx], Cursor);
6173       
6174       if (finished)
6175         break;
6176       goto reprocess;
6177     }
6178   }
6179 }
6180
6181 // This gets run a separate thread to avoid stack blowout.
6182 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
6183                                      CXToken *Tokens, unsigned NumTokens,
6184                                      CXCursor *Cursors) {
6185   CIndexer *CXXIdx = TU->CIdx;
6186   if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
6187     setThreadBackgroundPriority();
6188
6189   // Determine the region of interest, which contains all of the tokens.
6190   SourceRange RegionOfInterest;
6191   RegionOfInterest.setBegin(
6192     cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
6193   RegionOfInterest.setEnd(
6194     cxloc::translateSourceLocation(clang_getTokenLocation(TU,
6195                                                          Tokens[NumTokens-1])));
6196
6197   // Relex the tokens within the source range to look for preprocessing
6198   // directives.
6199   annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
6200
6201   // If begin location points inside a macro argument, set it to the expansion
6202   // location so we can have the full context when annotating semantically.
6203   {
6204     SourceManager &SM = CXXUnit->getSourceManager();
6205     SourceLocation Loc =
6206         SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
6207     if (Loc.isMacroID())
6208       RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
6209   }
6210
6211   if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
6212     // Search and mark tokens that are macro argument expansions.
6213     MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
6214                                       Tokens, NumTokens);
6215     CursorVisitor MacroArgMarker(TU,
6216                                  MarkMacroArgTokensVisitorDelegate, &Visitor,
6217                                  /*VisitPreprocessorLast=*/true,
6218                                  /*VisitIncludedEntities=*/false,
6219                                  RegionOfInterest);
6220     MacroArgMarker.visitPreprocessedEntitiesInRegion();
6221   }
6222   
6223   // Annotate all of the source locations in the region of interest that map to
6224   // a specific cursor.
6225   AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
6226   
6227   // FIXME: We use a ridiculous stack size here because the data-recursion
6228   // algorithm uses a large stack frame than the non-data recursive version,
6229   // and AnnotationTokensWorker currently transforms the data-recursion
6230   // algorithm back into a traditional recursion by explicitly calling
6231   // VisitChildren().  We will need to remove this explicit recursive call.
6232   W.AnnotateTokens();
6233
6234   // If we ran into any entities that involve context-sensitive keywords,
6235   // take another pass through the tokens to mark them as such.
6236   if (W.hasContextSensitiveKeywords()) {
6237     for (unsigned I = 0; I != NumTokens; ++I) {
6238       if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
6239         continue;
6240       
6241       if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
6242         IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6243         if (const ObjCPropertyDecl *Property
6244             = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
6245           if (Property->getPropertyAttributesAsWritten() != 0 &&
6246               llvm::StringSwitch<bool>(II->getName())
6247               .Case("readonly", true)
6248               .Case("assign", true)
6249               .Case("unsafe_unretained", true)
6250               .Case("readwrite", true)
6251               .Case("retain", true)
6252               .Case("copy", true)
6253               .Case("nonatomic", true)
6254               .Case("atomic", true)
6255               .Case("getter", true)
6256               .Case("setter", true)
6257               .Case("strong", true)
6258               .Case("weak", true)
6259               .Default(false))
6260             Tokens[I].int_data[0] = CXToken_Keyword;
6261         }
6262         continue;
6263       }
6264       
6265       if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
6266           Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
6267         IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
6268         if (llvm::StringSwitch<bool>(II->getName())
6269             .Case("in", true)
6270             .Case("out", true)
6271             .Case("inout", true)
6272             .Case("oneway", true)
6273             .Case("bycopy", true)
6274             .Case("byref", true)
6275             .Default(false))
6276           Tokens[I].int_data[0] = CXToken_Keyword;
6277         continue;
6278       }
6279
6280       if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
6281           Cursors[I].kind == CXCursor_CXXOverrideAttr) {
6282         Tokens[I].int_data[0] = CXToken_Keyword;
6283         continue;
6284       }
6285     }
6286   }
6287 }
6288
6289 extern "C" {
6290
6291 void clang_annotateTokens(CXTranslationUnit TU,
6292                           CXToken *Tokens, unsigned NumTokens,
6293                           CXCursor *Cursors) {
6294   if (isNotUsableTU(TU)) {
6295     LOG_BAD_TU(TU);
6296     return;
6297   }
6298   if (NumTokens == 0 || !Tokens || !Cursors) {
6299     LOG_FUNC_SECTION { *Log << "<null input>"; }
6300     return;
6301   }
6302
6303   LOG_FUNC_SECTION {
6304     *Log << TU << ' ';
6305     CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
6306     CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
6307     *Log << clang_getRange(bloc, eloc);
6308   }
6309
6310   // Any token we don't specifically annotate will have a NULL cursor.
6311   CXCursor C = clang_getNullCursor();
6312   for (unsigned I = 0; I != NumTokens; ++I)
6313     Cursors[I] = C;
6314
6315   ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6316   if (!CXXUnit)
6317     return;
6318
6319   ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6320
6321   auto AnnotateTokensImpl = [=]() {
6322     clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
6323   };
6324   llvm::CrashRecoveryContext CRC;
6325   if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
6326     fprintf(stderr, "libclang: crash detected while annotating tokens\n");
6327   }
6328 }
6329
6330 } // end: extern "C"
6331
6332 //===----------------------------------------------------------------------===//
6333 // Operations for querying linkage of a cursor.
6334 //===----------------------------------------------------------------------===//
6335
6336 extern "C" {
6337 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
6338   if (!clang_isDeclaration(cursor.kind))
6339     return CXLinkage_Invalid;
6340
6341   const Decl *D = cxcursor::getCursorDecl(cursor);
6342   if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
6343     switch (ND->getLinkageInternal()) {
6344       case NoLinkage:
6345       case VisibleNoLinkage: return CXLinkage_NoLinkage;
6346       case InternalLinkage: return CXLinkage_Internal;
6347       case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
6348       case ExternalLinkage: return CXLinkage_External;
6349     };
6350
6351   return CXLinkage_Invalid;
6352 }
6353 } // end: extern "C"
6354
6355 //===----------------------------------------------------------------------===//
6356 // Operations for querying language of a cursor.
6357 //===----------------------------------------------------------------------===//
6358
6359 static CXLanguageKind getDeclLanguage(const Decl *D) {
6360   if (!D)
6361     return CXLanguage_C;
6362
6363   switch (D->getKind()) {
6364     default:
6365       break;
6366     case Decl::ImplicitParam:
6367     case Decl::ObjCAtDefsField:
6368     case Decl::ObjCCategory:
6369     case Decl::ObjCCategoryImpl:
6370     case Decl::ObjCCompatibleAlias:
6371     case Decl::ObjCImplementation:
6372     case Decl::ObjCInterface:
6373     case Decl::ObjCIvar:
6374     case Decl::ObjCMethod:
6375     case Decl::ObjCProperty:
6376     case Decl::ObjCPropertyImpl:
6377     case Decl::ObjCProtocol:
6378     case Decl::ObjCTypeParam:
6379       return CXLanguage_ObjC;
6380     case Decl::CXXConstructor:
6381     case Decl::CXXConversion:
6382     case Decl::CXXDestructor:
6383     case Decl::CXXMethod:
6384     case Decl::CXXRecord:
6385     case Decl::ClassTemplate:
6386     case Decl::ClassTemplatePartialSpecialization:
6387     case Decl::ClassTemplateSpecialization:
6388     case Decl::Friend:
6389     case Decl::FriendTemplate:
6390     case Decl::FunctionTemplate:
6391     case Decl::LinkageSpec:
6392     case Decl::Namespace:
6393     case Decl::NamespaceAlias:
6394     case Decl::NonTypeTemplateParm:
6395     case Decl::StaticAssert:
6396     case Decl::TemplateTemplateParm:
6397     case Decl::TemplateTypeParm:
6398     case Decl::UnresolvedUsingTypename:
6399     case Decl::UnresolvedUsingValue:
6400     case Decl::Using:
6401     case Decl::UsingDirective:
6402     case Decl::UsingShadow:
6403       return CXLanguage_CPlusPlus;
6404   }
6405
6406   return CXLanguage_C;
6407 }
6408
6409 extern "C" {
6410
6411 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
6412   if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
6413     return CXAvailability_Available;
6414   
6415   switch (D->getAvailability()) {
6416   case AR_Available:
6417   case AR_NotYetIntroduced:
6418     if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
6419       return getCursorAvailabilityForDecl(
6420           cast<Decl>(EnumConst->getDeclContext()));
6421     return CXAvailability_Available;
6422
6423   case AR_Deprecated:
6424     return CXAvailability_Deprecated;
6425
6426   case AR_Unavailable:
6427     return CXAvailability_NotAvailable;
6428   }
6429
6430   llvm_unreachable("Unknown availability kind!");
6431 }
6432
6433 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
6434   if (clang_isDeclaration(cursor.kind))
6435     if (const Decl *D = cxcursor::getCursorDecl(cursor))
6436       return getCursorAvailabilityForDecl(D);
6437
6438   return CXAvailability_Available;
6439 }
6440
6441 static CXVersion convertVersion(VersionTuple In) {
6442   CXVersion Out = { -1, -1, -1 };
6443   if (In.empty())
6444     return Out;
6445
6446   Out.Major = In.getMajor();
6447   
6448   Optional<unsigned> Minor = In.getMinor();
6449   if (Minor.hasValue())
6450     Out.Minor = *Minor;
6451   else
6452     return Out;
6453
6454   Optional<unsigned> Subminor = In.getSubminor();
6455   if (Subminor.hasValue())
6456     Out.Subminor = *Subminor;
6457   
6458   return Out;
6459 }
6460
6461 static int getCursorPlatformAvailabilityForDecl(const Decl *D,
6462                                                 int *always_deprecated,
6463                                                 CXString *deprecated_message,
6464                                                 int *always_unavailable,
6465                                                 CXString *unavailable_message,
6466                                            CXPlatformAvailability *availability,
6467                                                 int availability_size) {
6468   bool HadAvailAttr = false;
6469   int N = 0;
6470   for (auto A : D->attrs()) {
6471     if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
6472       HadAvailAttr = true;
6473       if (always_deprecated)
6474         *always_deprecated = 1;
6475       if (deprecated_message) {
6476         clang_disposeString(*deprecated_message);
6477         *deprecated_message = cxstring::createDup(Deprecated->getMessage());
6478       }
6479       continue;
6480     }
6481     
6482     if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
6483       HadAvailAttr = true;
6484       if (always_unavailable)
6485         *always_unavailable = 1;
6486       if (unavailable_message) {
6487         clang_disposeString(*unavailable_message);
6488         *unavailable_message = cxstring::createDup(Unavailable->getMessage());
6489       }
6490       continue;
6491     }
6492     
6493     if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
6494       HadAvailAttr = true;
6495       if (N < availability_size) {
6496         availability[N].Platform
6497           = cxstring::createDup(Avail->getPlatform()->getName());
6498         availability[N].Introduced = convertVersion(Avail->getIntroduced());
6499         availability[N].Deprecated = convertVersion(Avail->getDeprecated());
6500         availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
6501         availability[N].Unavailable = Avail->getUnavailable();
6502         availability[N].Message = cxstring::createDup(Avail->getMessage());
6503       }
6504       ++N;
6505     }
6506   }
6507
6508   if (!HadAvailAttr)
6509     if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
6510       return getCursorPlatformAvailabilityForDecl(
6511                                         cast<Decl>(EnumConst->getDeclContext()),
6512                                                   always_deprecated,
6513                                                   deprecated_message,
6514                                                   always_unavailable,
6515                                                   unavailable_message,
6516                                                   availability,
6517                                                   availability_size);
6518   
6519   return N;
6520 }
6521
6522 int clang_getCursorPlatformAvailability(CXCursor cursor,
6523                                         int *always_deprecated,
6524                                         CXString *deprecated_message,
6525                                         int *always_unavailable,
6526                                         CXString *unavailable_message,
6527                                         CXPlatformAvailability *availability,
6528                                         int availability_size) {
6529   if (always_deprecated)
6530     *always_deprecated = 0;
6531   if (deprecated_message)
6532     *deprecated_message = cxstring::createEmpty();
6533   if (always_unavailable)
6534     *always_unavailable = 0;
6535   if (unavailable_message)
6536     *unavailable_message = cxstring::createEmpty();
6537
6538   if (!clang_isDeclaration(cursor.kind))
6539     return 0;
6540
6541   const Decl *D = cxcursor::getCursorDecl(cursor);
6542   if (!D)
6543     return 0;
6544
6545   return getCursorPlatformAvailabilityForDecl(D, always_deprecated,
6546                                               deprecated_message,
6547                                               always_unavailable,
6548                                               unavailable_message,
6549                                               availability,
6550                                               availability_size);
6551 }
6552   
6553 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
6554   clang_disposeString(availability->Platform);
6555   clang_disposeString(availability->Message);
6556 }
6557
6558 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
6559   if (clang_isDeclaration(cursor.kind))
6560     return getDeclLanguage(cxcursor::getCursorDecl(cursor));
6561
6562   return CXLanguage_Invalid;
6563 }
6564
6565  /// \brief If the given cursor is the "templated" declaration
6566  /// descibing a class or function template, return the class or
6567  /// function template.
6568 static const Decl *maybeGetTemplateCursor(const Decl *D) {
6569   if (!D)
6570     return nullptr;
6571
6572   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6573     if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
6574       return FunTmpl;
6575
6576   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6577     if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
6578       return ClassTmpl;
6579
6580   return D;
6581 }
6582
6583
6584 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
6585   StorageClass sc = SC_None;
6586   const Decl *D = getCursorDecl(C);
6587   if (D) {
6588     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6589       sc = FD->getStorageClass();
6590     } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6591       sc = VD->getStorageClass();
6592     } else {
6593       return CX_SC_Invalid;
6594     }
6595   } else {
6596     return CX_SC_Invalid;
6597   }
6598   switch (sc) {
6599   case SC_None:
6600     return CX_SC_None;
6601   case SC_Extern:
6602     return CX_SC_Extern;
6603   case SC_Static:
6604     return CX_SC_Static;
6605   case SC_PrivateExtern:
6606     return CX_SC_PrivateExtern;
6607   case SC_OpenCLWorkGroupLocal:
6608     return CX_SC_OpenCLWorkGroupLocal;
6609   case SC_Auto:
6610     return CX_SC_Auto;
6611   case SC_Register:
6612     return CX_SC_Register;
6613   }
6614   llvm_unreachable("Unhandled storage class!");
6615 }
6616
6617 CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
6618   if (clang_isDeclaration(cursor.kind)) {
6619     if (const Decl *D = getCursorDecl(cursor)) {
6620       const DeclContext *DC = D->getDeclContext();
6621       if (!DC)
6622         return clang_getNullCursor();
6623
6624       return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 
6625                           getCursorTU(cursor));
6626     }
6627   }
6628   
6629   if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
6630     if (const Decl *D = getCursorDecl(cursor))
6631       return MakeCXCursor(D, getCursorTU(cursor));
6632   }
6633   
6634   return clang_getNullCursor();
6635 }
6636
6637 CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
6638   if (clang_isDeclaration(cursor.kind)) {
6639     if (const Decl *D = getCursorDecl(cursor)) {
6640       const DeclContext *DC = D->getLexicalDeclContext();
6641       if (!DC)
6642         return clang_getNullCursor();
6643
6644       return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 
6645                           getCursorTU(cursor));
6646     }
6647   }
6648
6649   // FIXME: Note that we can't easily compute the lexical context of a 
6650   // statement or expression, so we return nothing.
6651   return clang_getNullCursor();
6652 }
6653
6654 CXFile clang_getIncludedFile(CXCursor cursor) {
6655   if (cursor.kind != CXCursor_InclusionDirective)
6656     return nullptr;
6657
6658   const InclusionDirective *ID = getCursorInclusionDirective(cursor);
6659   return const_cast<FileEntry *>(ID->getFile());
6660 }
6661
6662 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
6663   if (C.kind != CXCursor_ObjCPropertyDecl)
6664     return CXObjCPropertyAttr_noattr;
6665
6666   unsigned Result = CXObjCPropertyAttr_noattr;
6667   const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
6668   ObjCPropertyDecl::PropertyAttributeKind Attr =
6669       PD->getPropertyAttributesAsWritten();
6670
6671 #define SET_CXOBJCPROP_ATTR(A) \
6672   if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
6673     Result |= CXObjCPropertyAttr_##A
6674   SET_CXOBJCPROP_ATTR(readonly);
6675   SET_CXOBJCPROP_ATTR(getter);
6676   SET_CXOBJCPROP_ATTR(assign);
6677   SET_CXOBJCPROP_ATTR(readwrite);
6678   SET_CXOBJCPROP_ATTR(retain);
6679   SET_CXOBJCPROP_ATTR(copy);
6680   SET_CXOBJCPROP_ATTR(nonatomic);
6681   SET_CXOBJCPROP_ATTR(setter);
6682   SET_CXOBJCPROP_ATTR(atomic);
6683   SET_CXOBJCPROP_ATTR(weak);
6684   SET_CXOBJCPROP_ATTR(strong);
6685   SET_CXOBJCPROP_ATTR(unsafe_unretained);
6686 #undef SET_CXOBJCPROP_ATTR
6687
6688   return Result;
6689 }
6690
6691 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
6692   if (!clang_isDeclaration(C.kind))
6693     return CXObjCDeclQualifier_None;
6694
6695   Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
6696   const Decl *D = getCursorDecl(C);
6697   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6698     QT = MD->getObjCDeclQualifier();
6699   else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
6700     QT = PD->getObjCDeclQualifier();
6701   if (QT == Decl::OBJC_TQ_None)
6702     return CXObjCDeclQualifier_None;
6703
6704   unsigned Result = CXObjCDeclQualifier_None;
6705   if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
6706   if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
6707   if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
6708   if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
6709   if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
6710   if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
6711
6712   return Result;
6713 }
6714
6715 unsigned clang_Cursor_isObjCOptional(CXCursor C) {
6716   if (!clang_isDeclaration(C.kind))
6717     return 0;
6718
6719   const Decl *D = getCursorDecl(C);
6720   if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
6721     return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
6722   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6723     return MD->getImplementationControl() == ObjCMethodDecl::Optional;
6724
6725   return 0;
6726 }
6727
6728 unsigned clang_Cursor_isVariadic(CXCursor C) {
6729   if (!clang_isDeclaration(C.kind))
6730     return 0;
6731
6732   const Decl *D = getCursorDecl(C);
6733   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6734     return FD->isVariadic();
6735   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6736     return MD->isVariadic();
6737
6738   return 0;
6739 }
6740
6741 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
6742   if (!clang_isDeclaration(C.kind))
6743     return clang_getNullRange();
6744
6745   const Decl *D = getCursorDecl(C);
6746   ASTContext &Context = getCursorContext(C);
6747   const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
6748   if (!RC)
6749     return clang_getNullRange();
6750
6751   return cxloc::translateSourceRange(Context, RC->getSourceRange());
6752 }
6753
6754 CXString clang_Cursor_getRawCommentText(CXCursor C) {
6755   if (!clang_isDeclaration(C.kind))
6756     return cxstring::createNull();
6757
6758   const Decl *D = getCursorDecl(C);
6759   ASTContext &Context = getCursorContext(C);
6760   const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
6761   StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
6762                            StringRef();
6763
6764   // Don't duplicate the string because RawText points directly into source
6765   // code.
6766   return cxstring::createRef(RawText);
6767 }
6768
6769 CXString clang_Cursor_getBriefCommentText(CXCursor C) {
6770   if (!clang_isDeclaration(C.kind))
6771     return cxstring::createNull();
6772
6773   const Decl *D = getCursorDecl(C);
6774   const ASTContext &Context = getCursorContext(C);
6775   const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
6776
6777   if (RC) {
6778     StringRef BriefText = RC->getBriefText(Context);
6779
6780     // Don't duplicate the string because RawComment ensures that this memory
6781     // will not go away.
6782     return cxstring::createRef(BriefText);
6783   }
6784
6785   return cxstring::createNull();
6786 }
6787
6788 CXModule clang_Cursor_getModule(CXCursor C) {
6789   if (C.kind == CXCursor_ModuleImportDecl) {
6790     if (const ImportDecl *ImportD =
6791             dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
6792       return ImportD->getImportedModule();
6793   }
6794
6795   return nullptr;
6796 }
6797
6798 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
6799   if (isNotUsableTU(TU)) {
6800     LOG_BAD_TU(TU);
6801     return nullptr;
6802   }
6803   if (!File)
6804     return nullptr;
6805   FileEntry *FE = static_cast<FileEntry *>(File);
6806   
6807   ASTUnit &Unit = *cxtu::getASTUnit(TU);
6808   HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
6809   ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
6810   
6811   return Header.getModule();
6812 }
6813
6814 CXFile clang_Module_getASTFile(CXModule CXMod) {
6815   if (!CXMod)
6816     return nullptr;
6817   Module *Mod = static_cast<Module*>(CXMod);
6818   return const_cast<FileEntry *>(Mod->getASTFile());
6819 }
6820
6821 CXModule clang_Module_getParent(CXModule CXMod) {
6822   if (!CXMod)
6823     return nullptr;
6824   Module *Mod = static_cast<Module*>(CXMod);
6825   return Mod->Parent;
6826 }
6827
6828 CXString clang_Module_getName(CXModule CXMod) {
6829   if (!CXMod)
6830     return cxstring::createEmpty();
6831   Module *Mod = static_cast<Module*>(CXMod);
6832   return cxstring::createDup(Mod->Name);
6833 }
6834
6835 CXString clang_Module_getFullName(CXModule CXMod) {
6836   if (!CXMod)
6837     return cxstring::createEmpty();
6838   Module *Mod = static_cast<Module*>(CXMod);
6839   return cxstring::createDup(Mod->getFullModuleName());
6840 }
6841
6842 int clang_Module_isSystem(CXModule CXMod) {
6843   if (!CXMod)
6844     return 0;
6845   Module *Mod = static_cast<Module*>(CXMod);
6846   return Mod->IsSystem;
6847 }
6848
6849 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
6850                                             CXModule CXMod) {
6851   if (isNotUsableTU(TU)) {
6852     LOG_BAD_TU(TU);
6853     return 0;
6854   }
6855   if (!CXMod)
6856     return 0;
6857   Module *Mod = static_cast<Module*>(CXMod);
6858   FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
6859   ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
6860   return TopHeaders.size();
6861 }
6862
6863 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
6864                                       CXModule CXMod, unsigned Index) {
6865   if (isNotUsableTU(TU)) {
6866     LOG_BAD_TU(TU);
6867     return nullptr;
6868   }
6869   if (!CXMod)
6870     return nullptr;
6871   Module *Mod = static_cast<Module*>(CXMod);
6872   FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
6873
6874   ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
6875   if (Index < TopHeaders.size())
6876     return const_cast<FileEntry *>(TopHeaders[Index]);
6877
6878   return nullptr;
6879 }
6880
6881 } // end: extern "C"
6882
6883 //===----------------------------------------------------------------------===//
6884 // C++ AST instrospection.
6885 //===----------------------------------------------------------------------===//
6886
6887 extern "C" {
6888 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
6889   if (!clang_isDeclaration(C.kind))
6890     return 0;
6891
6892   const Decl *D = cxcursor::getCursorDecl(C);
6893   const CXXMethodDecl *Method =
6894       D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
6895   return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
6896 }
6897
6898 unsigned clang_CXXMethod_isConst(CXCursor C) {
6899   if (!clang_isDeclaration(C.kind))
6900     return 0;
6901
6902   const Decl *D = cxcursor::getCursorDecl(C);
6903   const CXXMethodDecl *Method =
6904       D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
6905   return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
6906 }
6907
6908 unsigned clang_CXXMethod_isStatic(CXCursor C) {
6909   if (!clang_isDeclaration(C.kind))
6910     return 0;
6911   
6912   const Decl *D = cxcursor::getCursorDecl(C);
6913   const CXXMethodDecl *Method =
6914       D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
6915   return (Method && Method->isStatic()) ? 1 : 0;
6916 }
6917
6918 unsigned clang_CXXMethod_isVirtual(CXCursor C) {
6919   if (!clang_isDeclaration(C.kind))
6920     return 0;
6921   
6922   const Decl *D = cxcursor::getCursorDecl(C);
6923   const CXXMethodDecl *Method =
6924       D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
6925   return (Method && Method->isVirtual()) ? 1 : 0;
6926 }
6927 } // end: extern "C"
6928
6929 //===----------------------------------------------------------------------===//
6930 // Attribute introspection.
6931 //===----------------------------------------------------------------------===//
6932
6933 extern "C" {
6934 CXType clang_getIBOutletCollectionType(CXCursor C) {
6935   if (C.kind != CXCursor_IBOutletCollectionAttr)
6936     return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
6937   
6938   const IBOutletCollectionAttr *A =
6939     cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
6940   
6941   return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));  
6942 }
6943 } // end: extern "C"
6944
6945 //===----------------------------------------------------------------------===//
6946 // Inspecting memory usage.
6947 //===----------------------------------------------------------------------===//
6948
6949 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
6950
6951 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
6952                                               enum CXTUResourceUsageKind k,
6953                                               unsigned long amount) {
6954   CXTUResourceUsageEntry entry = { k, amount };
6955   entries.push_back(entry);
6956 }
6957
6958 extern "C" {
6959
6960 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
6961   const char *str = "";
6962   switch (kind) {
6963     case CXTUResourceUsage_AST:
6964       str = "ASTContext: expressions, declarations, and types"; 
6965       break;
6966     case CXTUResourceUsage_Identifiers:
6967       str = "ASTContext: identifiers";
6968       break;
6969     case CXTUResourceUsage_Selectors:
6970       str = "ASTContext: selectors";
6971       break;
6972     case CXTUResourceUsage_GlobalCompletionResults:
6973       str = "Code completion: cached global results";
6974       break;
6975     case CXTUResourceUsage_SourceManagerContentCache:
6976       str = "SourceManager: content cache allocator";
6977       break;
6978     case CXTUResourceUsage_AST_SideTables:
6979       str = "ASTContext: side tables";
6980       break;
6981     case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
6982       str = "SourceManager: malloc'ed memory buffers";
6983       break;
6984     case CXTUResourceUsage_SourceManager_Membuffer_MMap:
6985       str = "SourceManager: mmap'ed memory buffers";
6986       break;
6987     case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
6988       str = "ExternalASTSource: malloc'ed memory buffers";
6989       break;
6990     case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
6991       str = "ExternalASTSource: mmap'ed memory buffers";
6992       break;
6993     case CXTUResourceUsage_Preprocessor:
6994       str = "Preprocessor: malloc'ed memory";
6995       break;
6996     case CXTUResourceUsage_PreprocessingRecord:
6997       str = "Preprocessor: PreprocessingRecord";
6998       break;
6999     case CXTUResourceUsage_SourceManager_DataStructures:
7000       str = "SourceManager: data structures and tables";
7001       break;
7002     case CXTUResourceUsage_Preprocessor_HeaderSearch:
7003       str = "Preprocessor: header search tables";
7004       break;
7005   }
7006   return str;
7007 }
7008
7009 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
7010   if (isNotUsableTU(TU)) {
7011     LOG_BAD_TU(TU);
7012     CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
7013     return usage;
7014   }
7015   
7016   ASTUnit *astUnit = cxtu::getASTUnit(TU);
7017   std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
7018   ASTContext &astContext = astUnit->getASTContext();
7019   
7020   // How much memory is used by AST nodes and types?
7021   createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
7022     (unsigned long) astContext.getASTAllocatedMemory());
7023
7024   // How much memory is used by identifiers?
7025   createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
7026     (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
7027
7028   // How much memory is used for selectors?
7029   createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
7030     (unsigned long) astContext.Selectors.getTotalMemory());
7031   
7032   // How much memory is used by ASTContext's side tables?
7033   createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
7034     (unsigned long) astContext.getSideTableAllocatedMemory());
7035   
7036   // How much memory is used for caching global code completion results?
7037   unsigned long completionBytes = 0;
7038   if (GlobalCodeCompletionAllocator *completionAllocator =
7039       astUnit->getCachedCompletionAllocator().get()) {
7040     completionBytes = completionAllocator->getTotalMemory();
7041   }
7042   createCXTUResourceUsageEntry(*entries,
7043                                CXTUResourceUsage_GlobalCompletionResults,
7044                                completionBytes);
7045   
7046   // How much memory is being used by SourceManager's content cache?
7047   createCXTUResourceUsageEntry(*entries,
7048           CXTUResourceUsage_SourceManagerContentCache,
7049           (unsigned long) astContext.getSourceManager().getContentCacheSize());
7050   
7051   // How much memory is being used by the MemoryBuffer's in SourceManager?
7052   const SourceManager::MemoryBufferSizes &srcBufs =
7053     astUnit->getSourceManager().getMemoryBufferSizes();
7054   
7055   createCXTUResourceUsageEntry(*entries,
7056                                CXTUResourceUsage_SourceManager_Membuffer_Malloc,
7057                                (unsigned long) srcBufs.malloc_bytes);
7058   createCXTUResourceUsageEntry(*entries,
7059                                CXTUResourceUsage_SourceManager_Membuffer_MMap,
7060                                (unsigned long) srcBufs.mmap_bytes);
7061   createCXTUResourceUsageEntry(*entries,
7062                                CXTUResourceUsage_SourceManager_DataStructures,
7063                                (unsigned long) astContext.getSourceManager()
7064                                 .getDataStructureSizes());
7065   
7066   // How much memory is being used by the ExternalASTSource?
7067   if (ExternalASTSource *esrc = astContext.getExternalSource()) {
7068     const ExternalASTSource::MemoryBufferSizes &sizes =
7069       esrc->getMemoryBufferSizes();
7070     
7071     createCXTUResourceUsageEntry(*entries,
7072       CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
7073                                  (unsigned long) sizes.malloc_bytes);
7074     createCXTUResourceUsageEntry(*entries,
7075       CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
7076                                  (unsigned long) sizes.mmap_bytes);
7077   }
7078   
7079   // How much memory is being used by the Preprocessor?
7080   Preprocessor &pp = astUnit->getPreprocessor();
7081   createCXTUResourceUsageEntry(*entries,
7082                                CXTUResourceUsage_Preprocessor,
7083                                pp.getTotalMemory());
7084   
7085   if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
7086     createCXTUResourceUsageEntry(*entries,
7087                                  CXTUResourceUsage_PreprocessingRecord,
7088                                  pRec->getTotalMemory());    
7089   }
7090   
7091   createCXTUResourceUsageEntry(*entries,
7092                                CXTUResourceUsage_Preprocessor_HeaderSearch,
7093                                pp.getHeaderSearchInfo().getTotalMemory());
7094
7095   CXTUResourceUsage usage = { (void*) entries.get(),
7096                             (unsigned) entries->size(),
7097                             !entries->empty() ? &(*entries)[0] : nullptr };
7098   entries.release();
7099   return usage;
7100 }
7101
7102 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
7103   if (usage.data)
7104     delete (MemUsageEntries*) usage.data;
7105 }
7106
7107 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
7108   CXSourceRangeList *skipped = new CXSourceRangeList;
7109   skipped->count = 0;
7110   skipped->ranges = nullptr;
7111
7112   if (isNotUsableTU(TU)) {
7113     LOG_BAD_TU(TU);
7114     return skipped;
7115   }
7116
7117   if (!file)
7118     return skipped;
7119
7120   ASTUnit *astUnit = cxtu::getASTUnit(TU);
7121   PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
7122   if (!ppRec)
7123     return skipped;
7124
7125   ASTContext &Ctx = astUnit->getASTContext();
7126   SourceManager &sm = Ctx.getSourceManager();
7127   FileEntry *fileEntry = static_cast<FileEntry *>(file);
7128   FileID wantedFileID = sm.translateFile(fileEntry);
7129
7130   const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
7131   std::vector<SourceRange> wantedRanges;
7132   for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
7133        i != ei; ++i) {
7134     if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
7135       wantedRanges.push_back(*i);
7136   }
7137
7138   skipped->count = wantedRanges.size();
7139   skipped->ranges = new CXSourceRange[skipped->count];
7140   for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
7141     skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
7142
7143   return skipped;
7144 }
7145
7146 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
7147   if (ranges) {
7148     delete[] ranges->ranges;
7149     delete ranges;
7150   }
7151 }
7152
7153 } // end extern "C"
7154
7155 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
7156   CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
7157   for (unsigned I = 0; I != Usage.numEntries; ++I)
7158     fprintf(stderr, "  %s: %lu\n", 
7159             clang_getTUResourceUsageName(Usage.entries[I].kind),
7160             Usage.entries[I].amount);
7161   
7162   clang_disposeCXTUResourceUsage(Usage);
7163 }
7164
7165 //===----------------------------------------------------------------------===//
7166 // Misc. utility functions.
7167 //===----------------------------------------------------------------------===//
7168
7169 /// Default to using an 8 MB stack size on "safety" threads.
7170 static unsigned SafetyStackThreadSize = 8 << 20;
7171
7172 namespace clang {
7173
7174 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
7175                unsigned Size) {
7176   if (!Size)
7177     Size = GetSafetyThreadStackSize();
7178   if (Size)
7179     return CRC.RunSafelyOnThread(Fn, Size);
7180   return CRC.RunSafely(Fn);
7181 }
7182
7183 unsigned GetSafetyThreadStackSize() {
7184   return SafetyStackThreadSize;
7185 }
7186
7187 void SetSafetyThreadStackSize(unsigned Value) {
7188   SafetyStackThreadSize = Value;
7189 }
7190
7191 }
7192
7193 void clang::setThreadBackgroundPriority() {
7194   if (getenv("LIBCLANG_BGPRIO_DISABLE"))
7195     return;
7196
7197 #ifdef USE_DARWIN_THREADS
7198   setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
7199 #endif
7200 }
7201
7202 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
7203   if (!Unit)
7204     return;
7205
7206   for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 
7207                                   DEnd = Unit->stored_diag_end();
7208        D != DEnd; ++D) {
7209     CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
7210     CXString Msg = clang_formatDiagnostic(&Diag,
7211                                 clang_defaultDiagnosticDisplayOptions());
7212     fprintf(stderr, "%s\n", clang_getCString(Msg));
7213     clang_disposeString(Msg);
7214   }
7215 #ifdef LLVM_ON_WIN32
7216   // On Windows, force a flush, since there may be multiple copies of
7217   // stderr and stdout in the file system, all with different buffers
7218   // but writing to the same device.
7219   fflush(stderr);
7220 #endif
7221 }
7222
7223 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
7224                                  SourceLocation MacroDefLoc,
7225                                  CXTranslationUnit TU){
7226   if (MacroDefLoc.isInvalid() || !TU)
7227     return nullptr;
7228   if (!II.hadMacroDefinition())
7229     return nullptr;
7230
7231   ASTUnit *Unit = cxtu::getASTUnit(TU);
7232   Preprocessor &PP = Unit->getPreprocessor();
7233   MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
7234   if (MD) {
7235     for (MacroDirective::DefInfo
7236            Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
7237       if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
7238         return Def.getMacroInfo();
7239     }
7240   }
7241
7242   return nullptr;
7243 }
7244
7245 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
7246                                        CXTranslationUnit TU) {
7247   if (!MacroDef || !TU)
7248     return nullptr;
7249   const IdentifierInfo *II = MacroDef->getName();
7250   if (!II)
7251     return nullptr;
7252
7253   return getMacroInfo(*II, MacroDef->getLocation(), TU);
7254 }
7255
7256 MacroDefinitionRecord *
7257 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
7258                                         CXTranslationUnit TU) {
7259   if (!MI || !TU)
7260     return nullptr;
7261   if (Tok.isNot(tok::raw_identifier))
7262     return nullptr;
7263
7264   if (MI->getNumTokens() == 0)
7265     return nullptr;
7266   SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
7267                        MI->getDefinitionEndLoc());
7268   ASTUnit *Unit = cxtu::getASTUnit(TU);
7269
7270   // Check that the token is inside the definition and not its argument list.
7271   SourceManager &SM = Unit->getSourceManager();
7272   if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
7273     return nullptr;
7274   if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
7275     return nullptr;
7276
7277   Preprocessor &PP = Unit->getPreprocessor();
7278   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
7279   if (!PPRec)
7280     return nullptr;
7281
7282   IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
7283   if (!II.hadMacroDefinition())
7284     return nullptr;
7285
7286   // Check that the identifier is not one of the macro arguments.
7287   if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
7288     return nullptr;
7289
7290   MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
7291   if (!InnerMD)
7292     return nullptr;
7293
7294   return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
7295 }
7296
7297 MacroDefinitionRecord *
7298 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
7299                                         CXTranslationUnit TU) {
7300   if (Loc.isInvalid() || !MI || !TU)
7301     return nullptr;
7302
7303   if (MI->getNumTokens() == 0)
7304     return nullptr;
7305   ASTUnit *Unit = cxtu::getASTUnit(TU);
7306   Preprocessor &PP = Unit->getPreprocessor();
7307   if (!PP.getPreprocessingRecord())
7308     return nullptr;
7309   Loc = Unit->getSourceManager().getSpellingLoc(Loc);
7310   Token Tok;
7311   if (PP.getRawToken(Loc, Tok))
7312     return nullptr;
7313
7314   return checkForMacroInMacroDefinition(MI, Tok, TU);
7315 }
7316
7317 extern "C" {
7318
7319 CXString clang_getClangVersion() {
7320   return cxstring::createDup(getClangFullVersion());
7321 }
7322
7323 } // end: extern "C"
7324
7325 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
7326   if (TU) {
7327     if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
7328       LogOS << '<' << Unit->getMainFileName() << '>';
7329       if (Unit->isMainFileAST())
7330         LogOS << " (" << Unit->getASTFileName() << ')';
7331       return *this;
7332     }
7333   } else {
7334     LogOS << "<NULL TU>";
7335   }
7336   return *this;
7337 }
7338
7339 Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
7340   *this << FE->getName();
7341   return *this;
7342 }
7343
7344 Logger &cxindex::Logger::operator<<(CXCursor cursor) {
7345   CXString cursorName = clang_getCursorDisplayName(cursor);
7346   *this << cursorName << "@" << clang_getCursorLocation(cursor);
7347   clang_disposeString(cursorName);
7348   return *this;
7349 }
7350
7351 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
7352   CXFile File;
7353   unsigned Line, Column;
7354   clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
7355   CXString FileName = clang_getFileName(File);
7356   *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
7357   clang_disposeString(FileName);
7358   return *this;
7359 }
7360
7361 Logger &cxindex::Logger::operator<<(CXSourceRange range) {
7362   CXSourceLocation BLoc = clang_getRangeStart(range);
7363   CXSourceLocation ELoc = clang_getRangeEnd(range);
7364
7365   CXFile BFile;
7366   unsigned BLine, BColumn;
7367   clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
7368
7369   CXFile EFile;
7370   unsigned ELine, EColumn;
7371   clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
7372
7373   CXString BFileName = clang_getFileName(BFile);
7374   if (BFile == EFile) {
7375     *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
7376                          BLine, BColumn, ELine, EColumn);
7377   } else {
7378     CXString EFileName = clang_getFileName(EFile);
7379     *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
7380                           BLine, BColumn)
7381           << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
7382                           ELine, EColumn);
7383     clang_disposeString(EFileName);
7384   }
7385   clang_disposeString(BFileName);
7386   return *this;
7387 }
7388
7389 Logger &cxindex::Logger::operator<<(CXString Str) {
7390   *this << clang_getCString(Str);
7391   return *this;
7392 }
7393
7394 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
7395   LogOS << Fmt;
7396   return *this;
7397 }
7398
7399 static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
7400
7401 cxindex::Logger::~Logger() {
7402   llvm::sys::ScopedLock L(*LoggingMutex);
7403
7404   static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
7405
7406   raw_ostream &OS = llvm::errs();
7407   OS << "[libclang:" << Name << ':';
7408
7409 #ifdef USE_DARWIN_THREADS
7410   // TODO: Portability.
7411   mach_port_t tid = pthread_mach_thread_np(pthread_self());
7412   OS << tid << ':';
7413 #endif
7414
7415   llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
7416   OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
7417   OS << Msg << '\n';
7418
7419   if (Trace) {
7420     llvm::sys::PrintStackTrace(OS);
7421     OS << "--------------------------------------------------\n";
7422   }
7423 }