xref: /llvm-project/clang/lib/Basic/SourceManager.cpp (revision 99d1b295031ea4e74630914c14f94d919aa8e8dc)
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/Diagnostic.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/SourceManagerInternals.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Support/Capacity.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <algorithm>
27 #include <cstring>
28 
29 using namespace clang;
30 using namespace SrcMgr;
31 using llvm::MemoryBuffer;
32 
33 //===----------------------------------------------------------------------===//
34 // SourceManager Helper Classes
35 //===----------------------------------------------------------------------===//
36 
37 ContentCache::~ContentCache() {
38   if (shouldFreeBuffer())
39     delete Buffer.getPointer();
40 }
41 
42 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
43 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
44 unsigned ContentCache::getSizeBytesMapped() const {
45   return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
46 }
47 
48 /// Returns the kind of memory used to back the memory buffer for
49 /// this content cache.  This is used for performance analysis.
50 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
51   assert(Buffer.getPointer());
52 
53   // Should be unreachable, but keep for sanity.
54   if (!Buffer.getPointer())
55     return llvm::MemoryBuffer::MemoryBuffer_Malloc;
56 
57   llvm::MemoryBuffer *buf = Buffer.getPointer();
58   return buf->getBufferKind();
59 }
60 
61 /// getSize - Returns the size of the content encapsulated by this ContentCache.
62 ///  This can be the size of the source file or the size of an arbitrary
63 ///  scratch buffer.  If the ContentCache encapsulates a source file, that
64 ///  file is not lazily brought in from disk to satisfy this query.
65 unsigned ContentCache::getSize() const {
66   return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
67                              : (unsigned) ContentsEntry->getSize();
68 }
69 
70 void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) {
71   if (B && B == Buffer.getPointer()) {
72     assert(0 && "Replacing with the same buffer");
73     Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
74     return;
75   }
76 
77   if (shouldFreeBuffer())
78     delete Buffer.getPointer();
79   Buffer.setPointer(B);
80   Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
81 }
82 
83 llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
84                                             const SourceManager &SM,
85                                             SourceLocation Loc,
86                                             bool *Invalid) const {
87   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
88   // computed it, just return what we have.
89   if (Buffer.getPointer() || !ContentsEntry) {
90     if (Invalid)
91       *Invalid = isBufferInvalid();
92 
93     return Buffer.getPointer();
94   }
95 
96   bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
97   auto BufferOrError =
98       SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
99 
100   // If we were unable to open the file, then we are in an inconsistent
101   // situation where the content cache referenced a file which no longer
102   // exists. Most likely, we were using a stat cache with an invalid entry but
103   // the file could also have been removed during processing. Since we can't
104   // really deal with this situation, just create an empty buffer.
105   //
106   // FIXME: This is definitely not ideal, but our immediate clients can't
107   // currently handle returning a null entry here. Ideally we should detect
108   // that we are in an inconsistent situation and error out as quickly as
109   // possible.
110   if (!BufferOrError) {
111     StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
112     Buffer.setPointer(MemoryBuffer::getNewUninitMemBuffer(
113                           ContentsEntry->getSize(), "<invalid>").release());
114     char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
115     for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
116       Ptr[i] = FillStr[i % FillStr.size()];
117 
118     if (Diag.isDiagnosticInFlight())
119       Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
120                                 ContentsEntry->getName(),
121                                 BufferOrError.getError().message());
122     else
123       Diag.Report(Loc, diag::err_cannot_open_file)
124           << ContentsEntry->getName() << BufferOrError.getError().message();
125 
126     Buffer.setInt(Buffer.getInt() | InvalidFlag);
127 
128     if (Invalid) *Invalid = true;
129     return Buffer.getPointer();
130   }
131 
132   Buffer.setPointer(BufferOrError->release());
133 
134   // Check that the file's size is the same as in the file entry (which may
135   // have come from a stat cache).
136   if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
137     if (Diag.isDiagnosticInFlight())
138       Diag.SetDelayedDiagnostic(diag::err_file_modified,
139                                 ContentsEntry->getName());
140     else
141       Diag.Report(Loc, diag::err_file_modified)
142         << ContentsEntry->getName();
143 
144     Buffer.setInt(Buffer.getInt() | InvalidFlag);
145     if (Invalid) *Invalid = true;
146     return Buffer.getPointer();
147   }
148 
149   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
150   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
151   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
152   StringRef BufStr = Buffer.getPointer()->getBuffer();
153   const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
154     .StartsWith("\xFE\xFF", "UTF-16 (BE)")
155     .StartsWith("\xFF\xFE", "UTF-16 (LE)")
156     .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
157     .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
158     .StartsWith("\x2B\x2F\x76", "UTF-7")
159     .StartsWith("\xF7\x64\x4C", "UTF-1")
160     .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
161     .StartsWith("\x0E\xFE\xFF", "SDSU")
162     .StartsWith("\xFB\xEE\x28", "BOCU-1")
163     .StartsWith("\x84\x31\x95\x33", "GB-18030")
164     .Default(nullptr);
165 
166   if (InvalidBOM) {
167     Diag.Report(Loc, diag::err_unsupported_bom)
168       << InvalidBOM << ContentsEntry->getName();
169     Buffer.setInt(Buffer.getInt() | InvalidFlag);
170   }
171 
172   if (Invalid)
173     *Invalid = isBufferInvalid();
174 
175   return Buffer.getPointer();
176 }
177 
178 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
179   auto IterBool =
180       FilenameIDs.insert(std::make_pair(Name, FilenamesByID.size()));
181   if (IterBool.second)
182     FilenamesByID.push_back(&*IterBool.first);
183   return IterBool.first->second;
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(FileID 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(FileID 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(FileID 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 nullptr;
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(FileID 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   return getLineTable().getLineTableFilenameID(Name);
282 }
283 
284 
285 /// AddLineNote - Add a line note to the line table for the FileID and offset
286 /// specified by Loc.  If FilenameID is -1, it is considered to be
287 /// unspecified.
288 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
289                                 int FilenameID) {
290   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
291 
292   bool Invalid = false;
293   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
294   if (!Entry.isFile() || Invalid)
295     return;
296 
297   const SrcMgr::FileInfo &FileInfo = Entry.getFile();
298 
299   // Remember that this file has #line directives now if it doesn't already.
300   const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
301 
302   getLineTable().AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID);
303 }
304 
305 /// AddLineNote - Add a GNU line marker to the line table.
306 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
307                                 int FilenameID, bool IsFileEntry,
308                                 bool IsFileExit, bool IsSystemHeader,
309                                 bool IsExternCHeader) {
310   // If there is no filename and no flags, this is treated just like a #line,
311   // which does not change the flags of the previous line marker.
312   if (FilenameID == -1) {
313     assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
314            "Can't set flags without setting the filename!");
315     return AddLineNote(Loc, LineNo, FilenameID);
316   }
317 
318   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
319 
320   bool Invalid = false;
321   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
322   if (!Entry.isFile() || Invalid)
323     return;
324 
325   const SrcMgr::FileInfo &FileInfo = Entry.getFile();
326 
327   // Remember that this file has #line directives now if it doesn't already.
328   const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
329 
330   (void) getLineTable();
331 
332   SrcMgr::CharacteristicKind FileKind;
333   if (IsExternCHeader)
334     FileKind = SrcMgr::C_ExternCSystem;
335   else if (IsSystemHeader)
336     FileKind = SrcMgr::C_System;
337   else
338     FileKind = SrcMgr::C_User;
339 
340   unsigned EntryExit = 0;
341   if (IsFileEntry)
342     EntryExit = 1;
343   else if (IsFileExit)
344     EntryExit = 2;
345 
346   LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
347                          EntryExit, FileKind);
348 }
349 
350 LineTableInfo &SourceManager::getLineTable() {
351   if (!LineTable)
352     LineTable = new LineTableInfo();
353   return *LineTable;
354 }
355 
356 //===----------------------------------------------------------------------===//
357 // Private 'Create' methods.
358 //===----------------------------------------------------------------------===//
359 
360 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
361                              bool UserFilesAreVolatile)
362   : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
363     UserFilesAreVolatile(UserFilesAreVolatile), FilesAreTransient(false),
364     ExternalSLocEntries(nullptr), LineTable(nullptr), NumLinearScans(0),
365     NumBinaryProbes(0) {
366   clearIDTables();
367   Diag.setSourceManager(this);
368 }
369 
370 SourceManager::~SourceManager() {
371   delete LineTable;
372 
373   // Delete FileEntry objects corresponding to content caches.  Since the actual
374   // content cache objects are bump pointer allocated, we just have to run the
375   // dtors, but we call the deallocate method for completeness.
376   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
377     if (MemBufferInfos[i]) {
378       MemBufferInfos[i]->~ContentCache();
379       ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
380     }
381   }
382   for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
383        I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
384     if (I->second) {
385       I->second->~ContentCache();
386       ContentCacheAlloc.Deallocate(I->second);
387     }
388   }
389 
390   llvm::DeleteContainerSeconds(MacroArgsCacheMap);
391 }
392 
393 void SourceManager::clearIDTables() {
394   MainFileID = FileID();
395   LocalSLocEntryTable.clear();
396   LoadedSLocEntryTable.clear();
397   SLocEntryLoaded.clear();
398   LastLineNoFileIDQuery = FileID();
399   LastLineNoContentCache = nullptr;
400   LastFileIDLookup = FileID();
401 
402   if (LineTable)
403     LineTable->clear();
404 
405   // Use up FileID #0 as an invalid expansion.
406   NextLocalOffset = 0;
407   CurrentLoadedOffset = MaxLoadedOffset;
408   createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
409 }
410 
411 /// getOrCreateContentCache - Create or return a cached ContentCache for the
412 /// specified file.
413 const ContentCache *
414 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
415                                        bool isSystemFile) {
416   assert(FileEnt && "Didn't specify a file entry to use?");
417 
418   // Do we already have information about this file?
419   ContentCache *&Entry = FileInfos[FileEnt];
420   if (Entry) return Entry;
421 
422   // Nope, create a new Cache entry.
423   Entry = ContentCacheAlloc.Allocate<ContentCache>();
424 
425   if (OverriddenFilesInfo) {
426     // If the file contents are overridden with contents from another file,
427     // pass that file to ContentCache.
428     llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
429         overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
430     if (overI == OverriddenFilesInfo->OverriddenFiles.end())
431       new (Entry) ContentCache(FileEnt);
432     else
433       new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
434                                                               : overI->second,
435                                overI->second);
436   } else {
437     new (Entry) ContentCache(FileEnt);
438   }
439 
440   Entry->IsSystemFile = isSystemFile;
441   Entry->IsTransient = FilesAreTransient;
442 
443   return Entry;
444 }
445 
446 
447 /// createMemBufferContentCache - Create a new ContentCache for the specified
448 ///  memory buffer.  This does no caching.
449 const ContentCache *SourceManager::createMemBufferContentCache(
450     std::unique_ptr<llvm::MemoryBuffer> Buffer) {
451   // Add a new ContentCache to the MemBufferInfos list and return it.
452   ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
453   new (Entry) ContentCache();
454   MemBufferInfos.push_back(Entry);
455   Entry->setBuffer(std::move(Buffer));
456   return Entry;
457 }
458 
459 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
460                                                       bool *Invalid) const {
461   assert(!SLocEntryLoaded[Index]);
462   if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
463     if (Invalid)
464       *Invalid = true;
465     // If the file of the SLocEntry changed we could still have loaded it.
466     if (!SLocEntryLoaded[Index]) {
467       // Try to recover; create a SLocEntry so the rest of clang can handle it.
468       LoadedSLocEntryTable[Index] = SLocEntry::get(0,
469                                  FileInfo::get(SourceLocation(),
470                                                getFakeContentCacheForRecovery(),
471                                                SrcMgr::C_User));
472     }
473   }
474 
475   return LoadedSLocEntryTable[Index];
476 }
477 
478 std::pair<int, unsigned>
479 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
480                                          unsigned TotalSize) {
481   assert(ExternalSLocEntries && "Don't have an external sloc source");
482   // Make sure we're not about to run out of source locations.
483   if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
484     return std::make_pair(0, 0);
485   LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
486   SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
487   CurrentLoadedOffset -= TotalSize;
488   int ID = LoadedSLocEntryTable.size();
489   return std::make_pair(-ID - 1, CurrentLoadedOffset);
490 }
491 
492 /// \brief As part of recovering from missing or changed content, produce a
493 /// fake, non-empty buffer.
494 llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
495   if (!FakeBufferForRecovery)
496     FakeBufferForRecovery =
497         llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
498 
499   return FakeBufferForRecovery.get();
500 }
501 
502 /// \brief As part of recovering from missing or changed content, produce a
503 /// fake content cache.
504 const SrcMgr::ContentCache *
505 SourceManager::getFakeContentCacheForRecovery() const {
506   if (!FakeContentCacheForRecovery) {
507     FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
508     FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
509                                                /*DoNotFree=*/true);
510   }
511   return FakeContentCacheForRecovery.get();
512 }
513 
514 /// \brief Returns the previous in-order FileID or an invalid FileID if there
515 /// is no previous one.
516 FileID SourceManager::getPreviousFileID(FileID FID) const {
517   if (FID.isInvalid())
518     return FileID();
519 
520   int ID = FID.ID;
521   if (ID == -1)
522     return FileID();
523 
524   if (ID > 0) {
525     if (ID-1 == 0)
526       return FileID();
527   } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
528     return FileID();
529   }
530 
531   return FileID::get(ID-1);
532 }
533 
534 /// \brief Returns the next in-order FileID or an invalid FileID if there is
535 /// no next one.
536 FileID SourceManager::getNextFileID(FileID FID) const {
537   if (FID.isInvalid())
538     return FileID();
539 
540   int ID = FID.ID;
541   if (ID > 0) {
542     if (unsigned(ID+1) >= local_sloc_entry_size())
543       return FileID();
544   } else if (ID+1 >= -1) {
545     return FileID();
546   }
547 
548   return FileID::get(ID+1);
549 }
550 
551 //===----------------------------------------------------------------------===//
552 // Methods to create new FileID's and macro expansions.
553 //===----------------------------------------------------------------------===//
554 
555 /// createFileID - Create a new FileID for the specified ContentCache and
556 /// include position.  This works regardless of whether the ContentCache
557 /// corresponds to a file or some other input source.
558 FileID SourceManager::createFileID(const ContentCache *File,
559                                    SourceLocation IncludePos,
560                                    SrcMgr::CharacteristicKind FileCharacter,
561                                    int LoadedID, unsigned LoadedOffset) {
562   if (LoadedID < 0) {
563     assert(LoadedID != -1 && "Loading sentinel FileID");
564     unsigned Index = unsigned(-LoadedID) - 2;
565     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
566     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
567     LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
568         FileInfo::get(IncludePos, File, FileCharacter));
569     SLocEntryLoaded[Index] = true;
570     return FileID::get(LoadedID);
571   }
572   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
573                                                FileInfo::get(IncludePos, File,
574                                                              FileCharacter)));
575   unsigned FileSize = File->getSize();
576   assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
577          NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
578          "Ran out of source locations!");
579   // We do a +1 here because we want a SourceLocation that means "the end of the
580   // file", e.g. for the "no newline at the end of the file" diagnostic.
581   NextLocalOffset += FileSize + 1;
582 
583   // Set LastFileIDLookup to the newly created file.  The next getFileID call is
584   // almost guaranteed to be from that file.
585   FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
586   return LastFileIDLookup = FID;
587 }
588 
589 SourceLocation
590 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
591                                           SourceLocation ExpansionLoc,
592                                           unsigned TokLength) {
593   ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
594                                                         ExpansionLoc);
595   return createExpansionLocImpl(Info, TokLength);
596 }
597 
598 SourceLocation
599 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
600                                   SourceLocation ExpansionLocStart,
601                                   SourceLocation ExpansionLocEnd,
602                                   unsigned TokLength,
603                                   int LoadedID,
604                                   unsigned LoadedOffset) {
605   ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
606                                              ExpansionLocEnd);
607   return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
608 }
609 
610 SourceLocation
611 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
612                                       unsigned TokLength,
613                                       int LoadedID,
614                                       unsigned LoadedOffset) {
615   if (LoadedID < 0) {
616     assert(LoadedID != -1 && "Loading sentinel FileID");
617     unsigned Index = unsigned(-LoadedID) - 2;
618     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
619     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
620     LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
621     SLocEntryLoaded[Index] = true;
622     return SourceLocation::getMacroLoc(LoadedOffset);
623   }
624   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
625   assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
626          NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
627          "Ran out of source locations!");
628   // See createFileID for that +1.
629   NextLocalOffset += TokLength + 1;
630   return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
631 }
632 
633 llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
634                                                           bool *Invalid) {
635   const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
636   assert(IR && "getOrCreateContentCache() cannot return NULL");
637   return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
638 }
639 
640 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
641                                          llvm::MemoryBuffer *Buffer,
642                                          bool DoNotFree) {
643   const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
644   assert(IR && "getOrCreateContentCache() cannot return NULL");
645 
646   const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
647   const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
648 
649   getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
650 }
651 
652 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
653                                          const FileEntry *NewFile) {
654   assert(SourceFile->getSize() == NewFile->getSize() &&
655          "Different sizes, use the FileManager to create a virtual file with "
656          "the correct size");
657   assert(FileInfos.count(SourceFile) == 0 &&
658          "This function should be called at the initialization stage, before "
659          "any parsing occurs.");
660   getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
661 }
662 
663 void SourceManager::disableFileContentsOverride(const FileEntry *File) {
664   if (!isFileOverridden(File))
665     return;
666 
667   const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
668   const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
669   const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
670 
671   assert(OverriddenFilesInfo);
672   OverriddenFilesInfo->OverriddenFiles.erase(File);
673   OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
674 }
675 
676 void SourceManager::setFileIsTransient(const FileEntry *File) {
677   const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
678   const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
679 }
680 
681 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
682   bool MyInvalid = false;
683   const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
684   if (!SLoc.isFile() || MyInvalid) {
685     if (Invalid)
686       *Invalid = true;
687     return "<<<<<INVALID SOURCE LOCATION>>>>>";
688   }
689 
690   llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
691       Diag, *this, SourceLocation(), &MyInvalid);
692   if (Invalid)
693     *Invalid = MyInvalid;
694 
695   if (MyInvalid)
696     return "<<<<<INVALID SOURCE LOCATION>>>>>";
697 
698   return Buf->getBuffer();
699 }
700 
701 //===----------------------------------------------------------------------===//
702 // SourceLocation manipulation methods.
703 //===----------------------------------------------------------------------===//
704 
705 /// \brief Return the FileID for a SourceLocation.
706 ///
707 /// This is the cache-miss path of getFileID. Not as hot as that function, but
708 /// still very important. It is responsible for finding the entry in the
709 /// SLocEntry tables that contains the specified location.
710 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
711   if (!SLocOffset)
712     return FileID::get(0);
713 
714   // Now it is time to search for the correct file. See where the SLocOffset
715   // sits in the global view and consult local or loaded buffers for it.
716   if (SLocOffset < NextLocalOffset)
717     return getFileIDLocal(SLocOffset);
718   return getFileIDLoaded(SLocOffset);
719 }
720 
721 /// \brief Return the FileID for a SourceLocation with a low offset.
722 ///
723 /// This function knows that the SourceLocation is in a local buffer, not a
724 /// loaded one.
725 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
726   assert(SLocOffset < NextLocalOffset && "Bad function choice");
727 
728   // After the first and second level caches, I see two common sorts of
729   // behavior: 1) a lot of searched FileID's are "near" the cached file
730   // location or are "near" the cached expansion location. 2) others are just
731   // completely random and may be a very long way away.
732   //
733   // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
734   // then we fall back to a less cache efficient, but more scalable, binary
735   // search to find the location.
736 
737   // See if this is near the file point - worst case we start scanning from the
738   // most newly created FileID.
739   const SrcMgr::SLocEntry *I;
740 
741   if (LastFileIDLookup.ID < 0 ||
742       LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
743     // Neither loc prunes our search.
744     I = LocalSLocEntryTable.end();
745   } else {
746     // Perhaps it is near the file point.
747     I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
748   }
749 
750   // Find the FileID that contains this.  "I" is an iterator that points to a
751   // FileID whose offset is known to be larger than SLocOffset.
752   unsigned NumProbes = 0;
753   while (1) {
754     --I;
755     if (I->getOffset() <= SLocOffset) {
756       FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
757 
758       // If this isn't an expansion, remember it.  We have good locality across
759       // FileID lookups.
760       if (!I->isExpansion())
761         LastFileIDLookup = Res;
762       NumLinearScans += NumProbes+1;
763       return Res;
764     }
765     if (++NumProbes == 8)
766       break;
767   }
768 
769   // Convert "I" back into an index.  We know that it is an entry whose index is
770   // larger than the offset we are looking for.
771   unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
772   // LessIndex - This is the lower bound of the range that we're searching.
773   // We know that the offset corresponding to the FileID is is less than
774   // SLocOffset.
775   unsigned LessIndex = 0;
776   NumProbes = 0;
777   while (1) {
778     bool Invalid = false;
779     unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
780     unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
781     if (Invalid)
782       return FileID::get(0);
783 
784     ++NumProbes;
785 
786     // If the offset of the midpoint is too large, chop the high side of the
787     // range to the midpoint.
788     if (MidOffset > SLocOffset) {
789       GreaterIndex = MiddleIndex;
790       continue;
791     }
792 
793     // If the middle index contains the value, succeed and return.
794     // FIXME: This could be made faster by using a function that's aware of
795     // being in the local area.
796     if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
797       FileID Res = FileID::get(MiddleIndex);
798 
799       // If this isn't a macro expansion, remember it.  We have good locality
800       // across FileID lookups.
801       if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
802         LastFileIDLookup = Res;
803       NumBinaryProbes += NumProbes;
804       return Res;
805     }
806 
807     // Otherwise, move the low-side up to the middle index.
808     LessIndex = MiddleIndex;
809   }
810 }
811 
812 /// \brief Return the FileID for a SourceLocation with a high offset.
813 ///
814 /// This function knows that the SourceLocation is in a loaded buffer, not a
815 /// local one.
816 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
817   // Sanity checking, otherwise a bug may lead to hanging in release build.
818   if (SLocOffset < CurrentLoadedOffset) {
819     assert(0 && "Invalid SLocOffset or bad function choice");
820     return FileID();
821   }
822 
823   // Essentially the same as the local case, but the loaded array is sorted
824   // in the other direction.
825 
826   // First do a linear scan from the last lookup position, if possible.
827   unsigned I;
828   int LastID = LastFileIDLookup.ID;
829   if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
830     I = 0;
831   else
832     I = (-LastID - 2) + 1;
833 
834   unsigned NumProbes;
835   for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
836     // Make sure the entry is loaded!
837     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
838     if (E.getOffset() <= SLocOffset) {
839       FileID Res = FileID::get(-int(I) - 2);
840 
841       if (!E.isExpansion())
842         LastFileIDLookup = Res;
843       NumLinearScans += NumProbes + 1;
844       return Res;
845     }
846   }
847 
848   // Linear scan failed. Do the binary search. Note the reverse sorting of the
849   // table: GreaterIndex is the one where the offset is greater, which is
850   // actually a lower index!
851   unsigned GreaterIndex = I;
852   unsigned LessIndex = LoadedSLocEntryTable.size();
853   NumProbes = 0;
854   while (1) {
855     ++NumProbes;
856     unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
857     const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
858     if (E.getOffset() == 0)
859       return FileID(); // invalid entry.
860 
861     ++NumProbes;
862 
863     if (E.getOffset() > SLocOffset) {
864       // Sanity checking, otherwise a bug may lead to hanging in release build.
865       if (GreaterIndex == MiddleIndex) {
866         assert(0 && "binary search missed the entry");
867         return FileID();
868       }
869       GreaterIndex = MiddleIndex;
870       continue;
871     }
872 
873     if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
874       FileID Res = FileID::get(-int(MiddleIndex) - 2);
875       if (!E.isExpansion())
876         LastFileIDLookup = Res;
877       NumBinaryProbes += NumProbes;
878       return Res;
879     }
880 
881     // Sanity checking, otherwise a bug may lead to hanging in release build.
882     if (LessIndex == MiddleIndex) {
883       assert(0 && "binary search missed the entry");
884       return FileID();
885     }
886     LessIndex = MiddleIndex;
887   }
888 }
889 
890 SourceLocation SourceManager::
891 getExpansionLocSlowCase(SourceLocation Loc) const {
892   do {
893     // Note: If Loc indicates an offset into a token that came from a macro
894     // expansion (e.g. the 5th character of the token) we do not want to add
895     // this offset when going to the expansion location.  The expansion
896     // location is the macro invocation, which the offset has nothing to do
897     // with.  This is unlike when we get the spelling loc, because the offset
898     // directly correspond to the token whose spelling we're inspecting.
899     Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
900   } while (!Loc.isFileID());
901 
902   return Loc;
903 }
904 
905 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
906   do {
907     std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
908     Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
909     Loc = Loc.getLocWithOffset(LocInfo.second);
910   } while (!Loc.isFileID());
911   return Loc;
912 }
913 
914 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
915   do {
916     if (isMacroArgExpansion(Loc))
917       Loc = getImmediateSpellingLoc(Loc);
918     else
919       Loc = getImmediateExpansionRange(Loc).first;
920   } while (!Loc.isFileID());
921   return Loc;
922 }
923 
924 
925 std::pair<FileID, unsigned>
926 SourceManager::getDecomposedExpansionLocSlowCase(
927                                              const SrcMgr::SLocEntry *E) const {
928   // If this is an expansion record, walk through all the expansion points.
929   FileID FID;
930   SourceLocation Loc;
931   unsigned Offset;
932   do {
933     Loc = E->getExpansion().getExpansionLocStart();
934 
935     FID = getFileID(Loc);
936     E = &getSLocEntry(FID);
937     Offset = Loc.getOffset()-E->getOffset();
938   } while (!Loc.isFileID());
939 
940   return std::make_pair(FID, Offset);
941 }
942 
943 std::pair<FileID, unsigned>
944 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
945                                                 unsigned Offset) const {
946   // If this is an expansion record, walk through all the expansion points.
947   FileID FID;
948   SourceLocation Loc;
949   do {
950     Loc = E->getExpansion().getSpellingLoc();
951     Loc = Loc.getLocWithOffset(Offset);
952 
953     FID = getFileID(Loc);
954     E = &getSLocEntry(FID);
955     Offset = Loc.getOffset()-E->getOffset();
956   } while (!Loc.isFileID());
957 
958   return std::make_pair(FID, Offset);
959 }
960 
961 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
962 /// spelling location referenced by the ID.  This is the first level down
963 /// towards the place where the characters that make up the lexed token can be
964 /// found.  This should not generally be used by clients.
965 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
966   if (Loc.isFileID()) return Loc;
967   std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
968   Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
969   return Loc.getLocWithOffset(LocInfo.second);
970 }
971 
972 
973 /// getImmediateExpansionRange - Loc is required to be an expansion location.
974 /// Return the start/end of the expansion information.
975 std::pair<SourceLocation,SourceLocation>
976 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
977   assert(Loc.isMacroID() && "Not a macro expansion loc!");
978   const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
979   return Expansion.getExpansionLocRange();
980 }
981 
982 /// getExpansionRange - Given a SourceLocation object, return the range of
983 /// tokens covered by the expansion in the ultimate file.
984 std::pair<SourceLocation,SourceLocation>
985 SourceManager::getExpansionRange(SourceLocation Loc) const {
986   if (Loc.isFileID()) return std::make_pair(Loc, Loc);
987 
988   std::pair<SourceLocation,SourceLocation> Res =
989     getImmediateExpansionRange(Loc);
990 
991   // Fully resolve the start and end locations to their ultimate expansion
992   // points.
993   while (!Res.first.isFileID())
994     Res.first = getImmediateExpansionRange(Res.first).first;
995   while (!Res.second.isFileID())
996     Res.second = getImmediateExpansionRange(Res.second).second;
997   return Res;
998 }
999 
1000 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1001                                         SourceLocation *StartLoc) const {
1002   if (!Loc.isMacroID()) return false;
1003 
1004   FileID FID = getFileID(Loc);
1005   const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1006   if (!Expansion.isMacroArgExpansion()) return false;
1007 
1008   if (StartLoc)
1009     *StartLoc = Expansion.getExpansionLocStart();
1010   return true;
1011 }
1012 
1013 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1014   if (!Loc.isMacroID()) return false;
1015 
1016   FileID FID = getFileID(Loc);
1017   const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1018   return Expansion.isMacroBodyExpansion();
1019 }
1020 
1021 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1022                                              SourceLocation *MacroBegin) const {
1023   assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1024 
1025   std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1026   if (DecompLoc.second > 0)
1027     return false; // Does not point at the start of expansion range.
1028 
1029   bool Invalid = false;
1030   const SrcMgr::ExpansionInfo &ExpInfo =
1031       getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1032   if (Invalid)
1033     return false;
1034   SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1035 
1036   if (ExpInfo.isMacroArgExpansion()) {
1037     // For macro argument expansions, check if the previous FileID is part of
1038     // the same argument expansion, in which case this Loc is not at the
1039     // beginning of the expansion.
1040     FileID PrevFID = getPreviousFileID(DecompLoc.first);
1041     if (!PrevFID.isInvalid()) {
1042       const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1043       if (Invalid)
1044         return false;
1045       if (PrevEntry.isExpansion() &&
1046           PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1047         return false;
1048     }
1049   }
1050 
1051   if (MacroBegin)
1052     *MacroBegin = ExpLoc;
1053   return true;
1054 }
1055 
1056 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1057                                                SourceLocation *MacroEnd) const {
1058   assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1059 
1060   FileID FID = getFileID(Loc);
1061   SourceLocation NextLoc = Loc.getLocWithOffset(1);
1062   if (isInFileID(NextLoc, FID))
1063     return false; // Does not point at the end of expansion range.
1064 
1065   bool Invalid = false;
1066   const SrcMgr::ExpansionInfo &ExpInfo =
1067       getSLocEntry(FID, &Invalid).getExpansion();
1068   if (Invalid)
1069     return false;
1070 
1071   if (ExpInfo.isMacroArgExpansion()) {
1072     // For macro argument expansions, check if the next FileID is part of the
1073     // same argument expansion, in which case this Loc is not at the end of the
1074     // expansion.
1075     FileID NextFID = getNextFileID(FID);
1076     if (!NextFID.isInvalid()) {
1077       const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1078       if (Invalid)
1079         return false;
1080       if (NextEntry.isExpansion() &&
1081           NextEntry.getExpansion().getExpansionLocStart() ==
1082               ExpInfo.getExpansionLocStart())
1083         return false;
1084     }
1085   }
1086 
1087   if (MacroEnd)
1088     *MacroEnd = ExpInfo.getExpansionLocEnd();
1089   return true;
1090 }
1091 
1092 
1093 //===----------------------------------------------------------------------===//
1094 // Queries about the code at a SourceLocation.
1095 //===----------------------------------------------------------------------===//
1096 
1097 /// getCharacterData - Return a pointer to the start of the specified location
1098 /// in the appropriate MemoryBuffer.
1099 const char *SourceManager::getCharacterData(SourceLocation SL,
1100                                             bool *Invalid) const {
1101   // Note that this is a hot function in the getSpelling() path, which is
1102   // heavily used by -E mode.
1103   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1104 
1105   // Note that calling 'getBuffer()' may lazily page in a source file.
1106   bool CharDataInvalid = false;
1107   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1108   if (CharDataInvalid || !Entry.isFile()) {
1109     if (Invalid)
1110       *Invalid = true;
1111 
1112     return "<<<<INVALID BUFFER>>>>";
1113   }
1114   llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1115       Diag, *this, SourceLocation(), &CharDataInvalid);
1116   if (Invalid)
1117     *Invalid = CharDataInvalid;
1118   return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
1119 }
1120 
1121 
1122 /// getColumnNumber - Return the column # for the specified file position.
1123 /// this is significantly cheaper to compute than the line number.
1124 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1125                                         bool *Invalid) const {
1126   bool MyInvalid = false;
1127   llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1128   if (Invalid)
1129     *Invalid = MyInvalid;
1130 
1131   if (MyInvalid)
1132     return 1;
1133 
1134   // It is okay to request a position just past the end of the buffer.
1135   if (FilePos > MemBuf->getBufferSize()) {
1136     if (Invalid)
1137       *Invalid = true;
1138     return 1;
1139   }
1140 
1141   // See if we just calculated the line number for this FilePos and can use
1142   // that to lookup the start of the line instead of searching for it.
1143   if (LastLineNoFileIDQuery == FID &&
1144       LastLineNoContentCache->SourceLineCache != nullptr &&
1145       LastLineNoResult < LastLineNoContentCache->NumLines) {
1146     unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1147     unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1148     unsigned LineEnd = SourceLineCache[LastLineNoResult];
1149     if (FilePos >= LineStart && FilePos < LineEnd)
1150       return FilePos - LineStart + 1;
1151   }
1152 
1153   const char *Buf = MemBuf->getBufferStart();
1154   unsigned LineStart = FilePos;
1155   while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1156     --LineStart;
1157   return FilePos-LineStart+1;
1158 }
1159 
1160 // isInvalid - Return the result of calling loc.isInvalid(), and
1161 // if Invalid is not null, set its value to same.
1162 template<typename LocType>
1163 static bool isInvalid(LocType Loc, bool *Invalid) {
1164   bool MyInvalid = Loc.isInvalid();
1165   if (Invalid)
1166     *Invalid = MyInvalid;
1167   return MyInvalid;
1168 }
1169 
1170 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1171                                                 bool *Invalid) const {
1172   if (isInvalid(Loc, Invalid)) return 0;
1173   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1174   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1175 }
1176 
1177 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1178                                                  bool *Invalid) const {
1179   if (isInvalid(Loc, Invalid)) return 0;
1180   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1181   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1182 }
1183 
1184 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1185                                                 bool *Invalid) const {
1186   PresumedLoc PLoc = getPresumedLoc(Loc);
1187   if (isInvalid(PLoc, Invalid)) return 0;
1188   return PLoc.getColumn();
1189 }
1190 
1191 #ifdef __SSE2__
1192 #include <emmintrin.h>
1193 #endif
1194 
1195 static LLVM_ATTRIBUTE_NOINLINE void
1196 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1197                    llvm::BumpPtrAllocator &Alloc,
1198                    const SourceManager &SM, bool &Invalid);
1199 static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1200                                llvm::BumpPtrAllocator &Alloc,
1201                                const SourceManager &SM, bool &Invalid) {
1202   // Note that calling 'getBuffer()' may lazily page in the file.
1203   MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
1204   if (Invalid)
1205     return;
1206 
1207   // Find the file offsets of all of the *physical* source lines.  This does
1208   // not look at trigraphs, escaped newlines, or anything else tricky.
1209   SmallVector<unsigned, 256> LineOffsets;
1210 
1211   // Line #1 starts at char 0.
1212   LineOffsets.push_back(0);
1213 
1214   const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1215   const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1216   unsigned Offs = 0;
1217   while (1) {
1218     // Skip over the contents of the line.
1219     const unsigned char *NextBuf = (const unsigned char *)Buf;
1220 
1221 #ifdef __SSE2__
1222     // Try to skip to the next newline using SSE instructions. This is very
1223     // performance sensitive for programs with lots of diagnostics and in -E
1224     // mode.
1225     __m128i CRs = _mm_set1_epi8('\r');
1226     __m128i LFs = _mm_set1_epi8('\n');
1227 
1228     // First fix up the alignment to 16 bytes.
1229     while (((uintptr_t)NextBuf & 0xF) != 0) {
1230       if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1231         goto FoundSpecialChar;
1232       ++NextBuf;
1233     }
1234 
1235     // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1236     while (NextBuf+16 <= End) {
1237       const __m128i Chunk = *(const __m128i*)NextBuf;
1238       __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1239                                  _mm_cmpeq_epi8(Chunk, LFs));
1240       unsigned Mask = _mm_movemask_epi8(Cmp);
1241 
1242       // If we found a newline, adjust the pointer and jump to the handling code.
1243       if (Mask != 0) {
1244         NextBuf += llvm::countTrailingZeros(Mask);
1245         goto FoundSpecialChar;
1246       }
1247       NextBuf += 16;
1248     }
1249 #endif
1250 
1251     while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1252       ++NextBuf;
1253 
1254 #ifdef __SSE2__
1255 FoundSpecialChar:
1256 #endif
1257     Offs += NextBuf-Buf;
1258     Buf = NextBuf;
1259 
1260     if (Buf[0] == '\n' || Buf[0] == '\r') {
1261       // If this is \n\r or \r\n, skip both characters.
1262       if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) {
1263         ++Offs;
1264         ++Buf;
1265       }
1266       ++Offs;
1267       ++Buf;
1268       LineOffsets.push_back(Offs);
1269     } else {
1270       // Otherwise, this is a null.  If end of file, exit.
1271       if (Buf == End) break;
1272       // Otherwise, skip the null.
1273       ++Offs;
1274       ++Buf;
1275     }
1276   }
1277 
1278   // Copy the offsets into the FileInfo structure.
1279   FI->NumLines = LineOffsets.size();
1280   FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1281   std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1282 }
1283 
1284 /// getLineNumber - Given a SourceLocation, return the spelling line number
1285 /// for the position indicated.  This requires building and caching a table of
1286 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1287 /// about to emit a diagnostic.
1288 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1289                                       bool *Invalid) const {
1290   if (FID.isInvalid()) {
1291     if (Invalid)
1292       *Invalid = true;
1293     return 1;
1294   }
1295 
1296   ContentCache *Content;
1297   if (LastLineNoFileIDQuery == FID)
1298     Content = LastLineNoContentCache;
1299   else {
1300     bool MyInvalid = false;
1301     const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1302     if (MyInvalid || !Entry.isFile()) {
1303       if (Invalid)
1304         *Invalid = true;
1305       return 1;
1306     }
1307 
1308     Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1309   }
1310 
1311   // If this is the first use of line information for this buffer, compute the
1312   /// SourceLineCache for it on demand.
1313   if (!Content->SourceLineCache) {
1314     bool MyInvalid = false;
1315     ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1316     if (Invalid)
1317       *Invalid = MyInvalid;
1318     if (MyInvalid)
1319       return 1;
1320   } else if (Invalid)
1321     *Invalid = false;
1322 
1323   // Okay, we know we have a line number table.  Do a binary search to find the
1324   // line number that this character position lands on.
1325   unsigned *SourceLineCache = Content->SourceLineCache;
1326   unsigned *SourceLineCacheStart = SourceLineCache;
1327   unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1328 
1329   unsigned QueriedFilePos = FilePos+1;
1330 
1331   // FIXME: I would like to be convinced that this code is worth being as
1332   // complicated as it is, binary search isn't that slow.
1333   //
1334   // If it is worth being optimized, then in my opinion it could be more
1335   // performant, simpler, and more obviously correct by just "galloping" outward
1336   // from the queried file position. In fact, this could be incorporated into a
1337   // generic algorithm such as lower_bound_with_hint.
1338   //
1339   // If someone gives me a test case where this matters, and I will do it! - DWD
1340 
1341   // If the previous query was to the same file, we know both the file pos from
1342   // that query and the line number returned.  This allows us to narrow the
1343   // search space from the entire file to something near the match.
1344   if (LastLineNoFileIDQuery == FID) {
1345     if (QueriedFilePos >= LastLineNoFilePos) {
1346       // FIXME: Potential overflow?
1347       SourceLineCache = SourceLineCache+LastLineNoResult-1;
1348 
1349       // The query is likely to be nearby the previous one.  Here we check to
1350       // see if it is within 5, 10 or 20 lines.  It can be far away in cases
1351       // where big comment blocks and vertical whitespace eat up lines but
1352       // contribute no tokens.
1353       if (SourceLineCache+5 < SourceLineCacheEnd) {
1354         if (SourceLineCache[5] > QueriedFilePos)
1355           SourceLineCacheEnd = SourceLineCache+5;
1356         else if (SourceLineCache+10 < SourceLineCacheEnd) {
1357           if (SourceLineCache[10] > QueriedFilePos)
1358             SourceLineCacheEnd = SourceLineCache+10;
1359           else if (SourceLineCache+20 < SourceLineCacheEnd) {
1360             if (SourceLineCache[20] > QueriedFilePos)
1361               SourceLineCacheEnd = SourceLineCache+20;
1362           }
1363         }
1364       }
1365     } else {
1366       if (LastLineNoResult < Content->NumLines)
1367         SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1368     }
1369   }
1370 
1371   unsigned *Pos
1372     = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1373   unsigned LineNo = Pos-SourceLineCacheStart;
1374 
1375   LastLineNoFileIDQuery = FID;
1376   LastLineNoContentCache = Content;
1377   LastLineNoFilePos = QueriedFilePos;
1378   LastLineNoResult = LineNo;
1379   return LineNo;
1380 }
1381 
1382 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1383                                               bool *Invalid) const {
1384   if (isInvalid(Loc, Invalid)) return 0;
1385   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1386   return getLineNumber(LocInfo.first, LocInfo.second);
1387 }
1388 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1389                                                bool *Invalid) const {
1390   if (isInvalid(Loc, Invalid)) return 0;
1391   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1392   return getLineNumber(LocInfo.first, LocInfo.second);
1393 }
1394 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1395                                               bool *Invalid) const {
1396   PresumedLoc PLoc = getPresumedLoc(Loc);
1397   if (isInvalid(PLoc, Invalid)) return 0;
1398   return PLoc.getLine();
1399 }
1400 
1401 /// getFileCharacteristic - return the file characteristic of the specified
1402 /// source location, indicating whether this is a normal file, a system
1403 /// header, or an "implicit extern C" system header.
1404 ///
1405 /// This state can be modified with flags on GNU linemarker directives like:
1406 ///   # 4 "foo.h" 3
1407 /// which changes all source locations in the current file after that to be
1408 /// considered to be from a system header.
1409 SrcMgr::CharacteristicKind
1410 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1411   assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1412   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1413   bool Invalid = false;
1414   const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1415   if (Invalid || !SEntry.isFile())
1416     return C_User;
1417 
1418   const SrcMgr::FileInfo &FI = SEntry.getFile();
1419 
1420   // If there are no #line directives in this file, just return the whole-file
1421   // state.
1422   if (!FI.hasLineDirectives())
1423     return FI.getFileCharacteristic();
1424 
1425   assert(LineTable && "Can't have linetable entries without a LineTable!");
1426   // See if there is a #line directive before the location.
1427   const LineEntry *Entry =
1428     LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1429 
1430   // If this is before the first line marker, use the file characteristic.
1431   if (!Entry)
1432     return FI.getFileCharacteristic();
1433 
1434   return Entry->FileKind;
1435 }
1436 
1437 /// Return the filename or buffer identifier of the buffer the location is in.
1438 /// Note that this name does not respect \#line directives.  Use getPresumedLoc
1439 /// for normal clients.
1440 StringRef SourceManager::getBufferName(SourceLocation Loc,
1441                                        bool *Invalid) const {
1442   if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1443 
1444   return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1445 }
1446 
1447 
1448 /// getPresumedLoc - This method returns the "presumed" location of a
1449 /// SourceLocation specifies.  A "presumed location" can be modified by \#line
1450 /// or GNU line marker directives.  This provides a view on the data that a
1451 /// user should see in diagnostics, for example.
1452 ///
1453 /// Note that a presumed location is always given as the expansion point of an
1454 /// expansion location, not at the spelling location.
1455 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1456                                           bool UseLineDirectives) const {
1457   if (Loc.isInvalid()) return PresumedLoc();
1458 
1459   // Presumed locations are always for expansion points.
1460   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1461 
1462   bool Invalid = false;
1463   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1464   if (Invalid || !Entry.isFile())
1465     return PresumedLoc();
1466 
1467   const SrcMgr::FileInfo &FI = Entry.getFile();
1468   const SrcMgr::ContentCache *C = FI.getContentCache();
1469 
1470   // To get the source name, first consult the FileEntry (if one exists)
1471   // before the MemBuffer as this will avoid unnecessarily paging in the
1472   // MemBuffer.
1473   StringRef Filename;
1474   if (C->OrigEntry)
1475     Filename = C->OrigEntry->getName();
1476   else
1477     Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
1478 
1479   unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1480   if (Invalid)
1481     return PresumedLoc();
1482   unsigned ColNo  = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1483   if (Invalid)
1484     return PresumedLoc();
1485 
1486   SourceLocation IncludeLoc = FI.getIncludeLoc();
1487 
1488   // If we have #line directives in this file, update and overwrite the physical
1489   // location info if appropriate.
1490   if (UseLineDirectives && FI.hasLineDirectives()) {
1491     assert(LineTable && "Can't have linetable entries without a LineTable!");
1492     // See if there is a #line directive before this.  If so, get it.
1493     if (const LineEntry *Entry =
1494           LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1495       // If the LineEntry indicates a filename, use it.
1496       if (Entry->FilenameID != -1)
1497         Filename = LineTable->getFilename(Entry->FilenameID);
1498 
1499       // Use the line number specified by the LineEntry.  This line number may
1500       // be multiple lines down from the line entry.  Add the difference in
1501       // physical line numbers from the query point and the line marker to the
1502       // total.
1503       unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1504       LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1505 
1506       // Note that column numbers are not molested by line markers.
1507 
1508       // Handle virtual #include manipulation.
1509       if (Entry->IncludeOffset) {
1510         IncludeLoc = getLocForStartOfFile(LocInfo.first);
1511         IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1512       }
1513     }
1514   }
1515 
1516   return PresumedLoc(Filename.data(), LineNo, ColNo, IncludeLoc);
1517 }
1518 
1519 /// \brief Returns whether the PresumedLoc for a given SourceLocation is
1520 /// in the main file.
1521 ///
1522 /// This computes the "presumed" location for a SourceLocation, then checks
1523 /// whether it came from a file other than the main file. This is different
1524 /// from isWrittenInMainFile() because it takes line marker directives into
1525 /// account.
1526 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1527   if (Loc.isInvalid()) return false;
1528 
1529   // Presumed locations are always for expansion points.
1530   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1531 
1532   bool Invalid = false;
1533   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1534   if (Invalid || !Entry.isFile())
1535     return false;
1536 
1537   const SrcMgr::FileInfo &FI = Entry.getFile();
1538 
1539   // Check if there is a line directive for this location.
1540   if (FI.hasLineDirectives())
1541     if (const LineEntry *Entry =
1542             LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1543       if (Entry->IncludeOffset)
1544         return false;
1545 
1546   return FI.getIncludeLoc().isInvalid();
1547 }
1548 
1549 /// \brief The size of the SLocEntry that \p FID represents.
1550 unsigned SourceManager::getFileIDSize(FileID FID) const {
1551   bool Invalid = false;
1552   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1553   if (Invalid)
1554     return 0;
1555 
1556   int ID = FID.ID;
1557   unsigned NextOffset;
1558   if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1559     NextOffset = getNextLocalOffset();
1560   else if (ID+1 == -1)
1561     NextOffset = MaxLoadedOffset;
1562   else
1563     NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1564 
1565   return NextOffset - Entry.getOffset() - 1;
1566 }
1567 
1568 //===----------------------------------------------------------------------===//
1569 // Other miscellaneous methods.
1570 //===----------------------------------------------------------------------===//
1571 
1572 /// \brief Retrieve the inode for the given file entry, if possible.
1573 ///
1574 /// This routine involves a system call, and therefore should only be used
1575 /// in non-performance-critical code.
1576 static Optional<llvm::sys::fs::UniqueID>
1577 getActualFileUID(const FileEntry *File) {
1578   if (!File)
1579     return None;
1580 
1581   llvm::sys::fs::UniqueID ID;
1582   if (llvm::sys::fs::getUniqueID(File->getName(), ID))
1583     return None;
1584 
1585   return ID;
1586 }
1587 
1588 /// \brief Get the source location for the given file:line:col triplet.
1589 ///
1590 /// If the source file is included multiple times, the source location will
1591 /// be based upon an arbitrary inclusion.
1592 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1593                                                   unsigned Line,
1594                                                   unsigned Col) const {
1595   assert(SourceFile && "Null source file!");
1596   assert(Line && Col && "Line and column should start from 1!");
1597 
1598   FileID FirstFID = translateFile(SourceFile);
1599   return translateLineCol(FirstFID, Line, Col);
1600 }
1601 
1602 /// \brief Get the FileID for the given file.
1603 ///
1604 /// If the source file is included multiple times, the FileID will be the
1605 /// first inclusion.
1606 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1607   assert(SourceFile && "Null source file!");
1608 
1609   // Find the first file ID that corresponds to the given file.
1610   FileID FirstFID;
1611 
1612   // First, check the main file ID, since it is common to look for a
1613   // location in the main file.
1614   Optional<llvm::sys::fs::UniqueID> SourceFileUID;
1615   Optional<StringRef> SourceFileName;
1616   if (MainFileID.isValid()) {
1617     bool Invalid = false;
1618     const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1619     if (Invalid)
1620       return FileID();
1621 
1622     if (MainSLoc.isFile()) {
1623       const ContentCache *MainContentCache
1624         = MainSLoc.getFile().getContentCache();
1625       if (!MainContentCache) {
1626         // Can't do anything
1627       } else if (MainContentCache->OrigEntry == SourceFile) {
1628         FirstFID = MainFileID;
1629       } else {
1630         // Fall back: check whether we have the same base name and inode
1631         // as the main file.
1632         const FileEntry *MainFile = MainContentCache->OrigEntry;
1633         SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1634         if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1635           SourceFileUID = getActualFileUID(SourceFile);
1636           if (SourceFileUID) {
1637             if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1638                     getActualFileUID(MainFile)) {
1639               if (*SourceFileUID == *MainFileUID) {
1640                 FirstFID = MainFileID;
1641                 SourceFile = MainFile;
1642               }
1643             }
1644           }
1645         }
1646       }
1647     }
1648   }
1649 
1650   if (FirstFID.isInvalid()) {
1651     // The location we're looking for isn't in the main file; look
1652     // through all of the local source locations.
1653     for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1654       bool Invalid = false;
1655       const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1656       if (Invalid)
1657         return FileID();
1658 
1659       if (SLoc.isFile() &&
1660           SLoc.getFile().getContentCache() &&
1661           SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1662         FirstFID = FileID::get(I);
1663         break;
1664       }
1665     }
1666     // If that still didn't help, try the modules.
1667     if (FirstFID.isInvalid()) {
1668       for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1669         const SLocEntry &SLoc = getLoadedSLocEntry(I);
1670         if (SLoc.isFile() &&
1671             SLoc.getFile().getContentCache() &&
1672             SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1673           FirstFID = FileID::get(-int(I) - 2);
1674           break;
1675         }
1676       }
1677     }
1678   }
1679 
1680   // If we haven't found what we want yet, try again, but this time stat()
1681   // each of the files in case the files have changed since we originally
1682   // parsed the file.
1683   if (FirstFID.isInvalid() &&
1684       (SourceFileName ||
1685        (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1686       (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
1687     bool Invalid = false;
1688     for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1689       FileID IFileID;
1690       IFileID.ID = I;
1691       const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
1692       if (Invalid)
1693         return FileID();
1694 
1695       if (SLoc.isFile()) {
1696         const ContentCache *FileContentCache
1697           = SLoc.getFile().getContentCache();
1698         const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1699                                                   : nullptr;
1700         if (Entry &&
1701             *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1702           if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1703                   getActualFileUID(Entry)) {
1704             if (*SourceFileUID == *EntryUID) {
1705               FirstFID = FileID::get(I);
1706               SourceFile = Entry;
1707               break;
1708             }
1709           }
1710         }
1711       }
1712     }
1713   }
1714 
1715   (void) SourceFile;
1716   return FirstFID;
1717 }
1718 
1719 /// \brief Get the source location in \arg FID for the given line:col.
1720 /// Returns null location if \arg FID is not a file SLocEntry.
1721 SourceLocation SourceManager::translateLineCol(FileID FID,
1722                                                unsigned Line,
1723                                                unsigned Col) const {
1724   // Lines are used as a one-based index into a zero-based array. This assert
1725   // checks for possible buffer underruns.
1726   assert(Line && Col && "Line and column should start from 1!");
1727 
1728   if (FID.isInvalid())
1729     return SourceLocation();
1730 
1731   bool Invalid = false;
1732   const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1733   if (Invalid)
1734     return SourceLocation();
1735 
1736   if (!Entry.isFile())
1737     return SourceLocation();
1738 
1739   SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1740 
1741   if (Line == 1 && Col == 1)
1742     return FileLoc;
1743 
1744   ContentCache *Content
1745     = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1746   if (!Content)
1747     return SourceLocation();
1748 
1749   // If this is the first use of line information for this buffer, compute the
1750   // SourceLineCache for it on demand.
1751   if (!Content->SourceLineCache) {
1752     bool MyInvalid = false;
1753     ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1754     if (MyInvalid)
1755       return SourceLocation();
1756   }
1757 
1758   if (Line > Content->NumLines) {
1759     unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
1760     if (Size > 0)
1761       --Size;
1762     return FileLoc.getLocWithOffset(Size);
1763   }
1764 
1765   llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
1766   unsigned FilePos = Content->SourceLineCache[Line - 1];
1767   const char *Buf = Buffer->getBufferStart() + FilePos;
1768   unsigned BufLength = Buffer->getBufferSize() - FilePos;
1769   if (BufLength == 0)
1770     return FileLoc.getLocWithOffset(FilePos);
1771 
1772   unsigned i = 0;
1773 
1774   // Check that the given column is valid.
1775   while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1776     ++i;
1777   return FileLoc.getLocWithOffset(FilePos + i);
1778 }
1779 
1780 /// \brief Compute a map of macro argument chunks to their expanded source
1781 /// location. Chunks that are not part of a macro argument will map to an
1782 /// invalid source location. e.g. if a file contains one macro argument at
1783 /// offset 100 with length 10, this is how the map will be formed:
1784 ///     0   -> SourceLocation()
1785 ///     100 -> Expanded macro arg location
1786 ///     110 -> SourceLocation()
1787 void SourceManager::computeMacroArgsCache(MacroArgsMap *&CachePtr,
1788                                           FileID FID) const {
1789   assert(FID.isValid());
1790   assert(!CachePtr);
1791 
1792   CachePtr = new MacroArgsMap();
1793   MacroArgsMap &MacroArgsCache = *CachePtr;
1794   // Initially no macro argument chunk is present.
1795   MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1796 
1797   int ID = FID.ID;
1798   while (1) {
1799     ++ID;
1800     // Stop if there are no more FileIDs to check.
1801     if (ID > 0) {
1802       if (unsigned(ID) >= local_sloc_entry_size())
1803         return;
1804     } else if (ID == -1) {
1805       return;
1806     }
1807 
1808     bool Invalid = false;
1809     const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1810     if (Invalid)
1811       return;
1812     if (Entry.isFile()) {
1813       SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1814       if (IncludeLoc.isInvalid())
1815         continue;
1816       if (!isInFileID(IncludeLoc, FID))
1817         return; // No more files/macros that may be "contained" in this file.
1818 
1819       // Skip the files/macros of the #include'd file, we only care about macros
1820       // that lexed macro arguments from our file.
1821       if (Entry.getFile().NumCreatedFIDs)
1822         ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1823       continue;
1824     }
1825 
1826     const ExpansionInfo &ExpInfo = Entry.getExpansion();
1827 
1828     if (ExpInfo.getExpansionLocStart().isFileID()) {
1829       if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1830         return; // No more files/macros that may be "contained" in this file.
1831     }
1832 
1833     if (!ExpInfo.isMacroArgExpansion())
1834       continue;
1835 
1836     associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1837                                  ExpInfo.getSpellingLoc(),
1838                                  SourceLocation::getMacroLoc(Entry.getOffset()),
1839                                  getFileIDSize(FileID::get(ID)));
1840   }
1841 }
1842 
1843 void SourceManager::associateFileChunkWithMacroArgExp(
1844                                          MacroArgsMap &MacroArgsCache,
1845                                          FileID FID,
1846                                          SourceLocation SpellLoc,
1847                                          SourceLocation ExpansionLoc,
1848                                          unsigned ExpansionLength) const {
1849   if (!SpellLoc.isFileID()) {
1850     unsigned SpellBeginOffs = SpellLoc.getOffset();
1851     unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1852 
1853     // The spelling range for this macro argument expansion can span multiple
1854     // consecutive FileID entries. Go through each entry contained in the
1855     // spelling range and if one is itself a macro argument expansion, recurse
1856     // and associate the file chunk that it represents.
1857 
1858     FileID SpellFID; // Current FileID in the spelling range.
1859     unsigned SpellRelativeOffs;
1860     std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1861     while (1) {
1862       const SLocEntry &Entry = getSLocEntry(SpellFID);
1863       unsigned SpellFIDBeginOffs = Entry.getOffset();
1864       unsigned SpellFIDSize = getFileIDSize(SpellFID);
1865       unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1866       const ExpansionInfo &Info = Entry.getExpansion();
1867       if (Info.isMacroArgExpansion()) {
1868         unsigned CurrSpellLength;
1869         if (SpellFIDEndOffs < SpellEndOffs)
1870           CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1871         else
1872           CurrSpellLength = ExpansionLength;
1873         associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1874                       Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1875                       ExpansionLoc, CurrSpellLength);
1876       }
1877 
1878       if (SpellFIDEndOffs >= SpellEndOffs)
1879         return; // we covered all FileID entries in the spelling range.
1880 
1881       // Move to the next FileID entry in the spelling range.
1882       unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1883       ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1884       ExpansionLength -= advance;
1885       ++SpellFID.ID;
1886       SpellRelativeOffs = 0;
1887     }
1888 
1889   }
1890 
1891   assert(SpellLoc.isFileID());
1892 
1893   unsigned BeginOffs;
1894   if (!isInFileID(SpellLoc, FID, &BeginOffs))
1895     return;
1896 
1897   unsigned EndOffs = BeginOffs + ExpansionLength;
1898 
1899   // Add a new chunk for this macro argument. A previous macro argument chunk
1900   // may have been lexed again, so e.g. if the map is
1901   //     0   -> SourceLocation()
1902   //     100 -> Expanded loc #1
1903   //     110 -> SourceLocation()
1904   // and we found a new macro FileID that lexed from offet 105 with length 3,
1905   // the new map will be:
1906   //     0   -> SourceLocation()
1907   //     100 -> Expanded loc #1
1908   //     105 -> Expanded loc #2
1909   //     108 -> Expanded loc #1
1910   //     110 -> SourceLocation()
1911   //
1912   // Since re-lexed macro chunks will always be the same size or less of
1913   // previous chunks, we only need to find where the ending of the new macro
1914   // chunk is mapped to and update the map with new begin/end mappings.
1915 
1916   MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1917   --I;
1918   SourceLocation EndOffsMappedLoc = I->second;
1919   MacroArgsCache[BeginOffs] = ExpansionLoc;
1920   MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1921 }
1922 
1923 /// \brief If \arg Loc points inside a function macro argument, the returned
1924 /// location will be the macro location in which the argument was expanded.
1925 /// If a macro argument is used multiple times, the expanded location will
1926 /// be at the first expansion of the argument.
1927 /// e.g.
1928 ///   MY_MACRO(foo);
1929 ///             ^
1930 /// Passing a file location pointing at 'foo', will yield a macro location
1931 /// where 'foo' was expanded into.
1932 SourceLocation
1933 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1934   if (Loc.isInvalid() || !Loc.isFileID())
1935     return Loc;
1936 
1937   FileID FID;
1938   unsigned Offset;
1939   std::tie(FID, Offset) = getDecomposedLoc(Loc);
1940   if (FID.isInvalid())
1941     return Loc;
1942 
1943   MacroArgsMap *&MacroArgsCache = MacroArgsCacheMap[FID];
1944   if (!MacroArgsCache)
1945     computeMacroArgsCache(MacroArgsCache, FID);
1946 
1947   assert(!MacroArgsCache->empty());
1948   MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1949   --I;
1950 
1951   unsigned MacroArgBeginOffs = I->first;
1952   SourceLocation MacroArgExpandedLoc = I->second;
1953   if (MacroArgExpandedLoc.isValid())
1954     return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1955 
1956   return Loc;
1957 }
1958 
1959 std::pair<FileID, unsigned>
1960 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1961   if (FID.isInvalid())
1962     return std::make_pair(FileID(), 0);
1963 
1964   // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1965 
1966   typedef std::pair<FileID, unsigned> DecompTy;
1967   typedef llvm::DenseMap<FileID, DecompTy> MapTy;
1968   std::pair<MapTy::iterator, bool>
1969     InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1970   DecompTy &DecompLoc = InsertOp.first->second;
1971   if (!InsertOp.second)
1972     return DecompLoc; // already in map.
1973 
1974   SourceLocation UpperLoc;
1975   bool Invalid = false;
1976   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1977   if (!Invalid) {
1978     if (Entry.isExpansion())
1979       UpperLoc = Entry.getExpansion().getExpansionLocStart();
1980     else
1981       UpperLoc = Entry.getFile().getIncludeLoc();
1982   }
1983 
1984   if (UpperLoc.isValid())
1985     DecompLoc = getDecomposedLoc(UpperLoc);
1986 
1987   return DecompLoc;
1988 }
1989 
1990 /// Given a decomposed source location, move it up the include/expansion stack
1991 /// to the parent source location.  If this is possible, return the decomposed
1992 /// version of the parent in Loc and return false.  If Loc is the top-level
1993 /// entry, return true and don't modify it.
1994 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1995                                    const SourceManager &SM) {
1996   std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1997   if (UpperLoc.first.isInvalid())
1998     return true; // We reached the top.
1999 
2000   Loc = UpperLoc;
2001   return false;
2002 }
2003 
2004 /// Return the cache entry for comparing the given file IDs
2005 /// for isBeforeInTranslationUnit.
2006 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
2007                                                             FileID RFID) const {
2008   // This is a magic number for limiting the cache size.  It was experimentally
2009   // derived from a small Objective-C project (where the cache filled
2010   // out to ~250 items).  We can make it larger if necessary.
2011   enum { MagicCacheSize = 300 };
2012   IsBeforeInTUCacheKey Key(LFID, RFID);
2013 
2014   // If the cache size isn't too large, do a lookup and if necessary default
2015   // construct an entry.  We can then return it to the caller for direct
2016   // use.  When they update the value, the cache will get automatically
2017   // updated as well.
2018   if (IBTUCache.size() < MagicCacheSize)
2019     return IBTUCache[Key];
2020 
2021   // Otherwise, do a lookup that will not construct a new value.
2022   InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2023   if (I != IBTUCache.end())
2024     return I->second;
2025 
2026   // Fall back to the overflow value.
2027   return IBTUCacheOverflow;
2028 }
2029 
2030 /// \brief Determines the order of 2 source locations in the translation unit.
2031 ///
2032 /// \returns true if LHS source location comes before RHS, false otherwise.
2033 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2034                                               SourceLocation RHS) const {
2035   assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2036   if (LHS == RHS)
2037     return false;
2038 
2039   std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2040   std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2041 
2042   // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2043   // is a serialized one referring to a file that was removed after we loaded
2044   // the PCH.
2045   if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2046     return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2047 
2048   // If the source locations are in the same file, just compare offsets.
2049   if (LOffs.first == ROffs.first)
2050     return LOffs.second < ROffs.second;
2051 
2052   // If we are comparing a source location with multiple locations in the same
2053   // file, we get a big win by caching the result.
2054   InBeforeInTUCacheEntry &IsBeforeInTUCache =
2055     getInBeforeInTUCache(LOffs.first, ROffs.first);
2056 
2057   // If we are comparing a source location with multiple locations in the same
2058   // file, we get a big win by caching the result.
2059   if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2060     return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
2061 
2062   // Okay, we missed in the cache, start updating the cache for this query.
2063   IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2064                           /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2065 
2066   // We need to find the common ancestor. The only way of doing this is to
2067   // build the complete include chain for one and then walking up the chain
2068   // of the other looking for a match.
2069   // We use a map from FileID to Offset to store the chain. Easier than writing
2070   // a custom set hash info that only depends on the first part of a pair.
2071   typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet;
2072   LocSet LChain;
2073   do {
2074     LChain.insert(LOffs);
2075     // We catch the case where LOffs is in a file included by ROffs and
2076     // quit early. The other way round unfortunately remains suboptimal.
2077   } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2078   LocSet::iterator I;
2079   while((I = LChain.find(ROffs.first)) == LChain.end()) {
2080     if (MoveUpIncludeHierarchy(ROffs, *this))
2081       break; // Met at topmost file.
2082   }
2083   if (I != LChain.end())
2084     LOffs = *I;
2085 
2086   // If we exited because we found a nearest common ancestor, compare the
2087   // locations within the common file and cache them.
2088   if (LOffs.first == ROffs.first) {
2089     IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2090     return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
2091   }
2092 
2093   // If we arrived here, the location is either in a built-ins buffer or
2094   // associated with global inline asm. PR5662 and PR22576 are examples.
2095 
2096   // Clear the lookup cache, it depends on a common location.
2097   IsBeforeInTUCache.clear();
2098   StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2099   StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2100   bool LIsBuiltins = LB == "<built-in>";
2101   bool RIsBuiltins = RB == "<built-in>";
2102   // Sort built-in before non-built-in.
2103   if (LIsBuiltins || RIsBuiltins) {
2104     if (LIsBuiltins != RIsBuiltins)
2105       return LIsBuiltins;
2106     // Both are in built-in buffers, but from different files. We just claim that
2107     // lower IDs come first.
2108     return LOffs.first < ROffs.first;
2109   }
2110   bool LIsAsm = LB == "<inline asm>";
2111   bool RIsAsm = RB == "<inline asm>";
2112   // Sort assembler after built-ins, but before the rest.
2113   if (LIsAsm || RIsAsm) {
2114     if (LIsAsm != RIsAsm)
2115       return RIsAsm;
2116     assert(LOffs.first == ROffs.first);
2117     return false;
2118   }
2119   bool LIsScratch = LB == "<scratch space>";
2120   bool RIsScratch = RB == "<scratch space>";
2121   // Sort scratch after inline asm, but before the rest.
2122   if (LIsScratch || RIsScratch) {
2123     if (LIsScratch != RIsScratch)
2124       return LIsScratch;
2125     return LOffs.second < ROffs.second;
2126   }
2127   llvm_unreachable("Unsortable locations found");
2128 }
2129 
2130 void SourceManager::PrintStats() const {
2131   llvm::errs() << "\n*** Source Manager Stats:\n";
2132   llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2133                << " mem buffers mapped.\n";
2134   llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2135                << llvm::capacity_in_bytes(LocalSLocEntryTable)
2136                << " bytes of capacity), "
2137                << NextLocalOffset << "B of Sloc address space used.\n";
2138   llvm::errs() << LoadedSLocEntryTable.size()
2139                << " loaded SLocEntries allocated, "
2140                << MaxLoadedOffset - CurrentLoadedOffset
2141                << "B of Sloc address space used.\n";
2142 
2143   unsigned NumLineNumsComputed = 0;
2144   unsigned NumFileBytesMapped = 0;
2145   for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2146     NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2147     NumFileBytesMapped  += I->second->getSizeBytesMapped();
2148   }
2149   unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2150 
2151   llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2152                << NumLineNumsComputed << " files with line #'s computed, "
2153                << NumMacroArgsComputed << " files with macro args computed.\n";
2154   llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2155                << NumBinaryProbes << " binary.\n";
2156 }
2157 
2158 LLVM_DUMP_METHOD void SourceManager::dump() const {
2159   llvm::raw_ostream &out = llvm::errs();
2160 
2161   auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2162                            llvm::Optional<unsigned> NextStart) {
2163     out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2164         << " <SourceLocation " << Entry.getOffset() << ":";
2165     if (NextStart)
2166       out << *NextStart << ">\n";
2167     else
2168       out << "???\?>\n";
2169     if (Entry.isFile()) {
2170       auto &FI = Entry.getFile();
2171       if (FI.NumCreatedFIDs)
2172         out << "  covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2173             << ">\n";
2174       if (FI.getIncludeLoc().isValid())
2175         out << "  included from " << FI.getIncludeLoc().getOffset() << "\n";
2176       if (auto *CC = FI.getContentCache()) {
2177         out << "  for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2178             << "\n";
2179         if (CC->BufferOverridden)
2180           out << "  contents overridden\n";
2181         if (CC->ContentsEntry != CC->OrigEntry) {
2182           out << "  contents from "
2183               << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2184               << "\n";
2185         }
2186       }
2187     } else {
2188       auto &EI = Entry.getExpansion();
2189       out << "  spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2190       out << "  macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2191           << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2192           << EI.getExpansionLocEnd().getOffset() << ">\n";
2193     }
2194   };
2195 
2196   // Dump local SLocEntries.
2197   for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2198     DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2199                   ID == NumIDs - 1 ? NextLocalOffset
2200                                    : LocalSLocEntryTable[ID + 1].getOffset());
2201   }
2202   // Dump loaded SLocEntries.
2203   llvm::Optional<unsigned> NextStart;
2204   for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2205     int ID = -(int)Index - 2;
2206     if (SLocEntryLoaded[Index]) {
2207       DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2208       NextStart = LoadedSLocEntryTable[Index].getOffset();
2209     } else {
2210       NextStart = None;
2211     }
2212   }
2213 }
2214 
2215 ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
2216 
2217 /// Return the amount of memory used by memory buffers, breaking down
2218 /// by heap-backed versus mmap'ed memory.
2219 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2220   size_t malloc_bytes = 0;
2221   size_t mmap_bytes = 0;
2222 
2223   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2224     if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2225       switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2226         case llvm::MemoryBuffer::MemoryBuffer_MMap:
2227           mmap_bytes += sized_mapped;
2228           break;
2229         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2230           malloc_bytes += sized_mapped;
2231           break;
2232       }
2233 
2234   return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2235 }
2236 
2237 size_t SourceManager::getDataStructureSizes() const {
2238   size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2239     + llvm::capacity_in_bytes(LocalSLocEntryTable)
2240     + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2241     + llvm::capacity_in_bytes(SLocEntryLoaded)
2242     + llvm::capacity_in_bytes(FileInfos);
2243 
2244   if (OverriddenFilesInfo)
2245     size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2246 
2247   return size;
2248 }
2249