1 //===- SourceManager.cpp - Track and cache source files -------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the SourceManager interface.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Basic/SourceManager.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/LLVM.h"
17 #include "clang/Basic/SourceLocation.h"
18 #include "clang/Basic/SourceManagerInternals.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Capacity.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/raw_ostream.h"
44 using namespace clang;
45 using namespace SrcMgr;
46 using llvm::MemoryBuffer;
48 //===----------------------------------------------------------------------===//
49 // SourceManager Helper Classes
50 //===----------------------------------------------------------------------===//
52 ContentCache::~ContentCache() {
53 if (shouldFreeBuffer())
54 delete Buffer.getPointer();
57 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
58 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
59 unsigned ContentCache::getSizeBytesMapped() const {
60 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
63 /// Returns the kind of memory used to back the memory buffer for
64 /// this content cache. This is used for performance analysis.
65 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
66 assert(Buffer.getPointer());
68 // Should be unreachable, but keep for sanity.
69 if (!Buffer.getPointer())
70 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
72 const llvm::MemoryBuffer *buf = Buffer.getPointer();
73 return buf->getBufferKind();
76 /// getSize - Returns the size of the content encapsulated by this ContentCache.
77 /// This can be the size of the source file or the size of an arbitrary
78 /// scratch buffer. If the ContentCache encapsulates a source file, that
79 /// file is not lazily brought in from disk to satisfy this query.
80 unsigned ContentCache::getSize() const {
81 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
82 : (unsigned) ContentsEntry->getSize();
85 void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree) {
86 if (B && B == Buffer.getPointer()) {
87 assert(0 && "Replacing with the same buffer");
88 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
92 if (shouldFreeBuffer())
93 delete Buffer.getPointer();
95 Buffer.setInt((B && DoNotFree) ? DoNotFreeFlag : 0);
98 const char *ContentCache::getInvalidBOM(StringRef BufStr) {
99 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
100 // (BOM). We only support UTF-8 with and without a BOM right now. See
101 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
102 const char *InvalidBOM =
103 llvm::StringSwitch<const char *>(BufStr)
104 .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
106 .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
108 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
109 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
110 .StartsWith("\x2B\x2F\x76", "UTF-7")
111 .StartsWith("\xF7\x64\x4C", "UTF-1")
112 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
113 .StartsWith("\x0E\xFE\xFF", "SCSU")
114 .StartsWith("\xFB\xEE\x28", "BOCU-1")
115 .StartsWith("\x84\x31\x95\x33", "GB-18030")
121 const llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
124 bool *Invalid) const {
125 // Lazily create the Buffer for ContentCaches that wrap files. If we already
126 // computed it, just return what we have.
127 if (Buffer.getPointer() || !ContentsEntry) {
129 *Invalid = isBufferInvalid();
131 return Buffer.getPointer();
134 // Check that the file's size fits in an 'unsigned' (with room for a
135 // past-the-end value). This is deeply regrettable, but various parts of
136 // Clang (including elsewhere in this file!) use 'unsigned' to represent file
137 // offsets, line numbers, string literal lengths, and so on, and fail
138 // miserably on large source files.
139 if ((uint64_t)ContentsEntry->getSize() >=
140 std::numeric_limits<unsigned>::max()) {
141 // We can't make a memory buffer of the required size, so just make a small
142 // one. We should never hit a situation where we've already parsed to a
143 // later offset of the file, so it shouldn't matter that the buffer is
144 // smaller than the file.
146 llvm::MemoryBuffer::getMemBuffer("", ContentsEntry->getName())
148 if (Diag.isDiagnosticInFlight())
149 Diag.SetDelayedDiagnostic(diag::err_file_too_large,
150 ContentsEntry->getName());
152 Diag.Report(Loc, diag::err_file_too_large)
153 << ContentsEntry->getName();
155 Buffer.setInt(Buffer.getInt() | InvalidFlag);
156 if (Invalid) *Invalid = true;
157 return Buffer.getPointer();
160 auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
162 // If we were unable to open the file, then we are in an inconsistent
163 // situation where the content cache referenced a file which no longer
164 // exists. Most likely, we were using a stat cache with an invalid entry but
165 // the file could also have been removed during processing. Since we can't
166 // really deal with this situation, just create an empty buffer.
168 // FIXME: This is definitely not ideal, but our immediate clients can't
169 // currently handle returning a null entry here. Ideally we should detect
170 // that we are in an inconsistent situation and error out as quickly as
172 if (!BufferOrError) {
173 StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
174 auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
175 ContentsEntry->getSize(), "<invalid>");
176 char *Ptr = BackupBuffer->getBufferStart();
177 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
178 Ptr[i] = FillStr[i % FillStr.size()];
179 Buffer.setPointer(BackupBuffer.release());
181 if (Diag.isDiagnosticInFlight())
182 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
183 ContentsEntry->getName(),
184 BufferOrError.getError().message());
186 Diag.Report(Loc, diag::err_cannot_open_file)
187 << ContentsEntry->getName() << BufferOrError.getError().message();
189 Buffer.setInt(Buffer.getInt() | InvalidFlag);
191 if (Invalid) *Invalid = true;
192 return Buffer.getPointer();
195 Buffer.setPointer(BufferOrError->release());
197 // Check that the file's size is the same as in the file entry (which may
198 // have come from a stat cache).
199 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
200 if (Diag.isDiagnosticInFlight())
201 Diag.SetDelayedDiagnostic(diag::err_file_modified,
202 ContentsEntry->getName());
204 Diag.Report(Loc, diag::err_file_modified)
205 << ContentsEntry->getName();
207 Buffer.setInt(Buffer.getInt() | InvalidFlag);
208 if (Invalid) *Invalid = true;
209 return Buffer.getPointer();
212 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
213 // (BOM). We only support UTF-8 with and without a BOM right now. See
214 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
215 StringRef BufStr = Buffer.getPointer()->getBuffer();
216 const char *InvalidBOM = getInvalidBOM(BufStr);
219 Diag.Report(Loc, diag::err_unsupported_bom)
220 << InvalidBOM << ContentsEntry->getName();
221 Buffer.setInt(Buffer.getInt() | InvalidFlag);
225 *Invalid = isBufferInvalid();
227 return Buffer.getPointer();
230 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
231 auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
233 FilenamesByID.push_back(&*IterBool.first);
234 return IterBool.first->second;
237 /// Add a line note to the line table that indicates that there is a \#line or
238 /// GNU line marker at the specified FID/Offset location which changes the
239 /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
240 /// change the presumed \#include stack. If it is 1, this is a file entry, if
241 /// it is 2 then this is a file exit. FileKind specifies whether this is a
242 /// system header or extern C system header.
243 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
244 int FilenameID, unsigned EntryExit,
245 SrcMgr::CharacteristicKind FileKind) {
246 std::vector<LineEntry> &Entries = LineEntries[FID];
248 // An unspecified FilenameID means use the last filename if available, or the
249 // main source file otherwise.
250 if (FilenameID == -1 && !Entries.empty())
251 FilenameID = Entries.back().FilenameID;
253 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
254 "Adding line entries out of order!");
256 unsigned IncludeOffset = 0;
257 if (EntryExit == 0) { // No #include stack change.
258 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
259 } else if (EntryExit == 1) {
260 IncludeOffset = Offset-1;
261 } else if (EntryExit == 2) {
262 assert(!Entries.empty() && Entries.back().IncludeOffset &&
263 "PPDirectives should have caught case when popping empty include stack");
265 // Get the include loc of the last entries' include loc as our include loc.
267 if (const LineEntry *PrevEntry =
268 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
269 IncludeOffset = PrevEntry->IncludeOffset;
272 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
276 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
277 /// it. If there is no line entry before Offset in FID, return null.
278 const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
280 const std::vector<LineEntry> &Entries = LineEntries[FID];
281 assert(!Entries.empty() && "No #line entries for this FID after all!");
283 // It is very common for the query to be after the last #line, check this
285 if (Entries.back().FileOffset <= Offset)
286 return &Entries.back();
288 // Do a binary search to find the maximal element that is still before Offset.
289 std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
290 if (I == Entries.begin())
295 /// Add a new line entry that has already been encoded into
296 /// the internal representation of the line table.
297 void LineTableInfo::AddEntry(FileID FID,
298 const std::vector<LineEntry> &Entries) {
299 LineEntries[FID] = Entries;
302 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
303 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
304 return getLineTable().getLineTableFilenameID(Name);
307 /// AddLineNote - Add a line note to the line table for the FileID and offset
308 /// specified by Loc. If FilenameID is -1, it is considered to be
310 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
311 int FilenameID, bool IsFileEntry,
313 SrcMgr::CharacteristicKind FileKind) {
314 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
316 bool Invalid = false;
317 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
318 if (!Entry.isFile() || Invalid)
321 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
323 // Remember that this file has #line directives now if it doesn't already.
324 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
326 (void) getLineTable();
328 unsigned EntryExit = 0;
334 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
335 EntryExit, FileKind);
338 LineTableInfo &SourceManager::getLineTable() {
340 LineTable.reset(new LineTableInfo());
344 //===----------------------------------------------------------------------===//
345 // Private 'Create' methods.
346 //===----------------------------------------------------------------------===//
348 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
349 bool UserFilesAreVolatile)
350 : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
352 Diag.setSourceManager(this);
355 SourceManager::~SourceManager() {
356 // Delete FileEntry objects corresponding to content caches. Since the actual
357 // content cache objects are bump pointer allocated, we just have to run the
358 // dtors, but we call the deallocate method for completeness.
359 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
360 if (MemBufferInfos[i]) {
361 MemBufferInfos[i]->~ContentCache();
362 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
365 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
366 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
368 I->second->~ContentCache();
369 ContentCacheAlloc.Deallocate(I->second);
374 void SourceManager::clearIDTables() {
375 MainFileID = FileID();
376 LocalSLocEntryTable.clear();
377 LoadedSLocEntryTable.clear();
378 SLocEntryLoaded.clear();
379 LastLineNoFileIDQuery = FileID();
380 LastLineNoContentCache = nullptr;
381 LastFileIDLookup = FileID();
386 // Use up FileID #0 as an invalid expansion.
388 CurrentLoadedOffset = MaxLoadedOffset;
389 createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
392 void SourceManager::initializeForReplay(const SourceManager &Old) {
393 assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
395 auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
396 auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
397 Clone->OrigEntry = Cache->OrigEntry;
398 Clone->ContentsEntry = Cache->ContentsEntry;
399 Clone->BufferOverridden = Cache->BufferOverridden;
400 Clone->IsFileVolatile = Cache->IsFileVolatile;
401 Clone->IsTransient = Cache->IsTransient;
402 Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
406 // Ensure all SLocEntries are loaded from the external source.
407 for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
408 if (!Old.SLocEntryLoaded[I])
409 Old.loadSLocEntry(I, nullptr);
411 // Inherit any content cache data from the old source manager.
412 for (auto &FileInfo : Old.FileInfos) {
413 SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
416 Slot = CloneContentCache(FileInfo.second);
420 /// getOrCreateContentCache - Create or return a cached ContentCache for the
423 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
425 assert(FileEnt && "Didn't specify a file entry to use?");
427 // Do we already have information about this file?
428 ContentCache *&Entry = FileInfos[FileEnt];
429 if (Entry) return Entry;
431 // Nope, create a new Cache entry.
432 Entry = ContentCacheAlloc.Allocate<ContentCache>();
434 if (OverriddenFilesInfo) {
435 // If the file contents are overridden with contents from another file,
436 // pass that file to ContentCache.
437 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
438 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
439 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
440 new (Entry) ContentCache(FileEnt);
442 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
446 new (Entry) ContentCache(FileEnt);
449 Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;
450 Entry->IsTransient = FilesAreTransient;
455 /// Create a new ContentCache for the specified memory buffer.
456 /// This does no caching.
458 SourceManager::createMemBufferContentCache(const llvm::MemoryBuffer *Buffer,
460 // Add a new ContentCache to the MemBufferInfos list and return it.
461 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
462 new (Entry) ContentCache();
463 MemBufferInfos.push_back(Entry);
464 Entry->replaceBuffer(Buffer, DoNotFree);
468 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
469 bool *Invalid) const {
470 assert(!SLocEntryLoaded[Index]);
471 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
474 // If the file of the SLocEntry changed we could still have loaded it.
475 if (!SLocEntryLoaded[Index]) {
476 // Try to recover; create a SLocEntry so the rest of clang can handle it.
477 LoadedSLocEntryTable[Index] = SLocEntry::get(
478 0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
479 SrcMgr::C_User, ""));
483 return LoadedSLocEntryTable[Index];
486 std::pair<int, unsigned>
487 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
488 unsigned TotalSize) {
489 assert(ExternalSLocEntries && "Don't have an external sloc source");
490 // Make sure we're not about to run out of source locations.
491 if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
492 return std::make_pair(0, 0);
493 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
494 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
495 CurrentLoadedOffset -= TotalSize;
496 int ID = LoadedSLocEntryTable.size();
497 return std::make_pair(-ID - 1, CurrentLoadedOffset);
500 /// As part of recovering from missing or changed content, produce a
501 /// fake, non-empty buffer.
502 llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
503 if (!FakeBufferForRecovery)
504 FakeBufferForRecovery =
505 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
507 return FakeBufferForRecovery.get();
510 /// As part of recovering from missing or changed content, produce a
511 /// fake content cache.
512 const SrcMgr::ContentCache *
513 SourceManager::getFakeContentCacheForRecovery() const {
514 if (!FakeContentCacheForRecovery) {
515 FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
516 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
519 return FakeContentCacheForRecovery.get();
522 /// Returns the previous in-order FileID or an invalid FileID if there
523 /// is no previous one.
524 FileID SourceManager::getPreviousFileID(FileID FID) const {
535 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
539 return FileID::get(ID-1);
542 /// Returns the next in-order FileID or an invalid FileID if there is
544 FileID SourceManager::getNextFileID(FileID FID) const {
550 if (unsigned(ID+1) >= local_sloc_entry_size())
552 } else if (ID+1 >= -1) {
556 return FileID::get(ID+1);
559 //===----------------------------------------------------------------------===//
560 // Methods to create new FileID's and macro expansions.
561 //===----------------------------------------------------------------------===//
563 /// createFileID - Create a new FileID for the specified ContentCache and
564 /// include position. This works regardless of whether the ContentCache
565 /// corresponds to a file or some other input source.
566 FileID SourceManager::createFileID(const ContentCache *File, StringRef Filename,
567 SourceLocation IncludePos,
568 SrcMgr::CharacteristicKind FileCharacter,
569 int LoadedID, unsigned LoadedOffset) {
571 assert(LoadedID != -1 && "Loading sentinel FileID");
572 unsigned Index = unsigned(-LoadedID) - 2;
573 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
574 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
575 LoadedSLocEntryTable[Index] = SLocEntry::get(
576 LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
577 SLocEntryLoaded[Index] = true;
578 return FileID::get(LoadedID);
580 LocalSLocEntryTable.push_back(
581 SLocEntry::get(NextLocalOffset,
582 FileInfo::get(IncludePos, File, FileCharacter, Filename)));
583 unsigned FileSize = File->getSize();
584 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
585 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
586 "Ran out of source locations!");
587 // We do a +1 here because we want a SourceLocation that means "the end of the
588 // file", e.g. for the "no newline at the end of the file" diagnostic.
589 NextLocalOffset += FileSize + 1;
591 // Set LastFileIDLookup to the newly created file. The next getFileID call is
592 // almost guaranteed to be from that file.
593 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
594 return LastFileIDLookup = FID;
598 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
599 SourceLocation ExpansionLoc,
600 unsigned TokLength) {
601 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
603 return createExpansionLocImpl(Info, TokLength);
607 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
608 SourceLocation ExpansionLocStart,
609 SourceLocation ExpansionLocEnd,
611 bool ExpansionIsTokenRange,
613 unsigned LoadedOffset) {
614 ExpansionInfo Info = ExpansionInfo::create(
615 SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
616 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
619 SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
620 SourceLocation TokenStart,
621 SourceLocation TokenEnd) {
622 assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
623 "token spans multiple files");
624 return createExpansionLocImpl(
625 ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
626 TokenEnd.getOffset() - TokenStart.getOffset());
630 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
633 unsigned LoadedOffset) {
635 assert(LoadedID != -1 && "Loading sentinel FileID");
636 unsigned Index = unsigned(-LoadedID) - 2;
637 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
638 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
639 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
640 SLocEntryLoaded[Index] = true;
641 return SourceLocation::getMacroLoc(LoadedOffset);
643 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
644 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
645 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
646 "Ran out of source locations!");
647 // See createFileID for that +1.
648 NextLocalOffset += TokLength + 1;
649 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
652 const llvm::MemoryBuffer *
653 SourceManager::getMemoryBufferForFile(const FileEntry *File, bool *Invalid) {
654 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
655 assert(IR && "getOrCreateContentCache() cannot return NULL");
656 return IR->getBuffer(Diag, getFileManager(), SourceLocation(), Invalid);
659 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
660 llvm::MemoryBuffer *Buffer,
662 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
663 assert(IR && "getOrCreateContentCache() cannot return NULL");
665 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
666 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
668 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
671 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
672 const FileEntry *NewFile) {
673 assert(SourceFile->getSize() == NewFile->getSize() &&
674 "Different sizes, use the FileManager to create a virtual file with "
676 assert(FileInfos.count(SourceFile) == 0 &&
677 "This function should be called at the initialization stage, before "
678 "any parsing occurs.");
679 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
683 SourceManager::bypassFileContentsOverride(const FileEntry &File) {
684 assert(isFileOverridden(&File));
685 llvm::Optional<FileEntryRef> BypassFile =
686 FileMgr.getBypassFile(FileEntryRef(File.getName(), File));
688 // If the file can't be found in the FS, give up.
692 const FileEntry *FE = &BypassFile->getFileEntry();
693 (void)getOrCreateContentCache(FE);
697 void SourceManager::setFileIsTransient(const FileEntry *File) {
698 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
699 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
702 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
703 bool MyInvalid = false;
704 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
705 if (!SLoc.isFile() || MyInvalid) {
708 return "<<<<<INVALID SOURCE LOCATION>>>>>";
711 const llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
712 Diag, getFileManager(), SourceLocation(), &MyInvalid);
714 *Invalid = MyInvalid;
717 return "<<<<<INVALID SOURCE LOCATION>>>>>";
719 return Buf->getBuffer();
722 //===----------------------------------------------------------------------===//
723 // SourceLocation manipulation methods.
724 //===----------------------------------------------------------------------===//
726 /// Return the FileID for a SourceLocation.
728 /// This is the cache-miss path of getFileID. Not as hot as that function, but
729 /// still very important. It is responsible for finding the entry in the
730 /// SLocEntry tables that contains the specified location.
731 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
733 return FileID::get(0);
735 // Now it is time to search for the correct file. See where the SLocOffset
736 // sits in the global view and consult local or loaded buffers for it.
737 if (SLocOffset < NextLocalOffset)
738 return getFileIDLocal(SLocOffset);
739 return getFileIDLoaded(SLocOffset);
742 /// Return the FileID for a SourceLocation with a low offset.
744 /// This function knows that the SourceLocation is in a local buffer, not a
746 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
747 assert(SLocOffset < NextLocalOffset && "Bad function choice");
749 // After the first and second level caches, I see two common sorts of
750 // behavior: 1) a lot of searched FileID's are "near" the cached file
751 // location or are "near" the cached expansion location. 2) others are just
752 // completely random and may be a very long way away.
754 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
755 // then we fall back to a less cache efficient, but more scalable, binary
756 // search to find the location.
758 // See if this is near the file point - worst case we start scanning from the
759 // most newly created FileID.
760 const SrcMgr::SLocEntry *I;
762 if (LastFileIDLookup.ID < 0 ||
763 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
764 // Neither loc prunes our search.
765 I = LocalSLocEntryTable.end();
767 // Perhaps it is near the file point.
768 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
771 // Find the FileID that contains this. "I" is an iterator that points to a
772 // FileID whose offset is known to be larger than SLocOffset.
773 unsigned NumProbes = 0;
776 if (I->getOffset() <= SLocOffset) {
777 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
779 // If this isn't an expansion, remember it. We have good locality across
781 if (!I->isExpansion())
782 LastFileIDLookup = Res;
783 NumLinearScans += NumProbes+1;
786 if (++NumProbes == 8)
790 // Convert "I" back into an index. We know that it is an entry whose index is
791 // larger than the offset we are looking for.
792 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
793 // LessIndex - This is the lower bound of the range that we're searching.
794 // We know that the offset corresponding to the FileID is is less than
796 unsigned LessIndex = 0;
799 bool Invalid = false;
800 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
801 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
803 return FileID::get(0);
807 // If the offset of the midpoint is too large, chop the high side of the
808 // range to the midpoint.
809 if (MidOffset > SLocOffset) {
810 GreaterIndex = MiddleIndex;
814 // If the middle index contains the value, succeed and return.
815 // FIXME: This could be made faster by using a function that's aware of
816 // being in the local area.
817 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
818 FileID Res = FileID::get(MiddleIndex);
820 // If this isn't a macro expansion, remember it. We have good locality
821 // across FileID lookups.
822 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
823 LastFileIDLookup = Res;
824 NumBinaryProbes += NumProbes;
828 // Otherwise, move the low-side up to the middle index.
829 LessIndex = MiddleIndex;
833 /// Return the FileID for a SourceLocation with a high offset.
835 /// This function knows that the SourceLocation is in a loaded buffer, not a
837 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
838 // Sanity checking, otherwise a bug may lead to hanging in release build.
839 if (SLocOffset < CurrentLoadedOffset) {
840 assert(0 && "Invalid SLocOffset or bad function choice");
844 // Essentially the same as the local case, but the loaded array is sorted
845 // in the other direction.
847 // First do a linear scan from the last lookup position, if possible.
849 int LastID = LastFileIDLookup.ID;
850 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
853 I = (-LastID - 2) + 1;
856 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
857 // Make sure the entry is loaded!
858 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
859 if (E.getOffset() <= SLocOffset) {
860 FileID Res = FileID::get(-int(I) - 2);
862 if (!E.isExpansion())
863 LastFileIDLookup = Res;
864 NumLinearScans += NumProbes + 1;
869 // Linear scan failed. Do the binary search. Note the reverse sorting of the
870 // table: GreaterIndex is the one where the offset is greater, which is
871 // actually a lower index!
872 unsigned GreaterIndex = I;
873 unsigned LessIndex = LoadedSLocEntryTable.size();
877 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
878 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
879 if (E.getOffset() == 0)
880 return FileID(); // invalid entry.
884 if (E.getOffset() > SLocOffset) {
885 // Sanity checking, otherwise a bug may lead to hanging in release build.
886 if (GreaterIndex == MiddleIndex) {
887 assert(0 && "binary search missed the entry");
890 GreaterIndex = MiddleIndex;
894 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
895 FileID Res = FileID::get(-int(MiddleIndex) - 2);
896 if (!E.isExpansion())
897 LastFileIDLookup = Res;
898 NumBinaryProbes += NumProbes;
902 // Sanity checking, otherwise a bug may lead to hanging in release build.
903 if (LessIndex == MiddleIndex) {
904 assert(0 && "binary search missed the entry");
907 LessIndex = MiddleIndex;
911 SourceLocation SourceManager::
912 getExpansionLocSlowCase(SourceLocation Loc) const {
914 // Note: If Loc indicates an offset into a token that came from a macro
915 // expansion (e.g. the 5th character of the token) we do not want to add
916 // this offset when going to the expansion location. The expansion
917 // location is the macro invocation, which the offset has nothing to do
918 // with. This is unlike when we get the spelling loc, because the offset
919 // directly correspond to the token whose spelling we're inspecting.
920 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
921 } while (!Loc.isFileID());
926 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
928 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
929 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
930 Loc = Loc.getLocWithOffset(LocInfo.second);
931 } while (!Loc.isFileID());
935 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
937 if (isMacroArgExpansion(Loc))
938 Loc = getImmediateSpellingLoc(Loc);
940 Loc = getImmediateExpansionRange(Loc).getBegin();
941 } while (!Loc.isFileID());
946 std::pair<FileID, unsigned>
947 SourceManager::getDecomposedExpansionLocSlowCase(
948 const SrcMgr::SLocEntry *E) const {
949 // If this is an expansion record, walk through all the expansion points.
954 Loc = E->getExpansion().getExpansionLocStart();
956 FID = getFileID(Loc);
957 E = &getSLocEntry(FID);
958 Offset = Loc.getOffset()-E->getOffset();
959 } while (!Loc.isFileID());
961 return std::make_pair(FID, Offset);
964 std::pair<FileID, unsigned>
965 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
966 unsigned Offset) const {
967 // If this is an expansion record, walk through all the expansion points.
971 Loc = E->getExpansion().getSpellingLoc();
972 Loc = Loc.getLocWithOffset(Offset);
974 FID = getFileID(Loc);
975 E = &getSLocEntry(FID);
976 Offset = Loc.getOffset()-E->getOffset();
977 } while (!Loc.isFileID());
979 return std::make_pair(FID, Offset);
982 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
983 /// spelling location referenced by the ID. This is the first level down
984 /// towards the place where the characters that make up the lexed token can be
985 /// found. This should not generally be used by clients.
986 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
987 if (Loc.isFileID()) return Loc;
988 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
989 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
990 return Loc.getLocWithOffset(LocInfo.second);
993 /// getImmediateExpansionRange - Loc is required to be an expansion location.
994 /// Return the start/end of the expansion information.
996 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
997 assert(Loc.isMacroID() && "Not a macro expansion loc!");
998 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
999 return Expansion.getExpansionLocRange();
1002 SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
1003 while (isMacroArgExpansion(Loc))
1004 Loc = getImmediateSpellingLoc(Loc);
1008 /// getExpansionRange - Given a SourceLocation object, return the range of
1009 /// tokens covered by the expansion in the ultimate file.
1010 CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
1012 return CharSourceRange(SourceRange(Loc, Loc), true);
1014 CharSourceRange Res = getImmediateExpansionRange(Loc);
1016 // Fully resolve the start and end locations to their ultimate expansion
1018 while (!Res.getBegin().isFileID())
1019 Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
1020 while (!Res.getEnd().isFileID()) {
1021 CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
1022 Res.setEnd(EndRange.getEnd());
1023 Res.setTokenRange(EndRange.isTokenRange());
1028 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1029 SourceLocation *StartLoc) const {
1030 if (!Loc.isMacroID()) return false;
1032 FileID FID = getFileID(Loc);
1033 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1034 if (!Expansion.isMacroArgExpansion()) return false;
1037 *StartLoc = Expansion.getExpansionLocStart();
1041 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1042 if (!Loc.isMacroID()) return false;
1044 FileID FID = getFileID(Loc);
1045 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1046 return Expansion.isMacroBodyExpansion();
1049 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1050 SourceLocation *MacroBegin) const {
1051 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1053 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1054 if (DecompLoc.second > 0)
1055 return false; // Does not point at the start of expansion range.
1057 bool Invalid = false;
1058 const SrcMgr::ExpansionInfo &ExpInfo =
1059 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1062 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1064 if (ExpInfo.isMacroArgExpansion()) {
1065 // For macro argument expansions, check if the previous FileID is part of
1066 // the same argument expansion, in which case this Loc is not at the
1067 // beginning of the expansion.
1068 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1069 if (!PrevFID.isInvalid()) {
1070 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1073 if (PrevEntry.isExpansion() &&
1074 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1080 *MacroBegin = ExpLoc;
1084 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1085 SourceLocation *MacroEnd) const {
1086 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1088 FileID FID = getFileID(Loc);
1089 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1090 if (isInFileID(NextLoc, FID))
1091 return false; // Does not point at the end of expansion range.
1093 bool Invalid = false;
1094 const SrcMgr::ExpansionInfo &ExpInfo =
1095 getSLocEntry(FID, &Invalid).getExpansion();
1099 if (ExpInfo.isMacroArgExpansion()) {
1100 // For macro argument expansions, check if the next FileID is part of the
1101 // same argument expansion, in which case this Loc is not at the end of the
1103 FileID NextFID = getNextFileID(FID);
1104 if (!NextFID.isInvalid()) {
1105 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1108 if (NextEntry.isExpansion() &&
1109 NextEntry.getExpansion().getExpansionLocStart() ==
1110 ExpInfo.getExpansionLocStart())
1116 *MacroEnd = ExpInfo.getExpansionLocEnd();
1120 //===----------------------------------------------------------------------===//
1121 // Queries about the code at a SourceLocation.
1122 //===----------------------------------------------------------------------===//
1124 /// getCharacterData - Return a pointer to the start of the specified location
1125 /// in the appropriate MemoryBuffer.
1126 const char *SourceManager::getCharacterData(SourceLocation SL,
1127 bool *Invalid) const {
1128 // Note that this is a hot function in the getSpelling() path, which is
1129 // heavily used by -E mode.
1130 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1132 // Note that calling 'getBuffer()' may lazily page in a source file.
1133 bool CharDataInvalid = false;
1134 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1135 if (CharDataInvalid || !Entry.isFile()) {
1139 return "<<<<INVALID BUFFER>>>>";
1141 const llvm::MemoryBuffer *Buffer =
1142 Entry.getFile().getContentCache()->getBuffer(
1143 Diag, getFileManager(), SourceLocation(), &CharDataInvalid);
1145 *Invalid = CharDataInvalid;
1146 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
1149 /// getColumnNumber - Return the column # for the specified file position.
1150 /// this is significantly cheaper to compute than the line number.
1151 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1152 bool *Invalid) const {
1153 bool MyInvalid = false;
1154 const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1156 *Invalid = MyInvalid;
1161 // It is okay to request a position just past the end of the buffer.
1162 if (FilePos > MemBuf->getBufferSize()) {
1168 const char *Buf = MemBuf->getBufferStart();
1169 // See if we just calculated the line number for this FilePos and can use
1170 // that to lookup the start of the line instead of searching for it.
1171 if (LastLineNoFileIDQuery == FID &&
1172 LastLineNoContentCache->SourceLineCache != nullptr &&
1173 LastLineNoResult < LastLineNoContentCache->NumLines) {
1174 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1175 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1176 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1177 if (FilePos >= LineStart && FilePos < LineEnd) {
1178 // LineEnd is the LineStart of the next line.
1179 // A line ends with separator LF or CR+LF on Windows.
1180 // FilePos might point to the last separator,
1181 // but we need a column number at most 1 + the last column.
1182 if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1183 if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1186 return FilePos - LineStart + 1;
1190 unsigned LineStart = FilePos;
1191 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1193 return FilePos-LineStart+1;
1196 // isInvalid - Return the result of calling loc.isInvalid(), and
1197 // if Invalid is not null, set its value to same.
1198 template<typename LocType>
1199 static bool isInvalid(LocType Loc, bool *Invalid) {
1200 bool MyInvalid = Loc.isInvalid();
1202 *Invalid = MyInvalid;
1206 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1207 bool *Invalid) const {
1208 if (isInvalid(Loc, Invalid)) return 0;
1209 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1210 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1213 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1214 bool *Invalid) const {
1215 if (isInvalid(Loc, Invalid)) return 0;
1216 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1217 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1220 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1221 bool *Invalid) const {
1222 PresumedLoc PLoc = getPresumedLoc(Loc);
1223 if (isInvalid(PLoc, Invalid)) return 0;
1224 return PLoc.getColumn();
1228 #include <emmintrin.h>
1231 static LLVM_ATTRIBUTE_NOINLINE void
1232 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1233 llvm::BumpPtrAllocator &Alloc,
1234 const SourceManager &SM, bool &Invalid);
1235 static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1236 llvm::BumpPtrAllocator &Alloc,
1237 const SourceManager &SM, bool &Invalid) {
1238 // Note that calling 'getBuffer()' may lazily page in the file.
1239 const MemoryBuffer *Buffer =
1240 FI->getBuffer(Diag, SM.getFileManager(), SourceLocation(), &Invalid);
1244 // Find the file offsets of all of the *physical* source lines. This does
1245 // not look at trigraphs, escaped newlines, or anything else tricky.
1246 SmallVector<unsigned, 256> LineOffsets;
1248 // Line #1 starts at char 0.
1249 LineOffsets.push_back(0);
1251 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1252 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1253 const std::size_t BufLen = End - Buf;
1255 while (I < BufLen) {
1256 if (Buf[I] == '\n') {
1257 LineOffsets.push_back(I + 1);
1258 } else if (Buf[I] == '\r') {
1259 // If this is \r\n, skip both characters.
1260 if (I + 1 < BufLen && Buf[I + 1] == '\n')
1262 LineOffsets.push_back(I + 1);
1267 // Copy the offsets into the FileInfo structure.
1268 FI->NumLines = LineOffsets.size();
1269 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1270 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1273 /// getLineNumber - Given a SourceLocation, return the spelling line number
1274 /// for the position indicated. This requires building and caching a table of
1275 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1276 /// about to emit a diagnostic.
1277 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1278 bool *Invalid) const {
1279 if (FID.isInvalid()) {
1285 ContentCache *Content;
1286 if (LastLineNoFileIDQuery == FID)
1287 Content = LastLineNoContentCache;
1289 bool MyInvalid = false;
1290 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1291 if (MyInvalid || !Entry.isFile()) {
1297 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1300 // If this is the first use of line information for this buffer, compute the
1301 /// SourceLineCache for it on demand.
1302 if (!Content->SourceLineCache) {
1303 bool MyInvalid = false;
1304 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1306 *Invalid = MyInvalid;
1312 // Okay, we know we have a line number table. Do a binary search to find the
1313 // line number that this character position lands on.
1314 unsigned *SourceLineCache = Content->SourceLineCache;
1315 unsigned *SourceLineCacheStart = SourceLineCache;
1316 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1318 unsigned QueriedFilePos = FilePos+1;
1320 // FIXME: I would like to be convinced that this code is worth being as
1321 // complicated as it is, binary search isn't that slow.
1323 // If it is worth being optimized, then in my opinion it could be more
1324 // performant, simpler, and more obviously correct by just "galloping" outward
1325 // from the queried file position. In fact, this could be incorporated into a
1326 // generic algorithm such as lower_bound_with_hint.
1328 // If someone gives me a test case where this matters, and I will do it! - DWD
1330 // If the previous query was to the same file, we know both the file pos from
1331 // that query and the line number returned. This allows us to narrow the
1332 // search space from the entire file to something near the match.
1333 if (LastLineNoFileIDQuery == FID) {
1334 if (QueriedFilePos >= LastLineNoFilePos) {
1335 // FIXME: Potential overflow?
1336 SourceLineCache = SourceLineCache+LastLineNoResult-1;
1338 // The query is likely to be nearby the previous one. Here we check to
1339 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1340 // where big comment blocks and vertical whitespace eat up lines but
1341 // contribute no tokens.
1342 if (SourceLineCache+5 < SourceLineCacheEnd) {
1343 if (SourceLineCache[5] > QueriedFilePos)
1344 SourceLineCacheEnd = SourceLineCache+5;
1345 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1346 if (SourceLineCache[10] > QueriedFilePos)
1347 SourceLineCacheEnd = SourceLineCache+10;
1348 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1349 if (SourceLineCache[20] > QueriedFilePos)
1350 SourceLineCacheEnd = SourceLineCache+20;
1355 if (LastLineNoResult < Content->NumLines)
1356 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1361 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1362 unsigned LineNo = Pos-SourceLineCacheStart;
1364 LastLineNoFileIDQuery = FID;
1365 LastLineNoContentCache = Content;
1366 LastLineNoFilePos = QueriedFilePos;
1367 LastLineNoResult = LineNo;
1371 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1372 bool *Invalid) const {
1373 if (isInvalid(Loc, Invalid)) return 0;
1374 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1375 return getLineNumber(LocInfo.first, LocInfo.second);
1377 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1378 bool *Invalid) const {
1379 if (isInvalid(Loc, Invalid)) return 0;
1380 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1381 return getLineNumber(LocInfo.first, LocInfo.second);
1383 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1384 bool *Invalid) const {
1385 PresumedLoc PLoc = getPresumedLoc(Loc);
1386 if (isInvalid(PLoc, Invalid)) return 0;
1387 return PLoc.getLine();
1390 /// getFileCharacteristic - return the file characteristic of the specified
1391 /// source location, indicating whether this is a normal file, a system
1392 /// header, or an "implicit extern C" system header.
1394 /// This state can be modified with flags on GNU linemarker directives like:
1396 /// which changes all source locations in the current file after that to be
1397 /// considered to be from a system header.
1398 SrcMgr::CharacteristicKind
1399 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1400 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1401 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1402 bool Invalid = false;
1403 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1404 if (Invalid || !SEntry.isFile())
1407 const SrcMgr::FileInfo &FI = SEntry.getFile();
1409 // If there are no #line directives in this file, just return the whole-file
1411 if (!FI.hasLineDirectives())
1412 return FI.getFileCharacteristic();
1414 assert(LineTable && "Can't have linetable entries without a LineTable!");
1415 // See if there is a #line directive before the location.
1416 const LineEntry *Entry =
1417 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1419 // If this is before the first line marker, use the file characteristic.
1421 return FI.getFileCharacteristic();
1423 return Entry->FileKind;
1426 /// Return the filename or buffer identifier of the buffer the location is in.
1427 /// Note that this name does not respect \#line directives. Use getPresumedLoc
1428 /// for normal clients.
1429 StringRef SourceManager::getBufferName(SourceLocation Loc,
1430 bool *Invalid) const {
1431 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1433 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1436 /// getPresumedLoc - This method returns the "presumed" location of a
1437 /// SourceLocation specifies. A "presumed location" can be modified by \#line
1438 /// or GNU line marker directives. This provides a view on the data that a
1439 /// user should see in diagnostics, for example.
1441 /// Note that a presumed location is always given as the expansion point of an
1442 /// expansion location, not at the spelling location.
1443 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1444 bool UseLineDirectives) const {
1445 if (Loc.isInvalid()) return PresumedLoc();
1447 // Presumed locations are always for expansion points.
1448 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1450 bool Invalid = false;
1451 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1452 if (Invalid || !Entry.isFile())
1453 return PresumedLoc();
1455 const SrcMgr::FileInfo &FI = Entry.getFile();
1456 const SrcMgr::ContentCache *C = FI.getContentCache();
1458 // To get the source name, first consult the FileEntry (if one exists)
1459 // before the MemBuffer as this will avoid unnecessarily paging in the
1461 FileID FID = LocInfo.first;
1464 Filename = C->OrigEntry->getName();
1466 Filename = C->getBuffer(Diag, getFileManager())->getBufferIdentifier();
1468 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1470 return PresumedLoc();
1471 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1473 return PresumedLoc();
1475 SourceLocation IncludeLoc = FI.getIncludeLoc();
1477 // If we have #line directives in this file, update and overwrite the physical
1478 // location info if appropriate.
1479 if (UseLineDirectives && FI.hasLineDirectives()) {
1480 assert(LineTable && "Can't have linetable entries without a LineTable!");
1481 // See if there is a #line directive before this. If so, get it.
1482 if (const LineEntry *Entry =
1483 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1484 // If the LineEntry indicates a filename, use it.
1485 if (Entry->FilenameID != -1) {
1486 Filename = LineTable->getFilename(Entry->FilenameID);
1487 // The contents of files referenced by #line are not in the
1489 FID = FileID::get(0);
1492 // Use the line number specified by the LineEntry. This line number may
1493 // be multiple lines down from the line entry. Add the difference in
1494 // physical line numbers from the query point and the line marker to the
1496 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1497 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1499 // Note that column numbers are not molested by line markers.
1501 // Handle virtual #include manipulation.
1502 if (Entry->IncludeOffset) {
1503 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1504 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1509 return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1512 /// Returns whether the PresumedLoc for a given SourceLocation is
1513 /// in the main file.
1515 /// This computes the "presumed" location for a SourceLocation, then checks
1516 /// whether it came from a file other than the main file. This is different
1517 /// from isWrittenInMainFile() because it takes line marker directives into
1519 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1520 if (Loc.isInvalid()) return false;
1522 // Presumed locations are always for expansion points.
1523 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1525 bool Invalid = false;
1526 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1527 if (Invalid || !Entry.isFile())
1530 const SrcMgr::FileInfo &FI = Entry.getFile();
1532 // Check if there is a line directive for this location.
1533 if (FI.hasLineDirectives())
1534 if (const LineEntry *Entry =
1535 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1536 if (Entry->IncludeOffset)
1539 return FI.getIncludeLoc().isInvalid();
1542 /// The size of the SLocEntry that \p FID represents.
1543 unsigned SourceManager::getFileIDSize(FileID FID) const {
1544 bool Invalid = false;
1545 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1550 unsigned NextOffset;
1551 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1552 NextOffset = getNextLocalOffset();
1553 else if (ID+1 == -1)
1554 NextOffset = MaxLoadedOffset;
1556 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1558 return NextOffset - Entry.getOffset() - 1;
1561 //===----------------------------------------------------------------------===//
1562 // Other miscellaneous methods.
1563 //===----------------------------------------------------------------------===//
1565 /// Get the source location for the given file:line:col triplet.
1567 /// If the source file is included multiple times, the source location will
1568 /// be based upon an arbitrary inclusion.
1569 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1571 unsigned Col) const {
1572 assert(SourceFile && "Null source file!");
1573 assert(Line && Col && "Line and column should start from 1!");
1575 FileID FirstFID = translateFile(SourceFile);
1576 return translateLineCol(FirstFID, Line, Col);
1579 /// Get the FileID for the given file.
1581 /// If the source file is included multiple times, the FileID will be the
1582 /// first inclusion.
1583 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1584 assert(SourceFile && "Null source file!");
1586 // First, check the main file ID, since it is common to look for a
1587 // location in the main file.
1588 if (MainFileID.isValid()) {
1589 bool Invalid = false;
1590 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1594 if (MainSLoc.isFile()) {
1595 const ContentCache *MainContentCache =
1596 MainSLoc.getFile().getContentCache();
1597 if (MainContentCache && MainContentCache->OrigEntry == SourceFile)
1602 // The location we're looking for isn't in the main file; look
1603 // through all of the local source locations.
1604 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1605 bool Invalid = false;
1606 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1610 if (SLoc.isFile() && SLoc.getFile().getContentCache() &&
1611 SLoc.getFile().getContentCache()->OrigEntry == SourceFile)
1612 return FileID::get(I);
1615 // If that still didn't help, try the modules.
1616 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1617 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1618 if (SLoc.isFile() && SLoc.getFile().getContentCache() &&
1619 SLoc.getFile().getContentCache()->OrigEntry == SourceFile)
1620 return FileID::get(-int(I) - 2);
1626 /// Get the source location in \arg FID for the given line:col.
1627 /// Returns null location if \arg FID is not a file SLocEntry.
1628 SourceLocation SourceManager::translateLineCol(FileID FID,
1630 unsigned Col) const {
1631 // Lines are used as a one-based index into a zero-based array. This assert
1632 // checks for possible buffer underruns.
1633 assert(Line && Col && "Line and column should start from 1!");
1635 if (FID.isInvalid())
1636 return SourceLocation();
1638 bool Invalid = false;
1639 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1641 return SourceLocation();
1643 if (!Entry.isFile())
1644 return SourceLocation();
1646 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1648 if (Line == 1 && Col == 1)
1651 ContentCache *Content
1652 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1654 return SourceLocation();
1656 // If this is the first use of line information for this buffer, compute the
1657 // SourceLineCache for it on demand.
1658 if (!Content->SourceLineCache) {
1659 bool MyInvalid = false;
1660 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1662 return SourceLocation();
1665 if (Line > Content->NumLines) {
1666 unsigned Size = Content->getBuffer(Diag, getFileManager())->getBufferSize();
1669 return FileLoc.getLocWithOffset(Size);
1672 const llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, getFileManager());
1673 unsigned FilePos = Content->SourceLineCache[Line - 1];
1674 const char *Buf = Buffer->getBufferStart() + FilePos;
1675 unsigned BufLength = Buffer->getBufferSize() - FilePos;
1677 return FileLoc.getLocWithOffset(FilePos);
1681 // Check that the given column is valid.
1682 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1684 return FileLoc.getLocWithOffset(FilePos + i);
1687 /// Compute a map of macro argument chunks to their expanded source
1688 /// location. Chunks that are not part of a macro argument will map to an
1689 /// invalid source location. e.g. if a file contains one macro argument at
1690 /// offset 100 with length 10, this is how the map will be formed:
1691 /// 0 -> SourceLocation()
1692 /// 100 -> Expanded macro arg location
1693 /// 110 -> SourceLocation()
1694 void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1696 assert(FID.isValid());
1698 // Initially no macro argument chunk is present.
1699 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1704 // Stop if there are no more FileIDs to check.
1706 if (unsigned(ID) >= local_sloc_entry_size())
1708 } else if (ID == -1) {
1712 bool Invalid = false;
1713 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1716 if (Entry.isFile()) {
1717 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1718 if (IncludeLoc.isInvalid())
1720 if (!isInFileID(IncludeLoc, FID))
1721 return; // No more files/macros that may be "contained" in this file.
1723 // Skip the files/macros of the #include'd file, we only care about macros
1724 // that lexed macro arguments from our file.
1725 if (Entry.getFile().NumCreatedFIDs)
1726 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1730 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1732 if (ExpInfo.getExpansionLocStart().isFileID()) {
1733 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1734 return; // No more files/macros that may be "contained" in this file.
1737 if (!ExpInfo.isMacroArgExpansion())
1740 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1741 ExpInfo.getSpellingLoc(),
1742 SourceLocation::getMacroLoc(Entry.getOffset()),
1743 getFileIDSize(FileID::get(ID)));
1747 void SourceManager::associateFileChunkWithMacroArgExp(
1748 MacroArgsMap &MacroArgsCache,
1750 SourceLocation SpellLoc,
1751 SourceLocation ExpansionLoc,
1752 unsigned ExpansionLength) const {
1753 if (!SpellLoc.isFileID()) {
1754 unsigned SpellBeginOffs = SpellLoc.getOffset();
1755 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1757 // The spelling range for this macro argument expansion can span multiple
1758 // consecutive FileID entries. Go through each entry contained in the
1759 // spelling range and if one is itself a macro argument expansion, recurse
1760 // and associate the file chunk that it represents.
1762 FileID SpellFID; // Current FileID in the spelling range.
1763 unsigned SpellRelativeOffs;
1764 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1766 const SLocEntry &Entry = getSLocEntry(SpellFID);
1767 unsigned SpellFIDBeginOffs = Entry.getOffset();
1768 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1769 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1770 const ExpansionInfo &Info = Entry.getExpansion();
1771 if (Info.isMacroArgExpansion()) {
1772 unsigned CurrSpellLength;
1773 if (SpellFIDEndOffs < SpellEndOffs)
1774 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1776 CurrSpellLength = ExpansionLength;
1777 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1778 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1779 ExpansionLoc, CurrSpellLength);
1782 if (SpellFIDEndOffs >= SpellEndOffs)
1783 return; // we covered all FileID entries in the spelling range.
1785 // Move to the next FileID entry in the spelling range.
1786 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1787 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1788 ExpansionLength -= advance;
1790 SpellRelativeOffs = 0;
1794 assert(SpellLoc.isFileID());
1797 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1800 unsigned EndOffs = BeginOffs + ExpansionLength;
1802 // Add a new chunk for this macro argument. A previous macro argument chunk
1803 // may have been lexed again, so e.g. if the map is
1804 // 0 -> SourceLocation()
1805 // 100 -> Expanded loc #1
1806 // 110 -> SourceLocation()
1807 // and we found a new macro FileID that lexed from offset 105 with length 3,
1808 // the new map will be:
1809 // 0 -> SourceLocation()
1810 // 100 -> Expanded loc #1
1811 // 105 -> Expanded loc #2
1812 // 108 -> Expanded loc #1
1813 // 110 -> SourceLocation()
1815 // Since re-lexed macro chunks will always be the same size or less of
1816 // previous chunks, we only need to find where the ending of the new macro
1817 // chunk is mapped to and update the map with new begin/end mappings.
1819 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1821 SourceLocation EndOffsMappedLoc = I->second;
1822 MacroArgsCache[BeginOffs] = ExpansionLoc;
1823 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1826 /// If \arg Loc points inside a function macro argument, the returned
1827 /// location will be the macro location in which the argument was expanded.
1828 /// If a macro argument is used multiple times, the expanded location will
1829 /// be at the first expansion of the argument.
1833 /// Passing a file location pointing at 'foo', will yield a macro location
1834 /// where 'foo' was expanded into.
1836 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1837 if (Loc.isInvalid() || !Loc.isFileID())
1842 std::tie(FID, Offset) = getDecomposedLoc(Loc);
1843 if (FID.isInvalid())
1846 std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1847 if (!MacroArgsCache) {
1848 MacroArgsCache = std::make_unique<MacroArgsMap>();
1849 computeMacroArgsCache(*MacroArgsCache, FID);
1852 assert(!MacroArgsCache->empty());
1853 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1856 unsigned MacroArgBeginOffs = I->first;
1857 SourceLocation MacroArgExpandedLoc = I->second;
1858 if (MacroArgExpandedLoc.isValid())
1859 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1864 std::pair<FileID, unsigned>
1865 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1866 if (FID.isInvalid())
1867 return std::make_pair(FileID(), 0);
1869 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1871 using DecompTy = std::pair<FileID, unsigned>;
1872 auto InsertOp = IncludedLocMap.try_emplace(FID);
1873 DecompTy &DecompLoc = InsertOp.first->second;
1874 if (!InsertOp.second)
1875 return DecompLoc; // already in map.
1877 SourceLocation UpperLoc;
1878 bool Invalid = false;
1879 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1881 if (Entry.isExpansion())
1882 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1884 UpperLoc = Entry.getFile().getIncludeLoc();
1887 if (UpperLoc.isValid())
1888 DecompLoc = getDecomposedLoc(UpperLoc);
1893 /// Given a decomposed source location, move it up the include/expansion stack
1894 /// to the parent source location. If this is possible, return the decomposed
1895 /// version of the parent in Loc and return false. If Loc is the top-level
1896 /// entry, return true and don't modify it.
1897 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1898 const SourceManager &SM) {
1899 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1900 if (UpperLoc.first.isInvalid())
1901 return true; // We reached the top.
1907 /// Return the cache entry for comparing the given file IDs
1908 /// for isBeforeInTranslationUnit.
1909 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1910 FileID RFID) const {
1911 // This is a magic number for limiting the cache size. It was experimentally
1912 // derived from a small Objective-C project (where the cache filled
1913 // out to ~250 items). We can make it larger if necessary.
1914 enum { MagicCacheSize = 300 };
1915 IsBeforeInTUCacheKey Key(LFID, RFID);
1917 // If the cache size isn't too large, do a lookup and if necessary default
1918 // construct an entry. We can then return it to the caller for direct
1919 // use. When they update the value, the cache will get automatically
1921 if (IBTUCache.size() < MagicCacheSize)
1922 return IBTUCache[Key];
1924 // Otherwise, do a lookup that will not construct a new value.
1925 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
1926 if (I != IBTUCache.end())
1929 // Fall back to the overflow value.
1930 return IBTUCacheOverflow;
1933 /// Determines the order of 2 source locations in the translation unit.
1935 /// \returns true if LHS source location comes before RHS, false otherwise.
1936 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1937 SourceLocation RHS) const {
1938 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1942 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1943 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
1945 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
1946 // is a serialized one referring to a file that was removed after we loaded
1948 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
1949 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
1951 std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
1953 return InSameTU.second;
1955 // If we arrived here, the location is either in a built-ins buffer or
1956 // associated with global inline asm. PR5662 and PR22576 are examples.
1958 StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
1959 StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
1960 bool LIsBuiltins = LB == "<built-in>";
1961 bool RIsBuiltins = RB == "<built-in>";
1962 // Sort built-in before non-built-in.
1963 if (LIsBuiltins || RIsBuiltins) {
1964 if (LIsBuiltins != RIsBuiltins)
1966 // Both are in built-in buffers, but from different files. We just claim that
1967 // lower IDs come first.
1968 return LOffs.first < ROffs.first;
1970 bool LIsAsm = LB == "<inline asm>";
1971 bool RIsAsm = RB == "<inline asm>";
1972 // Sort assembler after built-ins, but before the rest.
1973 if (LIsAsm || RIsAsm) {
1974 if (LIsAsm != RIsAsm)
1976 assert(LOffs.first == ROffs.first);
1979 bool LIsScratch = LB == "<scratch space>";
1980 bool RIsScratch = RB == "<scratch space>";
1981 // Sort scratch after inline asm, but before the rest.
1982 if (LIsScratch || RIsScratch) {
1983 if (LIsScratch != RIsScratch)
1985 return LOffs.second < ROffs.second;
1987 llvm_unreachable("Unsortable locations found");
1990 std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
1991 std::pair<FileID, unsigned> &LOffs,
1992 std::pair<FileID, unsigned> &ROffs) const {
1993 // If the source locations are in the same file, just compare offsets.
1994 if (LOffs.first == ROffs.first)
1995 return std::make_pair(true, LOffs.second < ROffs.second);
1997 // If we are comparing a source location with multiple locations in the same
1998 // file, we get a big win by caching the result.
1999 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2000 getInBeforeInTUCache(LOffs.first, ROffs.first);
2002 // If we are comparing a source location with multiple locations in the same
2003 // file, we get a big win by caching the result.
2004 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2005 return std::make_pair(
2006 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2008 // Okay, we missed in the cache, start updating the cache for this query.
2009 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2010 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2012 // We need to find the common ancestor. The only way of doing this is to
2013 // build the complete include chain for one and then walking up the chain
2014 // of the other looking for a match.
2015 // We use a map from FileID to Offset to store the chain. Easier than writing
2016 // a custom set hash info that only depends on the first part of a pair.
2017 using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
2020 LChain.insert(LOffs);
2021 // We catch the case where LOffs is in a file included by ROffs and
2022 // quit early. The other way round unfortunately remains suboptimal.
2023 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2025 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2026 if (MoveUpIncludeHierarchy(ROffs, *this))
2027 break; // Met at topmost file.
2029 if (I != LChain.end())
2032 // If we exited because we found a nearest common ancestor, compare the
2033 // locations within the common file and cache them.
2034 if (LOffs.first == ROffs.first) {
2035 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2036 return std::make_pair(
2037 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2039 // Clear the lookup cache, it depends on a common location.
2040 IsBeforeInTUCache.clear();
2041 return std::make_pair(false, false);
2044 void SourceManager::PrintStats() const {
2045 llvm::errs() << "\n*** Source Manager Stats:\n";
2046 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2047 << " mem buffers mapped.\n";
2048 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2049 << llvm::capacity_in_bytes(LocalSLocEntryTable)
2050 << " bytes of capacity), "
2051 << NextLocalOffset << "B of Sloc address space used.\n";
2052 llvm::errs() << LoadedSLocEntryTable.size()
2053 << " loaded SLocEntries allocated, "
2054 << MaxLoadedOffset - CurrentLoadedOffset
2055 << "B of Sloc address space used.\n";
2057 unsigned NumLineNumsComputed = 0;
2058 unsigned NumFileBytesMapped = 0;
2059 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2060 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2061 NumFileBytesMapped += I->second->getSizeBytesMapped();
2063 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2065 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2066 << NumLineNumsComputed << " files with line #'s computed, "
2067 << NumMacroArgsComputed << " files with macro args computed.\n";
2068 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2069 << NumBinaryProbes << " binary.\n";
2072 LLVM_DUMP_METHOD void SourceManager::dump() const {
2073 llvm::raw_ostream &out = llvm::errs();
2075 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2076 llvm::Optional<unsigned> NextStart) {
2077 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2078 << " <SourceLocation " << Entry.getOffset() << ":";
2080 out << *NextStart << ">\n";
2083 if (Entry.isFile()) {
2084 auto &FI = Entry.getFile();
2085 if (FI.NumCreatedFIDs)
2086 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2088 if (FI.getIncludeLoc().isValid())
2089 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2090 if (auto *CC = FI.getContentCache()) {
2091 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2093 if (CC->BufferOverridden)
2094 out << " contents overridden\n";
2095 if (CC->ContentsEntry != CC->OrigEntry) {
2096 out << " contents from "
2097 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2102 auto &EI = Entry.getExpansion();
2103 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2104 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2105 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2106 << EI.getExpansionLocEnd().getOffset() << ">\n";
2110 // Dump local SLocEntries.
2111 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2112 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2113 ID == NumIDs - 1 ? NextLocalOffset
2114 : LocalSLocEntryTable[ID + 1].getOffset());
2116 // Dump loaded SLocEntries.
2117 llvm::Optional<unsigned> NextStart;
2118 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2119 int ID = -(int)Index - 2;
2120 if (SLocEntryLoaded[Index]) {
2121 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2122 NextStart = LoadedSLocEntryTable[Index].getOffset();
2129 ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2131 /// Return the amount of memory used by memory buffers, breaking down
2132 /// by heap-backed versus mmap'ed memory.
2133 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2134 size_t malloc_bytes = 0;
2135 size_t mmap_bytes = 0;
2137 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2138 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2139 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2140 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2141 mmap_bytes += sized_mapped;
2143 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2144 malloc_bytes += sized_mapped;
2148 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2151 size_t SourceManager::getDataStructureSizes() const {
2152 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2153 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2154 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2155 + llvm::capacity_in_bytes(SLocEntryLoaded)
2156 + llvm::capacity_in_bytes(FileInfos);
2158 if (OverriddenFilesInfo)
2159 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2164 SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2165 StringRef Content) {
2166 // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2168 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2169 new llvm::vfs::InMemoryFileSystem);
2170 InMemoryFileSystem->addFile(
2172 llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2173 /*RequiresNullTerminator=*/false));
2174 // This is passed to `SM` as reference, so the pointer has to be referenced
2175 // in `Environment` so that `FileMgr` can out-live this function scope.
2177 std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2178 // This is passed to `SM` as reference, so the pointer has to be referenced
2179 // by `Environment` due to the same reason above.
2180 Diagnostics = std::make_unique<DiagnosticsEngine>(
2181 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2182 new DiagnosticOptions);
2183 SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2184 FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
2185 SourceLocation(), clang::SrcMgr::C_User);
2186 assert(ID.isValid());
2187 SourceMgr->setMainFileID(ID);