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