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