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