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