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