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

Provided by KDAB

Privacy Policy
Learn to use CMake with our Intro Training
Find out more

source code of clang/lib/Basic/SourceManager.cpp