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