xref: /llvm-project/clang/lib/Basic/SourceManager.cpp (revision 92a47bd997710676fc9057e08785dcbbdc91a5d7)
1 //===--- SourceManager.cpp - Track and cache source files -----------------===//
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 SourceManager interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/SourceManager.h"
15 #include "clang/Basic/SourceManagerInternals.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/FileManager.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/Capacity.h"
25 #include <algorithm>
26 #include <string>
27 #include <cstring>
28 #include <sys/stat.h>
29 
30 using namespace clang;
31 using namespace SrcMgr;
32 using llvm::MemoryBuffer;
33 
34 //===----------------------------------------------------------------------===//
35 // SourceManager Helper Classes
36 //===----------------------------------------------------------------------===//
37 
38 ContentCache::~ContentCache() {
39   if (shouldFreeBuffer())
40     delete Buffer.getPointer();
41 }
42 
43 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
44 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
45 unsigned ContentCache::getSizeBytesMapped() const {
46   return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
47 }
48 
49 /// Returns the kind of memory used to back the memory buffer for
50 /// this content cache.  This is used for performance analysis.
51 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
52   assert(Buffer.getPointer());
53 
54   // Should be unreachable, but keep for sanity.
55   if (!Buffer.getPointer())
56     return llvm::MemoryBuffer::MemoryBuffer_Malloc;
57 
58   const llvm::MemoryBuffer *buf = Buffer.getPointer();
59   return buf->getBufferKind();
60 }
61 
62 /// getSize - Returns the size of the content encapsulated by this ContentCache.
63 ///  This can be the size of the source file or the size of an arbitrary
64 ///  scratch buffer.  If the ContentCache encapsulates a source file, that
65 ///  file is not lazily brought in from disk to satisfy this query.
66 unsigned ContentCache::getSize() const {
67   return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
68                              : (unsigned) ContentsEntry->getSize();
69 }
70 
71 void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
72                                  bool DoNotFree) {
73   assert(B != Buffer.getPointer());
74 
75   if (shouldFreeBuffer())
76     delete Buffer.getPointer();
77   Buffer.setPointer(B);
78   Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
79 }
80 
81 const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
82                                                   const SourceManager &SM,
83                                                   SourceLocation Loc,
84                                                   bool *Invalid) const {
85   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
86   // computed it, just return what we have.
87   if (Buffer.getPointer() || ContentsEntry == 0) {
88     if (Invalid)
89       *Invalid = isBufferInvalid();
90 
91     return Buffer.getPointer();
92   }
93 
94   std::string ErrorStr;
95   Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
96 
97   // If we were unable to open the file, then we are in an inconsistent
98   // situation where the content cache referenced a file which no longer
99   // exists. Most likely, we were using a stat cache with an invalid entry but
100   // the file could also have been removed during processing. Since we can't
101   // really deal with this situation, just create an empty buffer.
102   //
103   // FIXME: This is definitely not ideal, but our immediate clients can't
104   // currently handle returning a null entry here. Ideally we should detect
105   // that we are in an inconsistent situation and error out as quickly as
106   // possible.
107   if (!Buffer.getPointer()) {
108     const StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
109     Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
110                                                     "<invalid>"));
111     char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
112     for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
113       Ptr[i] = FillStr[i % FillStr.size()];
114 
115     if (Diag.isDiagnosticInFlight())
116       Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
117                                 ContentsEntry->getName(), ErrorStr);
118     else
119       Diag.Report(Loc, diag::err_cannot_open_file)
120         << ContentsEntry->getName() << ErrorStr;
121 
122     Buffer.setInt(Buffer.getInt() | InvalidFlag);
123 
124     if (Invalid) *Invalid = true;
125     return Buffer.getPointer();
126   }
127 
128   // Check that the file's size is the same as in the file entry (which may
129   // have come from a stat cache).
130   if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
131     if (Diag.isDiagnosticInFlight())
132       Diag.SetDelayedDiagnostic(diag::err_file_modified,
133                                 ContentsEntry->getName());
134     else
135       Diag.Report(Loc, diag::err_file_modified)
136         << ContentsEntry->getName();
137 
138     Buffer.setInt(Buffer.getInt() | InvalidFlag);
139     if (Invalid) *Invalid = true;
140     return Buffer.getPointer();
141   }
142 
143   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
144   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
145   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
146   StringRef BufStr = Buffer.getPointer()->getBuffer();
147   const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
148     .StartsWith("\xFE\xFF", "UTF-16 (BE)")
149     .StartsWith("\xFF\xFE", "UTF-16 (LE)")
150     .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
151     .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
152     .StartsWith("\x2B\x2F\x76", "UTF-7")
153     .StartsWith("\xF7\x64\x4C", "UTF-1")
154     .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
155     .StartsWith("\x0E\xFE\xFF", "SDSU")
156     .StartsWith("\xFB\xEE\x28", "BOCU-1")
157     .StartsWith("\x84\x31\x95\x33", "GB-18030")
158     .Default(0);
159 
160   if (InvalidBOM) {
161     Diag.Report(Loc, diag::err_unsupported_bom)
162       << InvalidBOM << ContentsEntry->getName();
163     Buffer.setInt(Buffer.getInt() | InvalidFlag);
164   }
165 
166   if (Invalid)
167     *Invalid = isBufferInvalid();
168 
169   return Buffer.getPointer();
170 }
171 
172 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
173   // Look up the filename in the string table, returning the pre-existing value
174   // if it exists.
175   llvm::StringMapEntry<unsigned> &Entry =
176     FilenameIDs.GetOrCreateValue(Name, ~0U);
177   if (Entry.getValue() != ~0U)
178     return Entry.getValue();
179 
180   // Otherwise, assign this the next available ID.
181   Entry.setValue(FilenamesByID.size());
182   FilenamesByID.push_back(&Entry);
183   return FilenamesByID.size()-1;
184 }
185 
186 /// AddLineNote - Add a line note to the line table that indicates that there
187 /// is a #line at the specified FID/Offset location which changes the presumed
188 /// location to LineNo/FilenameID.
189 void LineTableInfo::AddLineNote(int FID, unsigned Offset,
190                                 unsigned LineNo, int FilenameID) {
191   std::vector<LineEntry> &Entries = LineEntries[FID];
192 
193   assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
194          "Adding line entries out of order!");
195 
196   SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
197   unsigned IncludeOffset = 0;
198 
199   if (!Entries.empty()) {
200     // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
201     // that we are still in "foo.h".
202     if (FilenameID == -1)
203       FilenameID = Entries.back().FilenameID;
204 
205     // If we are after a line marker that switched us to system header mode, or
206     // that set #include information, preserve it.
207     Kind = Entries.back().FileKind;
208     IncludeOffset = Entries.back().IncludeOffset;
209   }
210 
211   Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
212                                    IncludeOffset));
213 }
214 
215 /// AddLineNote This is the same as the previous version of AddLineNote, but is
216 /// used for GNU line markers.  If EntryExit is 0, then this doesn't change the
217 /// presumed #include stack.  If it is 1, this is a file entry, if it is 2 then
218 /// this is a file exit.  FileKind specifies whether this is a system header or
219 /// extern C system header.
220 void LineTableInfo::AddLineNote(int FID, unsigned Offset,
221                                 unsigned LineNo, int FilenameID,
222                                 unsigned EntryExit,
223                                 SrcMgr::CharacteristicKind FileKind) {
224   assert(FilenameID != -1 && "Unspecified filename should use other accessor");
225 
226   std::vector<LineEntry> &Entries = LineEntries[FID];
227 
228   assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
229          "Adding line entries out of order!");
230 
231   unsigned IncludeOffset = 0;
232   if (EntryExit == 0) {  // No #include stack change.
233     IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
234   } else if (EntryExit == 1) {
235     IncludeOffset = Offset-1;
236   } else if (EntryExit == 2) {
237     assert(!Entries.empty() && Entries.back().IncludeOffset &&
238        "PPDirectives should have caught case when popping empty include stack");
239 
240     // Get the include loc of the last entries' include loc as our include loc.
241     IncludeOffset = 0;
242     if (const LineEntry *PrevEntry =
243           FindNearestLineEntry(FID, Entries.back().IncludeOffset))
244       IncludeOffset = PrevEntry->IncludeOffset;
245   }
246 
247   Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
248                                    IncludeOffset));
249 }
250 
251 
252 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
253 /// it.  If there is no line entry before Offset in FID, return null.
254 const LineEntry *LineTableInfo::FindNearestLineEntry(int FID,
255                                                      unsigned Offset) {
256   const std::vector<LineEntry> &Entries = LineEntries[FID];
257   assert(!Entries.empty() && "No #line entries for this FID after all!");
258 
259   // It is very common for the query to be after the last #line, check this
260   // first.
261   if (Entries.back().FileOffset <= Offset)
262     return &Entries.back();
263 
264   // Do a binary search to find the maximal element that is still before Offset.
265   std::vector<LineEntry>::const_iterator I =
266     std::upper_bound(Entries.begin(), Entries.end(), Offset);
267   if (I == Entries.begin()) return 0;
268   return &*--I;
269 }
270 
271 /// \brief Add a new line entry that has already been encoded into
272 /// the internal representation of the line table.
273 void LineTableInfo::AddEntry(int FID,
274                              const std::vector<LineEntry> &Entries) {
275   LineEntries[FID] = Entries;
276 }
277 
278 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
279 ///
280 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
281   if (LineTable == 0)
282     LineTable = new LineTableInfo();
283   return LineTable->getLineTableFilenameID(Name);
284 }
285 
286 
287 /// AddLineNote - Add a line note to the line table for the FileID and offset
288 /// specified by Loc.  If FilenameID is -1, it is considered to be
289 /// unspecified.
290 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
291                                 int FilenameID) {
292   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
293 
294   bool Invalid = false;
295   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
296   if (!Entry.isFile() || Invalid)
297     return;
298 
299   const SrcMgr::FileInfo &FileInfo = Entry.getFile();
300 
301   // Remember that this file has #line directives now if it doesn't already.
302   const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
303 
304   if (LineTable == 0)
305     LineTable = new LineTableInfo();
306   LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
307 }
308 
309 /// AddLineNote - Add a GNU line marker to the line table.
310 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
311                                 int FilenameID, bool IsFileEntry,
312                                 bool IsFileExit, bool IsSystemHeader,
313                                 bool IsExternCHeader) {
314   // If there is no filename and no flags, this is treated just like a #line,
315   // which does not change the flags of the previous line marker.
316   if (FilenameID == -1) {
317     assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
318            "Can't set flags without setting the filename!");
319     return AddLineNote(Loc, LineNo, FilenameID);
320   }
321 
322   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
323 
324   bool Invalid = false;
325   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
326   if (!Entry.isFile() || Invalid)
327     return;
328 
329   const SrcMgr::FileInfo &FileInfo = Entry.getFile();
330 
331   // Remember that this file has #line directives now if it doesn't already.
332   const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
333 
334   if (LineTable == 0)
335     LineTable = new LineTableInfo();
336 
337   SrcMgr::CharacteristicKind FileKind;
338   if (IsExternCHeader)
339     FileKind = SrcMgr::C_ExternCSystem;
340   else if (IsSystemHeader)
341     FileKind = SrcMgr::C_System;
342   else
343     FileKind = SrcMgr::C_User;
344 
345   unsigned EntryExit = 0;
346   if (IsFileEntry)
347     EntryExit = 1;
348   else if (IsFileExit)
349     EntryExit = 2;
350 
351   LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
352                          EntryExit, FileKind);
353 }
354 
355 LineTableInfo &SourceManager::getLineTable() {
356   if (LineTable == 0)
357     LineTable = new LineTableInfo();
358   return *LineTable;
359 }
360 
361 //===----------------------------------------------------------------------===//
362 // Private 'Create' methods.
363 //===----------------------------------------------------------------------===//
364 
365 SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
366   : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
367     ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
368     NumBinaryProbes(0), FakeBufferForRecovery(0) {
369   clearIDTables();
370   Diag.setSourceManager(this);
371 }
372 
373 SourceManager::~SourceManager() {
374   delete LineTable;
375 
376   // Delete FileEntry objects corresponding to content caches.  Since the actual
377   // content cache objects are bump pointer allocated, we just have to run the
378   // dtors, but we call the deallocate method for completeness.
379   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
380     MemBufferInfos[i]->~ContentCache();
381     ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
382   }
383   for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
384        I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
385     I->second->~ContentCache();
386     ContentCacheAlloc.Deallocate(I->second);
387   }
388 
389   delete FakeBufferForRecovery;
390 }
391 
392 void SourceManager::clearIDTables() {
393   MainFileID = FileID();
394   LocalSLocEntryTable.clear();
395   LoadedSLocEntryTable.clear();
396   SLocEntryLoaded.clear();
397   LastLineNoFileIDQuery = FileID();
398   LastLineNoContentCache = 0;
399   LastFileIDLookup = FileID();
400 
401   if (LineTable)
402     LineTable->clear();
403 
404   // Use up FileID #0 as an invalid expansion.
405   NextLocalOffset = 0;
406   CurrentLoadedOffset = MaxLoadedOffset;
407   createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
408 }
409 
410 /// getOrCreateContentCache - Create or return a cached ContentCache for the
411 /// specified file.
412 const ContentCache *
413 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
414   assert(FileEnt && "Didn't specify a file entry to use?");
415 
416   // Do we already have information about this file?
417   ContentCache *&Entry = FileInfos[FileEnt];
418   if (Entry) return Entry;
419 
420   // Nope, create a new Cache entry.  Make sure it is at least 8-byte aligned
421   // so that FileInfo can use the low 3 bits of the pointer for its own
422   // nefarious purposes.
423   unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
424   EntryAlign = std::max(8U, EntryAlign);
425   Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
426 
427   // If the file contents are overridden with contents from another file,
428   // pass that file to ContentCache.
429   llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
430       overI = OverriddenFiles.find(FileEnt);
431   if (overI == OverriddenFiles.end())
432     new (Entry) ContentCache(FileEnt);
433   else
434     new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
435                                                             : overI->second,
436                              overI->second);
437 
438   return Entry;
439 }
440 
441 
442 /// createMemBufferContentCache - Create a new ContentCache for the specified
443 ///  memory buffer.  This does no caching.
444 const ContentCache*
445 SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
446   // Add a new ContentCache to the MemBufferInfos list and return it.  Make sure
447   // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
448   // the pointer for its own nefarious purposes.
449   unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
450   EntryAlign = std::max(8U, EntryAlign);
451   ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
452   new (Entry) ContentCache();
453   MemBufferInfos.push_back(Entry);
454   Entry->setBuffer(Buffer);
455   return Entry;
456 }
457 
458 std::pair<int, unsigned>
459 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
460                                          unsigned TotalSize) {
461   assert(ExternalSLocEntries && "Don't have an external sloc source");
462   LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
463   SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
464   CurrentLoadedOffset -= TotalSize;
465   assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations");
466   int ID = LoadedSLocEntryTable.size();
467   return std::make_pair(-ID - 1, CurrentLoadedOffset);
468 }
469 
470 /// \brief As part of recovering from missing or changed content, produce a
471 /// fake, non-empty buffer.
472 const llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
473   if (!FakeBufferForRecovery)
474     FakeBufferForRecovery
475       = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
476 
477   return FakeBufferForRecovery;
478 }
479 
480 //===----------------------------------------------------------------------===//
481 // Methods to create new FileID's and macro expansions.
482 //===----------------------------------------------------------------------===//
483 
484 /// createFileID - Create a new FileID for the specified ContentCache and
485 /// include position.  This works regardless of whether the ContentCache
486 /// corresponds to a file or some other input source.
487 FileID SourceManager::createFileID(const ContentCache *File,
488                                    SourceLocation IncludePos,
489                                    SrcMgr::CharacteristicKind FileCharacter,
490                                    int LoadedID, unsigned LoadedOffset) {
491   if (LoadedID < 0) {
492     assert(LoadedID != -1 && "Loading sentinel FileID");
493     unsigned Index = unsigned(-LoadedID) - 2;
494     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
495     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
496     LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
497         FileInfo::get(IncludePos, File, FileCharacter));
498     SLocEntryLoaded[Index] = true;
499     return FileID::get(LoadedID);
500   }
501   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
502                                                FileInfo::get(IncludePos, File,
503                                                              FileCharacter)));
504   unsigned FileSize = File->getSize();
505   assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
506          NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
507          "Ran out of source locations!");
508   // We do a +1 here because we want a SourceLocation that means "the end of the
509   // file", e.g. for the "no newline at the end of the file" diagnostic.
510   NextLocalOffset += FileSize + 1;
511 
512   // Set LastFileIDLookup to the newly created file.  The next getFileID call is
513   // almost guaranteed to be from that file.
514   FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
515   return LastFileIDLookup = FID;
516 }
517 
518 SourceLocation
519 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
520                                           SourceLocation ExpansionLoc,
521                                           unsigned TokLength) {
522   ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
523                                                         ExpansionLoc);
524   return createExpansionLocImpl(Info, TokLength);
525 }
526 
527 SourceLocation
528 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
529                                   SourceLocation ExpansionLocStart,
530                                   SourceLocation ExpansionLocEnd,
531                                   unsigned TokLength,
532                                   int LoadedID,
533                                   unsigned LoadedOffset) {
534   ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
535                                              ExpansionLocEnd);
536   return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
537 }
538 
539 SourceLocation
540 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
541                                       unsigned TokLength,
542                                       int LoadedID,
543                                       unsigned LoadedOffset) {
544   if (LoadedID < 0) {
545     assert(LoadedID != -1 && "Loading sentinel FileID");
546     unsigned Index = unsigned(-LoadedID) - 2;
547     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
548     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
549     LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
550     SLocEntryLoaded[Index] = true;
551     return SourceLocation::getMacroLoc(LoadedOffset);
552   }
553   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
554   assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
555          NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
556          "Ran out of source locations!");
557   // See createFileID for that +1.
558   NextLocalOffset += TokLength + 1;
559   return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
560 }
561 
562 const llvm::MemoryBuffer *
563 SourceManager::getMemoryBufferForFile(const FileEntry *File,
564                                       bool *Invalid) {
565   const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
566   assert(IR && "getOrCreateContentCache() cannot return NULL");
567   return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
568 }
569 
570 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
571                                          const llvm::MemoryBuffer *Buffer,
572                                          bool DoNotFree) {
573   const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
574   assert(IR && "getOrCreateContentCache() cannot return NULL");
575 
576   const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
577 }
578 
579 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
580                                          const FileEntry *NewFile) {
581   assert(SourceFile->getSize() == NewFile->getSize() &&
582          "Different sizes, use the FileManager to create a virtual file with "
583          "the correct size");
584   assert(FileInfos.count(SourceFile) == 0 &&
585          "This function should be called at the initialization stage, before "
586          "any parsing occurs.");
587   OverriddenFiles[SourceFile] = NewFile;
588 }
589 
590 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
591   bool MyInvalid = false;
592   const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
593   if (!SLoc.isFile() || MyInvalid) {
594     if (Invalid)
595       *Invalid = true;
596     return "<<<<<INVALID SOURCE LOCATION>>>>>";
597   }
598 
599   const llvm::MemoryBuffer *Buf
600     = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
601                                                   &MyInvalid);
602   if (Invalid)
603     *Invalid = MyInvalid;
604 
605   if (MyInvalid)
606     return "<<<<<INVALID SOURCE LOCATION>>>>>";
607 
608   return Buf->getBuffer();
609 }
610 
611 //===----------------------------------------------------------------------===//
612 // SourceLocation manipulation methods.
613 //===----------------------------------------------------------------------===//
614 
615 /// \brief Return the FileID for a SourceLocation.
616 ///
617 /// This is the cache-miss path of getFileID. Not as hot as that function, but
618 /// still very important. It is responsible for finding the entry in the
619 /// SLocEntry tables that contains the specified location.
620 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
621   if (!SLocOffset)
622     return FileID::get(0);
623 
624   // Now it is time to search for the correct file. See where the SLocOffset
625   // sits in the global view and consult local or loaded buffers for it.
626   if (SLocOffset < NextLocalOffset)
627     return getFileIDLocal(SLocOffset);
628   return getFileIDLoaded(SLocOffset);
629 }
630 
631 /// \brief Return the FileID for a SourceLocation with a low offset.
632 ///
633 /// This function knows that the SourceLocation is in a local buffer, not a
634 /// loaded one.
635 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
636   assert(SLocOffset < NextLocalOffset && "Bad function choice");
637 
638   // After the first and second level caches, I see two common sorts of
639   // behavior: 1) a lot of searched FileID's are "near" the cached file
640   // location or are "near" the cached expansion location. 2) others are just
641   // completely random and may be a very long way away.
642   //
643   // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
644   // then we fall back to a less cache efficient, but more scalable, binary
645   // search to find the location.
646 
647   // See if this is near the file point - worst case we start scanning from the
648   // most newly created FileID.
649   std::vector<SrcMgr::SLocEntry>::const_iterator I;
650 
651   if (LastFileIDLookup.ID < 0 ||
652       LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
653     // Neither loc prunes our search.
654     I = LocalSLocEntryTable.end();
655   } else {
656     // Perhaps it is near the file point.
657     I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
658   }
659 
660   // Find the FileID that contains this.  "I" is an iterator that points to a
661   // FileID whose offset is known to be larger than SLocOffset.
662   unsigned NumProbes = 0;
663   while (1) {
664     --I;
665     if (I->getOffset() <= SLocOffset) {
666       FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
667 
668       // If this isn't an expansion, remember it.  We have good locality across
669       // FileID lookups.
670       if (!I->isExpansion())
671         LastFileIDLookup = Res;
672       NumLinearScans += NumProbes+1;
673       return Res;
674     }
675     if (++NumProbes == 8)
676       break;
677   }
678 
679   // Convert "I" back into an index.  We know that it is an entry whose index is
680   // larger than the offset we are looking for.
681   unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
682   // LessIndex - This is the lower bound of the range that we're searching.
683   // We know that the offset corresponding to the FileID is is less than
684   // SLocOffset.
685   unsigned LessIndex = 0;
686   NumProbes = 0;
687   while (1) {
688     bool Invalid = false;
689     unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
690     unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
691     if (Invalid)
692       return FileID::get(0);
693 
694     ++NumProbes;
695 
696     // If the offset of the midpoint is too large, chop the high side of the
697     // range to the midpoint.
698     if (MidOffset > SLocOffset) {
699       GreaterIndex = MiddleIndex;
700       continue;
701     }
702 
703     // If the middle index contains the value, succeed and return.
704     // FIXME: This could be made faster by using a function that's aware of
705     // being in the local area.
706     if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
707       FileID Res = FileID::get(MiddleIndex);
708 
709       // If this isn't a macro expansion, remember it.  We have good locality
710       // across FileID lookups.
711       if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
712         LastFileIDLookup = Res;
713       NumBinaryProbes += NumProbes;
714       return Res;
715     }
716 
717     // Otherwise, move the low-side up to the middle index.
718     LessIndex = MiddleIndex;
719   }
720 }
721 
722 /// \brief Return the FileID for a SourceLocation with a high offset.
723 ///
724 /// This function knows that the SourceLocation is in a loaded buffer, not a
725 /// local one.
726 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
727   assert(SLocOffset >= CurrentLoadedOffset && "Bad function choice");
728 
729   // Essentially the same as the local case, but the loaded array is sorted
730   // in the other direction.
731 
732   // First do a linear scan from the last lookup position, if possible.
733   unsigned I;
734   int LastID = LastFileIDLookup.ID;
735   if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
736     I = 0;
737   else
738     I = (-LastID - 2) + 1;
739 
740   unsigned NumProbes;
741   for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
742     // Make sure the entry is loaded!
743     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
744     if (E.getOffset() <= SLocOffset) {
745       FileID Res = FileID::get(-int(I) - 2);
746 
747       if (!E.isExpansion())
748         LastFileIDLookup = Res;
749       NumLinearScans += NumProbes + 1;
750       return Res;
751     }
752   }
753 
754   // Linear scan failed. Do the binary search. Note the reverse sorting of the
755   // table: GreaterIndex is the one where the offset is greater, which is
756   // actually a lower index!
757   unsigned GreaterIndex = I;
758   unsigned LessIndex = LoadedSLocEntryTable.size();
759   NumProbes = 0;
760   while (1) {
761     ++NumProbes;
762     unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
763     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
764 
765     ++NumProbes;
766 
767     if (E.getOffset() > SLocOffset) {
768       GreaterIndex = MiddleIndex;
769       continue;
770     }
771 
772     if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
773       FileID Res = FileID::get(-int(MiddleIndex) - 2);
774       if (!E.isExpansion())
775         LastFileIDLookup = Res;
776       NumBinaryProbes += NumProbes;
777       return Res;
778     }
779 
780     LessIndex = MiddleIndex;
781   }
782 }
783 
784 SourceLocation SourceManager::
785 getExpansionLocSlowCase(SourceLocation Loc) const {
786   do {
787     // Note: If Loc indicates an offset into a token that came from a macro
788     // expansion (e.g. the 5th character of the token) we do not want to add
789     // this offset when going to the expansion location.  The expansion
790     // location is the macro invocation, which the offset has nothing to do
791     // with.  This is unlike when we get the spelling loc, because the offset
792     // directly correspond to the token whose spelling we're inspecting.
793     Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
794   } while (!Loc.isFileID());
795 
796   return Loc;
797 }
798 
799 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
800   do {
801     std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
802     Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
803     Loc = Loc.getFileLocWithOffset(LocInfo.second);
804   } while (!Loc.isFileID());
805   return Loc;
806 }
807 
808 
809 std::pair<FileID, unsigned>
810 SourceManager::getDecomposedExpansionLocSlowCase(
811                                              const SrcMgr::SLocEntry *E) const {
812   // If this is an expansion record, walk through all the expansion points.
813   FileID FID;
814   SourceLocation Loc;
815   unsigned Offset;
816   do {
817     Loc = E->getExpansion().getExpansionLocStart();
818 
819     FID = getFileID(Loc);
820     E = &getSLocEntry(FID);
821     Offset = Loc.getOffset()-E->getOffset();
822   } while (!Loc.isFileID());
823 
824   return std::make_pair(FID, Offset);
825 }
826 
827 std::pair<FileID, unsigned>
828 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
829                                                 unsigned Offset) const {
830   // If this is an expansion record, walk through all the expansion points.
831   FileID FID;
832   SourceLocation Loc;
833   do {
834     Loc = E->getExpansion().getSpellingLoc();
835 
836     FID = getFileID(Loc);
837     E = &getSLocEntry(FID);
838     Offset += Loc.getOffset()-E->getOffset();
839   } while (!Loc.isFileID());
840 
841   return std::make_pair(FID, Offset);
842 }
843 
844 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
845 /// spelling location referenced by the ID.  This is the first level down
846 /// towards the place where the characters that make up the lexed token can be
847 /// found.  This should not generally be used by clients.
848 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
849   if (Loc.isFileID()) return Loc;
850   std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
851   Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
852   return Loc.getFileLocWithOffset(LocInfo.second);
853 }
854 
855 
856 /// getImmediateExpansionRange - Loc is required to be an expansion location.
857 /// Return the start/end of the expansion information.
858 std::pair<SourceLocation,SourceLocation>
859 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
860   assert(Loc.isMacroID() && "Not a macro expansion loc!");
861   const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
862   return Expansion.getExpansionLocRange();
863 }
864 
865 /// getExpansionRange - Given a SourceLocation object, return the range of
866 /// tokens covered by the expansion in the ultimate file.
867 std::pair<SourceLocation,SourceLocation>
868 SourceManager::getExpansionRange(SourceLocation Loc) const {
869   if (Loc.isFileID()) return std::make_pair(Loc, Loc);
870 
871   std::pair<SourceLocation,SourceLocation> Res =
872     getImmediateExpansionRange(Loc);
873 
874   // Fully resolve the start and end locations to their ultimate expansion
875   // points.
876   while (!Res.first.isFileID())
877     Res.first = getImmediateExpansionRange(Res.first).first;
878   while (!Res.second.isFileID())
879     Res.second = getImmediateExpansionRange(Res.second).second;
880   return Res;
881 }
882 
883 bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const {
884   if (!Loc.isMacroID()) return false;
885 
886   FileID FID = getFileID(Loc);
887   const SrcMgr::SLocEntry *E = &getSLocEntry(FID);
888   const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
889   return Expansion.isMacroArgExpansion();
890 }
891 
892 
893 //===----------------------------------------------------------------------===//
894 // Queries about the code at a SourceLocation.
895 //===----------------------------------------------------------------------===//
896 
897 /// getCharacterData - Return a pointer to the start of the specified location
898 /// in the appropriate MemoryBuffer.
899 const char *SourceManager::getCharacterData(SourceLocation SL,
900                                             bool *Invalid) const {
901   // Note that this is a hot function in the getSpelling() path, which is
902   // heavily used by -E mode.
903   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
904 
905   // Note that calling 'getBuffer()' may lazily page in a source file.
906   bool CharDataInvalid = false;
907   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
908   if (CharDataInvalid || !Entry.isFile()) {
909     if (Invalid)
910       *Invalid = true;
911 
912     return "<<<<INVALID BUFFER>>>>";
913   }
914   const llvm::MemoryBuffer *Buffer
915     = Entry.getFile().getContentCache()
916                   ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
917   if (Invalid)
918     *Invalid = CharDataInvalid;
919   return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
920 }
921 
922 
923 /// getColumnNumber - Return the column # for the specified file position.
924 /// this is significantly cheaper to compute than the line number.
925 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
926                                         bool *Invalid) const {
927   bool MyInvalid = false;
928   const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
929   if (Invalid)
930     *Invalid = MyInvalid;
931 
932   if (MyInvalid)
933     return 1;
934 
935   unsigned LineStart = FilePos;
936   while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
937     --LineStart;
938   return FilePos-LineStart+1;
939 }
940 
941 // isInvalid - Return the result of calling loc.isInvalid(), and
942 // if Invalid is not null, set its value to same.
943 static bool isInvalid(SourceLocation Loc, bool *Invalid) {
944   bool MyInvalid = Loc.isInvalid();
945   if (Invalid)
946     *Invalid = MyInvalid;
947   return MyInvalid;
948 }
949 
950 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
951                                                 bool *Invalid) const {
952   if (isInvalid(Loc, Invalid)) return 0;
953   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
954   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
955 }
956 
957 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
958                                                  bool *Invalid) const {
959   if (isInvalid(Loc, Invalid)) return 0;
960   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
961   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
962 }
963 
964 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
965                                                 bool *Invalid) const {
966   if (isInvalid(Loc, Invalid)) return 0;
967   return getPresumedLoc(Loc).getColumn();
968 }
969 
970 static LLVM_ATTRIBUTE_NOINLINE void
971 ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
972                    llvm::BumpPtrAllocator &Alloc,
973                    const SourceManager &SM, bool &Invalid);
974 static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
975                                llvm::BumpPtrAllocator &Alloc,
976                                const SourceManager &SM, bool &Invalid) {
977   // Note that calling 'getBuffer()' may lazily page in the file.
978   const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
979                                              &Invalid);
980   if (Invalid)
981     return;
982 
983   // Find the file offsets of all of the *physical* source lines.  This does
984   // not look at trigraphs, escaped newlines, or anything else tricky.
985   SmallVector<unsigned, 256> LineOffsets;
986 
987   // Line #1 starts at char 0.
988   LineOffsets.push_back(0);
989 
990   const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
991   const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
992   unsigned Offs = 0;
993   while (1) {
994     // Skip over the contents of the line.
995     // TODO: Vectorize this?  This is very performance sensitive for programs
996     // with lots of diagnostics and in -E mode.
997     const unsigned char *NextBuf = (const unsigned char *)Buf;
998     while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
999       ++NextBuf;
1000     Offs += NextBuf-Buf;
1001     Buf = NextBuf;
1002 
1003     if (Buf[0] == '\n' || Buf[0] == '\r') {
1004       // If this is \n\r or \r\n, skip both characters.
1005       if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1006         ++Offs, ++Buf;
1007       ++Offs, ++Buf;
1008       LineOffsets.push_back(Offs);
1009     } else {
1010       // Otherwise, this is a null.  If end of file, exit.
1011       if (Buf == End) break;
1012       // Otherwise, skip the null.
1013       ++Offs, ++Buf;
1014     }
1015   }
1016 
1017   // Copy the offsets into the FileInfo structure.
1018   FI->NumLines = LineOffsets.size();
1019   FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1020   std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1021 }
1022 
1023 /// getLineNumber - Given a SourceLocation, return the spelling line number
1024 /// for the position indicated.  This requires building and caching a table of
1025 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1026 /// about to emit a diagnostic.
1027 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1028                                       bool *Invalid) const {
1029   if (FID.isInvalid()) {
1030     if (Invalid)
1031       *Invalid = true;
1032     return 1;
1033   }
1034 
1035   ContentCache *Content;
1036   if (LastLineNoFileIDQuery == FID)
1037     Content = LastLineNoContentCache;
1038   else {
1039     bool MyInvalid = false;
1040     const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1041     if (MyInvalid || !Entry.isFile()) {
1042       if (Invalid)
1043         *Invalid = true;
1044       return 1;
1045     }
1046 
1047     Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1048   }
1049 
1050   // If this is the first use of line information for this buffer, compute the
1051   /// SourceLineCache for it on demand.
1052   if (Content->SourceLineCache == 0) {
1053     bool MyInvalid = false;
1054     ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1055     if (Invalid)
1056       *Invalid = MyInvalid;
1057     if (MyInvalid)
1058       return 1;
1059   } else if (Invalid)
1060     *Invalid = false;
1061 
1062   // Okay, we know we have a line number table.  Do a binary search to find the
1063   // line number that this character position lands on.
1064   unsigned *SourceLineCache = Content->SourceLineCache;
1065   unsigned *SourceLineCacheStart = SourceLineCache;
1066   unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1067 
1068   unsigned QueriedFilePos = FilePos+1;
1069 
1070   // FIXME: I would like to be convinced that this code is worth being as
1071   // complicated as it is, binary search isn't that slow.
1072   //
1073   // If it is worth being optimized, then in my opinion it could be more
1074   // performant, simpler, and more obviously correct by just "galloping" outward
1075   // from the queried file position. In fact, this could be incorporated into a
1076   // generic algorithm such as lower_bound_with_hint.
1077   //
1078   // If someone gives me a test case where this matters, and I will do it! - DWD
1079 
1080   // If the previous query was to the same file, we know both the file pos from
1081   // that query and the line number returned.  This allows us to narrow the
1082   // search space from the entire file to something near the match.
1083   if (LastLineNoFileIDQuery == FID) {
1084     if (QueriedFilePos >= LastLineNoFilePos) {
1085       // FIXME: Potential overflow?
1086       SourceLineCache = SourceLineCache+LastLineNoResult-1;
1087 
1088       // The query is likely to be nearby the previous one.  Here we check to
1089       // see if it is within 5, 10 or 20 lines.  It can be far away in cases
1090       // where big comment blocks and vertical whitespace eat up lines but
1091       // contribute no tokens.
1092       if (SourceLineCache+5 < SourceLineCacheEnd) {
1093         if (SourceLineCache[5] > QueriedFilePos)
1094           SourceLineCacheEnd = SourceLineCache+5;
1095         else if (SourceLineCache+10 < SourceLineCacheEnd) {
1096           if (SourceLineCache[10] > QueriedFilePos)
1097             SourceLineCacheEnd = SourceLineCache+10;
1098           else if (SourceLineCache+20 < SourceLineCacheEnd) {
1099             if (SourceLineCache[20] > QueriedFilePos)
1100               SourceLineCacheEnd = SourceLineCache+20;
1101           }
1102         }
1103       }
1104     } else {
1105       if (LastLineNoResult < Content->NumLines)
1106         SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1107     }
1108   }
1109 
1110   // If the spread is large, do a "radix" test as our initial guess, based on
1111   // the assumption that lines average to approximately the same length.
1112   // NOTE: This is currently disabled, as it does not appear to be profitable in
1113   // initial measurements.
1114   if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
1115     unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
1116 
1117     // Take a stab at guessing where it is.
1118     unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
1119 
1120     // Check for -10 and +10 lines.
1121     unsigned LowerBound = std::max(int(ApproxPos-10), 0);
1122     unsigned UpperBound = std::min(ApproxPos+10, FileLen);
1123 
1124     // If the computed lower bound is less than the query location, move it in.
1125     if (SourceLineCache < SourceLineCacheStart+LowerBound &&
1126         SourceLineCacheStart[LowerBound] < QueriedFilePos)
1127       SourceLineCache = SourceLineCacheStart+LowerBound;
1128 
1129     // If the computed upper bound is greater than the query location, move it.
1130     if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
1131         SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1132       SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1133   }
1134 
1135   unsigned *Pos
1136     = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1137   unsigned LineNo = Pos-SourceLineCacheStart;
1138 
1139   LastLineNoFileIDQuery = FID;
1140   LastLineNoContentCache = Content;
1141   LastLineNoFilePos = QueriedFilePos;
1142   LastLineNoResult = LineNo;
1143   return LineNo;
1144 }
1145 
1146 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1147                                               bool *Invalid) const {
1148   if (isInvalid(Loc, Invalid)) return 0;
1149   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1150   return getLineNumber(LocInfo.first, LocInfo.second);
1151 }
1152 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1153                                                bool *Invalid) const {
1154   if (isInvalid(Loc, Invalid)) return 0;
1155   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1156   return getLineNumber(LocInfo.first, LocInfo.second);
1157 }
1158 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1159                                               bool *Invalid) const {
1160   if (isInvalid(Loc, Invalid)) return 0;
1161   return getPresumedLoc(Loc).getLine();
1162 }
1163 
1164 /// getFileCharacteristic - return the file characteristic of the specified
1165 /// source location, indicating whether this is a normal file, a system
1166 /// header, or an "implicit extern C" system header.
1167 ///
1168 /// This state can be modified with flags on GNU linemarker directives like:
1169 ///   # 4 "foo.h" 3
1170 /// which changes all source locations in the current file after that to be
1171 /// considered to be from a system header.
1172 SrcMgr::CharacteristicKind
1173 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1174   assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
1175   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1176   bool Invalid = false;
1177   const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1178   if (Invalid || !SEntry.isFile())
1179     return C_User;
1180 
1181   const SrcMgr::FileInfo &FI = SEntry.getFile();
1182 
1183   // If there are no #line directives in this file, just return the whole-file
1184   // state.
1185   if (!FI.hasLineDirectives())
1186     return FI.getFileCharacteristic();
1187 
1188   assert(LineTable && "Can't have linetable entries without a LineTable!");
1189   // See if there is a #line directive before the location.
1190   const LineEntry *Entry =
1191     LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
1192 
1193   // If this is before the first line marker, use the file characteristic.
1194   if (!Entry)
1195     return FI.getFileCharacteristic();
1196 
1197   return Entry->FileKind;
1198 }
1199 
1200 /// Return the filename or buffer identifier of the buffer the location is in.
1201 /// Note that this name does not respect #line directives.  Use getPresumedLoc
1202 /// for normal clients.
1203 const char *SourceManager::getBufferName(SourceLocation Loc,
1204                                          bool *Invalid) const {
1205   if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1206 
1207   return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1208 }
1209 
1210 
1211 /// getPresumedLoc - This method returns the "presumed" location of a
1212 /// SourceLocation specifies.  A "presumed location" can be modified by #line
1213 /// or GNU line marker directives.  This provides a view on the data that a
1214 /// user should see in diagnostics, for example.
1215 ///
1216 /// Note that a presumed location is always given as the expansion point of an
1217 /// expansion location, not at the spelling location.
1218 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1219   if (Loc.isInvalid()) return PresumedLoc();
1220 
1221   // Presumed locations are always for expansion points.
1222   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1223 
1224   bool Invalid = false;
1225   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1226   if (Invalid || !Entry.isFile())
1227     return PresumedLoc();
1228 
1229   const SrcMgr::FileInfo &FI = Entry.getFile();
1230   const SrcMgr::ContentCache *C = FI.getContentCache();
1231 
1232   // To get the source name, first consult the FileEntry (if one exists)
1233   // before the MemBuffer as this will avoid unnecessarily paging in the
1234   // MemBuffer.
1235   const char *Filename;
1236   if (C->OrigEntry)
1237     Filename = C->OrigEntry->getName();
1238   else
1239     Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
1240 
1241   unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1242   if (Invalid)
1243     return PresumedLoc();
1244   unsigned ColNo  = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1245   if (Invalid)
1246     return PresumedLoc();
1247 
1248   SourceLocation IncludeLoc = FI.getIncludeLoc();
1249 
1250   // If we have #line directives in this file, update and overwrite the physical
1251   // location info if appropriate.
1252   if (FI.hasLineDirectives()) {
1253     assert(LineTable && "Can't have linetable entries without a LineTable!");
1254     // See if there is a #line directive before this.  If so, get it.
1255     if (const LineEntry *Entry =
1256           LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
1257       // If the LineEntry indicates a filename, use it.
1258       if (Entry->FilenameID != -1)
1259         Filename = LineTable->getFilename(Entry->FilenameID);
1260 
1261       // Use the line number specified by the LineEntry.  This line number may
1262       // be multiple lines down from the line entry.  Add the difference in
1263       // physical line numbers from the query point and the line marker to the
1264       // total.
1265       unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1266       LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1267 
1268       // Note that column numbers are not molested by line markers.
1269 
1270       // Handle virtual #include manipulation.
1271       if (Entry->IncludeOffset) {
1272         IncludeLoc = getLocForStartOfFile(LocInfo.first);
1273         IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1274       }
1275     }
1276   }
1277 
1278   return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
1279 }
1280 
1281 //===----------------------------------------------------------------------===//
1282 // Other miscellaneous methods.
1283 //===----------------------------------------------------------------------===//
1284 
1285 /// \brief Retrieve the inode for the given file entry, if possible.
1286 ///
1287 /// This routine involves a system call, and therefore should only be used
1288 /// in non-performance-critical code.
1289 static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1290   if (!File)
1291     return llvm::Optional<ino_t>();
1292 
1293   struct stat StatBuf;
1294   if (::stat(File->getName(), &StatBuf))
1295     return llvm::Optional<ino_t>();
1296 
1297   return StatBuf.st_ino;
1298 }
1299 
1300 /// \brief Get the source location for the given file:line:col triplet.
1301 ///
1302 /// If the source file is included multiple times, the source location will
1303 /// be based upon an arbitrary inclusion.
1304 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1305                                                   unsigned Line, unsigned Col) {
1306   assert(SourceFile && "Null source file!");
1307   assert(Line && Col && "Line and column should start from 1!");
1308 
1309   // Find the first file ID that corresponds to the given file.
1310   FileID FirstFID;
1311 
1312   // First, check the main file ID, since it is common to look for a
1313   // location in the main file.
1314   llvm::Optional<ino_t> SourceFileInode;
1315   llvm::Optional<StringRef> SourceFileName;
1316   if (!MainFileID.isInvalid()) {
1317     bool Invalid = false;
1318     const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1319     if (Invalid)
1320       return SourceLocation();
1321 
1322     if (MainSLoc.isFile()) {
1323       const ContentCache *MainContentCache
1324         = MainSLoc.getFile().getContentCache();
1325       if (!MainContentCache) {
1326         // Can't do anything
1327       } else if (MainContentCache->OrigEntry == SourceFile) {
1328         FirstFID = MainFileID;
1329       } else {
1330         // Fall back: check whether we have the same base name and inode
1331         // as the main file.
1332         const FileEntry *MainFile = MainContentCache->OrigEntry;
1333         SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1334         if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1335           SourceFileInode = getActualFileInode(SourceFile);
1336           if (SourceFileInode) {
1337             if (llvm::Optional<ino_t> MainFileInode
1338                                                = getActualFileInode(MainFile)) {
1339               if (*SourceFileInode == *MainFileInode) {
1340                 FirstFID = MainFileID;
1341                 SourceFile = MainFile;
1342               }
1343             }
1344           }
1345         }
1346       }
1347     }
1348   }
1349 
1350   if (FirstFID.isInvalid()) {
1351     // The location we're looking for isn't in the main file; look
1352     // through all of the local source locations.
1353     for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1354       bool Invalid = false;
1355       const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1356       if (Invalid)
1357         return SourceLocation();
1358 
1359       if (SLoc.isFile() &&
1360           SLoc.getFile().getContentCache() &&
1361           SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1362         FirstFID = FileID::get(I);
1363         break;
1364       }
1365     }
1366     // If that still didn't help, try the modules.
1367     if (FirstFID.isInvalid()) {
1368       for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1369         const SLocEntry &SLoc = getLoadedSLocEntry(I);
1370         if (SLoc.isFile() &&
1371             SLoc.getFile().getContentCache() &&
1372             SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1373           FirstFID = FileID::get(-int(I) - 2);
1374           break;
1375         }
1376       }
1377     }
1378   }
1379 
1380   // If we haven't found what we want yet, try again, but this time stat()
1381   // each of the files in case the files have changed since we originally
1382   // parsed the file.
1383   if (FirstFID.isInvalid() &&
1384       (SourceFileName ||
1385        (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1386       (SourceFileInode ||
1387        (SourceFileInode = getActualFileInode(SourceFile)))) {
1388     bool Invalid = false;
1389     for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1390       FileID IFileID;
1391       IFileID.ID = I;
1392       const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
1393       if (Invalid)
1394         return SourceLocation();
1395 
1396       if (SLoc.isFile()) {
1397         const ContentCache *FileContentCache
1398           = SLoc.getFile().getContentCache();
1399       const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
1400         if (Entry &&
1401             *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1402           if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1403             if (*SourceFileInode == *EntryInode) {
1404               FirstFID = FileID::get(I);
1405               SourceFile = Entry;
1406               break;
1407             }
1408           }
1409         }
1410       }
1411     }
1412   }
1413 
1414   if (FirstFID.isInvalid())
1415     return SourceLocation();
1416 
1417   if (Line == 1 && Col == 1)
1418     return getLocForStartOfFile(FirstFID);
1419 
1420   ContentCache *Content
1421     = const_cast<ContentCache *>(getOrCreateContentCache(SourceFile));
1422   if (!Content)
1423     return SourceLocation();
1424 
1425   // If this is the first use of line information for this buffer, compute the
1426   // SourceLineCache for it on demand.
1427   if (Content->SourceLineCache == 0) {
1428     bool MyInvalid = false;
1429     ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1430     if (MyInvalid)
1431       return SourceLocation();
1432   }
1433 
1434   if (Line > Content->NumLines) {
1435     unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
1436     if (Size > 0)
1437       --Size;
1438     return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1439   }
1440 
1441   unsigned FilePos = Content->SourceLineCache[Line - 1];
1442   const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1443   unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
1444   unsigned i = 0;
1445 
1446   // Check that the given column is valid.
1447   while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1448     ++i;
1449   if (i < Col-1)
1450     return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1451 
1452   return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
1453 }
1454 
1455 /// \brief If \arg Loc points inside a function macro argument, the returned
1456 /// location will be the macro location in which the argument was expanded.
1457 /// If a macro argument is used multiple times, the expanded location will
1458 /// be at the first expansion of the argument.
1459 /// e.g.
1460 ///   MY_MACRO(foo);
1461 ///             ^
1462 /// Passing a file location pointing at 'foo', will yield a macro location
1463 /// where 'foo' was expanded into.
1464 SourceLocation SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) {
1465   if (Loc.isInvalid())
1466     return Loc;
1467 
1468   FileID FID = getFileID(Loc);
1469   if (FID.isInvalid())
1470     return Loc;
1471 
1472   int ID = FID.ID;
1473   while (1) {
1474     ++ID;
1475     // Stop if there are no more FileIDs to check.
1476     if (ID > 0) {
1477       if (unsigned(ID) >= local_sloc_entry_size())
1478         return Loc;
1479     } else if (ID == -1) {
1480       return Loc;
1481     }
1482 
1483     const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID);
1484     if (Entry.isFile()) {
1485       if (Entry.getFile().getIncludeLoc().isValid() &&
1486           !isBeforeInTranslationUnit(Entry.getFile().getIncludeLoc(), Loc))
1487         return Loc;
1488       continue;
1489     }
1490 
1491     if (isBeforeInTranslationUnit(Loc,
1492                                   Entry.getExpansion().getExpansionLocStart()))
1493       return Loc;
1494     if (!Entry.getExpansion().isMacroArgExpansion())
1495       continue;
1496 
1497     // This is a macro argument expansion. See if Loc points in the argument
1498     // that was lexed.
1499 
1500     SourceLocation SpellLoc = Entry.getExpansion().getSpellingLoc();
1501     unsigned NextOffset;
1502     if (ID > 0) {
1503       if (unsigned(ID+1) == local_sloc_entry_size())
1504         NextOffset = getNextLocalOffset();
1505       else
1506         NextOffset = getLocalSLocEntry(ID+1).getOffset();
1507     } else {
1508       if (ID+1 == -1)
1509         NextOffset = MaxLoadedOffset;
1510       else
1511         NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1512     }
1513     unsigned EntrySize = NextOffset - Entry.getOffset() - 1;
1514     unsigned BeginOffs = SpellLoc.getOffset();
1515     unsigned EndOffs = BeginOffs + EntrySize;
1516     if (BeginOffs <= Loc.getOffset() && Loc.getOffset() < EndOffs) {
1517       SourceLocation ExpandLoc = SourceLocation::getMacroLoc(Entry.getOffset());
1518       // Replace current Loc with the expanded location and continue.
1519       // The expanded argument may end up being passed to another function macro
1520       // and relexed again.
1521       Loc = ExpandLoc.getFileLocWithOffset(Loc.getOffset()-BeginOffs);
1522     }
1523   }
1524 }
1525 
1526 /// Given a decomposed source location, move it up the include/expansion stack
1527 /// to the parent source location.  If this is possible, return the decomposed
1528 /// version of the parent in Loc and return false.  If Loc is the top-level
1529 /// entry, return true and don't modify it.
1530 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1531                                    const SourceManager &SM) {
1532   SourceLocation UpperLoc;
1533   const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
1534   if (Entry.isExpansion())
1535     UpperLoc = Entry.getExpansion().getExpansionLocStart();
1536   else
1537     UpperLoc = Entry.getFile().getIncludeLoc();
1538 
1539   if (UpperLoc.isInvalid())
1540     return true; // We reached the top.
1541 
1542   Loc = SM.getDecomposedLoc(UpperLoc);
1543   return false;
1544 }
1545 
1546 
1547 /// \brief Determines the order of 2 source locations in the translation unit.
1548 ///
1549 /// \returns true if LHS source location comes before RHS, false otherwise.
1550 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1551                                               SourceLocation RHS) const {
1552   assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1553   if (LHS == RHS)
1554     return false;
1555 
1556   std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1557   std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
1558 
1559   // If the source locations are in the same file, just compare offsets.
1560   if (LOffs.first == ROffs.first)
1561     return LOffs.second < ROffs.second;
1562 
1563   // If we are comparing a source location with multiple locations in the same
1564   // file, we get a big win by caching the result.
1565   if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1566     return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
1567 
1568   // Okay, we missed in the cache, start updating the cache for this query.
1569   IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
1570                           /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
1571 
1572   // We need to find the common ancestor. The only way of doing this is to
1573   // build the complete include chain for one and then walking up the chain
1574   // of the other looking for a match.
1575   // We use a map from FileID to Offset to store the chain. Easier than writing
1576   // a custom set hash info that only depends on the first part of a pair.
1577   typedef llvm::DenseMap<FileID, unsigned> LocSet;
1578   LocSet LChain;
1579   do {
1580     LChain.insert(LOffs);
1581     // We catch the case where LOffs is in a file included by ROffs and
1582     // quit early. The other way round unfortunately remains suboptimal.
1583   } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
1584   LocSet::iterator I;
1585   while((I = LChain.find(ROffs.first)) == LChain.end()) {
1586     if (MoveUpIncludeHierarchy(ROffs, *this))
1587       break; // Met at topmost file.
1588   }
1589   if (I != LChain.end())
1590     LOffs = *I;
1591 
1592   // If we exited because we found a nearest common ancestor, compare the
1593   // locations within the common file and cache them.
1594   if (LOffs.first == ROffs.first) {
1595     IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1596     return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
1597   }
1598 
1599   // This can happen if a location is in a built-ins buffer.
1600   // But see PR5662.
1601   // Clear the lookup cache, it depends on a common location.
1602   IsBeforeInTUCache.clear();
1603   bool LIsBuiltins = strcmp("<built-in>",
1604                             getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
1605   bool RIsBuiltins = strcmp("<built-in>",
1606                             getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
1607   // built-in is before non-built-in
1608   if (LIsBuiltins != RIsBuiltins)
1609     return LIsBuiltins;
1610   assert(LIsBuiltins && RIsBuiltins &&
1611          "Non-built-in locations must be rooted in the main file");
1612   // Both are in built-in buffers, but from different files. We just claim that
1613   // lower IDs come first.
1614   return LOffs.first < ROffs.first;
1615 }
1616 
1617 /// PrintStats - Print statistics to stderr.
1618 ///
1619 void SourceManager::PrintStats() const {
1620   llvm::errs() << "\n*** Source Manager Stats:\n";
1621   llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1622                << " mem buffers mapped.\n";
1623   llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
1624                << llvm::capacity_in_bytes(LocalSLocEntryTable)
1625                << " bytes of capacity), "
1626                << NextLocalOffset << "B of Sloc address space used.\n";
1627   llvm::errs() << LoadedSLocEntryTable.size()
1628                << " loaded SLocEntries allocated, "
1629                << MaxLoadedOffset - CurrentLoadedOffset
1630                << "B of Sloc address space used.\n";
1631 
1632   unsigned NumLineNumsComputed = 0;
1633   unsigned NumFileBytesMapped = 0;
1634   for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1635     NumLineNumsComputed += I->second->SourceLineCache != 0;
1636     NumFileBytesMapped  += I->second->getSizeBytesMapped();
1637   }
1638 
1639   llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1640                << NumLineNumsComputed << " files with line #'s computed.\n";
1641   llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1642                << NumBinaryProbes << " binary.\n";
1643 }
1644 
1645 ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
1646 
1647 /// Return the amount of memory used by memory buffers, breaking down
1648 /// by heap-backed versus mmap'ed memory.
1649 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
1650   size_t malloc_bytes = 0;
1651   size_t mmap_bytes = 0;
1652 
1653   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
1654     if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
1655       switch (MemBufferInfos[i]->getMemoryBufferKind()) {
1656         case llvm::MemoryBuffer::MemoryBuffer_MMap:
1657           mmap_bytes += sized_mapped;
1658           break;
1659         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
1660           malloc_bytes += sized_mapped;
1661           break;
1662       }
1663 
1664   return MemoryBufferSizes(malloc_bytes, mmap_bytes);
1665 }
1666 
1667 size_t SourceManager::getDataStructureSizes() const {
1668   return llvm::capacity_in_bytes(MemBufferInfos)
1669     + llvm::capacity_in_bytes(LocalSLocEntryTable)
1670     + llvm::capacity_in_bytes(LoadedSLocEntryTable)
1671     + llvm::capacity_in_bytes(SLocEntryLoaded)
1672     + llvm::capacity_in_bytes(FileInfos)
1673     + llvm::capacity_in_bytes(OverriddenFiles);
1674 }
1675