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