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