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