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