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 llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
101 bool *Invalid) const {
102 // Lazily create the Buffer for ContentCaches that wrap files. If we already
103 // computed it, just return what we have.
104 if (Buffer.getPointer() || !ContentsEntry) {
106 *Invalid = isBufferInvalid();
108 return Buffer.getPointer();
111 // Check that the file's size fits in an 'unsigned' (with room for a
112 // past-the-end value). This is deeply regrettable, but various parts of
113 // Clang (including elsewhere in this file!) use 'unsigned' to represent file
114 // offsets, line numbers, string literal lengths, and so on, and fail
115 // miserably on large source files.
116 if ((uint64_t)ContentsEntry->getSize() >=
117 std::numeric_limits<unsigned>::max()) {
118 // We can't make a memory buffer of the required size, so just make a small
119 // one. We should never hit a situation where we've already parsed to a
120 // later offset of the file, so it shouldn't matter that the buffer is
121 // smaller than the file.
123 llvm::MemoryBuffer::getMemBuffer("", ContentsEntry->getName())
125 if (Diag.isDiagnosticInFlight())
126 Diag.SetDelayedDiagnostic(diag::err_file_too_large,
127 ContentsEntry->getName());
129 Diag.Report(Loc, diag::err_file_too_large)
130 << ContentsEntry->getName();
132 Buffer.setInt(Buffer.getInt() | InvalidFlag);
133 if (Invalid) *Invalid = true;
134 return Buffer.getPointer();
137 auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
139 // If we were unable to open the file, then we are in an inconsistent
140 // situation where the content cache referenced a file which no longer
141 // exists. Most likely, we were using a stat cache with an invalid entry but
142 // the file could also have been removed during processing. Since we can't
143 // really deal with this situation, just create an empty buffer.
145 // FIXME: This is definitely not ideal, but our immediate clients can't
146 // currently handle returning a null entry here. Ideally we should detect
147 // that we are in an inconsistent situation and error out as quickly as
149 if (!BufferOrError) {
150 StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
151 auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
152 ContentsEntry->getSize(), "<invalid>");
153 char *Ptr = BackupBuffer->getBufferStart();
154 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
155 Ptr[i] = FillStr[i % FillStr.size()];
156 Buffer.setPointer(BackupBuffer.release());
158 if (Diag.isDiagnosticInFlight())
159 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
160 ContentsEntry->getName(),
161 BufferOrError.getError().message());
163 Diag.Report(Loc, diag::err_cannot_open_file)
164 << ContentsEntry->getName() << BufferOrError.getError().message();
166 Buffer.setInt(Buffer.getInt() | InvalidFlag);
168 if (Invalid) *Invalid = true;
169 return Buffer.getPointer();
172 Buffer.setPointer(BufferOrError->release());
174 // Check that the file's size is the same as in the file entry (which may
175 // have come from a stat cache).
176 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
177 if (Diag.isDiagnosticInFlight())
178 Diag.SetDelayedDiagnostic(diag::err_file_modified,
179 ContentsEntry->getName());
181 Diag.Report(Loc, diag::err_file_modified)
182 << ContentsEntry->getName();
184 Buffer.setInt(Buffer.getInt() | InvalidFlag);
185 if (Invalid) *Invalid = true;
186 return Buffer.getPointer();
189 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
190 // (BOM). We only support UTF-8 with and without a BOM right now. See
191 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
192 StringRef BufStr = Buffer.getPointer()->getBuffer();
193 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
194 .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
196 .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
198 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
199 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
200 .StartsWith("\x2B\x2F\x76", "UTF-7")
201 .StartsWith("\xF7\x64\x4C", "UTF-1")
202 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
203 .StartsWith("\x0E\xFE\xFF", "SCSU")
204 .StartsWith("\xFB\xEE\x28", "BOCU-1")
205 .StartsWith("\x84\x31\x95\x33", "GB-18030")
209 Diag.Report(Loc, diag::err_unsupported_bom)
210 << InvalidBOM << ContentsEntry->getName();
211 Buffer.setInt(Buffer.getInt() | InvalidFlag);
215 *Invalid = isBufferInvalid();
217 return Buffer.getPointer();
220 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
221 auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
223 FilenamesByID.push_back(&*IterBool.first);
224 return IterBool.first->second;
227 /// Add a line note to the line table that indicates that there is a \#line or
228 /// GNU line marker at the specified FID/Offset location which changes the
229 /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
230 /// change the presumed \#include stack. If it is 1, this is a file entry, if
231 /// it is 2 then this is a file exit. FileKind specifies whether this is a
232 /// system header or extern C system header.
233 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
234 int FilenameID, unsigned EntryExit,
235 SrcMgr::CharacteristicKind FileKind) {
236 std::vector<LineEntry> &Entries = LineEntries[FID];
238 // An unspecified FilenameID means use the last filename if available, or the
239 // main source file otherwise.
240 if (FilenameID == -1 && !Entries.empty())
241 FilenameID = Entries.back().FilenameID;
243 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
244 "Adding line entries out of order!");
246 unsigned IncludeOffset = 0;
247 if (EntryExit == 0) { // No #include stack change.
248 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
249 } else if (EntryExit == 1) {
250 IncludeOffset = Offset-1;
251 } else if (EntryExit == 2) {
252 assert(!Entries.empty() && Entries.back().IncludeOffset &&
253 "PPDirectives should have caught case when popping empty include stack");
255 // Get the include loc of the last entries' include loc as our include loc.
257 if (const LineEntry *PrevEntry =
258 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
259 IncludeOffset = PrevEntry->IncludeOffset;
262 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
266 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
267 /// it. If there is no line entry before Offset in FID, return null.
268 const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
270 const std::vector<LineEntry> &Entries = LineEntries[FID];
271 assert(!Entries.empty() && "No #line entries for this FID after all!");
273 // It is very common for the query to be after the last #line, check this
275 if (Entries.back().FileOffset <= Offset)
276 return &Entries.back();
278 // Do a binary search to find the maximal element that is still before Offset.
279 std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
280 if (I == Entries.begin())
285 /// Add a new line entry that has already been encoded into
286 /// the internal representation of the line table.
287 void LineTableInfo::AddEntry(FileID FID,
288 const std::vector<LineEntry> &Entries) {
289 LineEntries[FID] = Entries;
292 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
293 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
294 return getLineTable().getLineTableFilenameID(Name);
297 /// AddLineNote - Add a line note to the line table for the FileID and offset
298 /// specified by Loc. If FilenameID is -1, it is considered to be
300 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
301 int FilenameID, bool IsFileEntry,
303 SrcMgr::CharacteristicKind FileKind) {
304 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
306 bool Invalid = false;
307 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
308 if (!Entry.isFile() || Invalid)
311 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
313 // Remember that this file has #line directives now if it doesn't already.
314 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
316 (void) getLineTable();
318 unsigned EntryExit = 0;
324 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
325 EntryExit, FileKind);
328 LineTableInfo &SourceManager::getLineTable() {
330 LineTable.reset(new LineTableInfo());
334 //===----------------------------------------------------------------------===//
335 // Private 'Create' methods.
336 //===----------------------------------------------------------------------===//
338 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
339 bool UserFilesAreVolatile)
340 : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
342 Diag.setSourceManager(this);
345 SourceManager::~SourceManager() {
346 // Delete FileEntry objects corresponding to content caches. Since the actual
347 // content cache objects are bump pointer allocated, we just have to run the
348 // dtors, but we call the deallocate method for completeness.
349 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
350 if (MemBufferInfos[i]) {
351 MemBufferInfos[i]->~ContentCache();
352 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
355 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
356 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
358 I->second->~ContentCache();
359 ContentCacheAlloc.Deallocate(I->second);
364 void SourceManager::clearIDTables() {
365 MainFileID = FileID();
366 LocalSLocEntryTable.clear();
367 LoadedSLocEntryTable.clear();
368 SLocEntryLoaded.clear();
369 LastLineNoFileIDQuery = FileID();
370 LastLineNoContentCache = nullptr;
371 LastFileIDLookup = FileID();
376 // Use up FileID #0 as an invalid expansion.
378 CurrentLoadedOffset = MaxLoadedOffset;
379 createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
382 void SourceManager::initializeForReplay(const SourceManager &Old) {
383 assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
385 auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
386 auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
387 Clone->OrigEntry = Cache->OrigEntry;
388 Clone->ContentsEntry = Cache->ContentsEntry;
389 Clone->BufferOverridden = Cache->BufferOverridden;
390 Clone->IsFileVolatile = Cache->IsFileVolatile;
391 Clone->IsTransient = Cache->IsTransient;
392 Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
396 // Ensure all SLocEntries are loaded from the external source.
397 for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
398 if (!Old.SLocEntryLoaded[I])
399 Old.loadSLocEntry(I, nullptr);
401 // Inherit any content cache data from the old source manager.
402 for (auto &FileInfo : Old.FileInfos) {
403 SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
406 Slot = CloneContentCache(FileInfo.second);
410 /// getOrCreateContentCache - Create or return a cached ContentCache for the
413 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
415 assert(FileEnt && "Didn't specify a file entry to use?");
417 // Do we already have information about this file?
418 ContentCache *&Entry = FileInfos[FileEnt];
419 if (Entry) return Entry;
421 // Nope, create a new Cache entry.
422 Entry = ContentCacheAlloc.Allocate<ContentCache>();
424 if (OverriddenFilesInfo) {
425 // If the file contents are overridden with contents from another file,
426 // pass that file to ContentCache.
427 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
428 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
429 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
430 new (Entry) ContentCache(FileEnt);
432 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
436 new (Entry) ContentCache(FileEnt);
439 Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;
440 Entry->IsTransient = FilesAreTransient;
445 /// Create a new ContentCache for the specified memory buffer.
446 /// This does no caching.
448 SourceManager::createMemBufferContentCache(const llvm::MemoryBuffer *Buffer,
450 // Add a new ContentCache to the MemBufferInfos list and return it.
451 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
452 new (Entry) ContentCache();
453 MemBufferInfos.push_back(Entry);
454 Entry->replaceBuffer(Buffer, DoNotFree);
458 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
459 bool *Invalid) const {
460 assert(!SLocEntryLoaded[Index]);
461 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
464 // If the file of the SLocEntry changed we could still have loaded it.
465 if (!SLocEntryLoaded[Index]) {
466 // Try to recover; create a SLocEntry so the rest of clang can handle it.
467 LoadedSLocEntryTable[Index] = SLocEntry::get(
468 0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
469 SrcMgr::C_User, ""));
473 return LoadedSLocEntryTable[Index];
476 std::pair<int, unsigned>
477 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
478 unsigned 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 < NextLocalOffset)
482 return std::make_pair(0, 0);
483 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
484 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
485 CurrentLoadedOffset -= TotalSize;
486 int ID = LoadedSLocEntryTable.size();
487 return std::make_pair(-ID - 1, CurrentLoadedOffset);
490 /// As part of recovering from missing or changed content, produce a
491 /// fake, non-empty buffer.
492 llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
493 if (!FakeBufferForRecovery)
494 FakeBufferForRecovery =
495 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
497 return FakeBufferForRecovery.get();
500 /// As part of recovering from missing or changed content, produce a
501 /// fake content cache.
502 const SrcMgr::ContentCache *
503 SourceManager::getFakeContentCacheForRecovery() const {
504 if (!FakeContentCacheForRecovery) {
505 FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
506 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
509 return FakeContentCacheForRecovery.get();
512 /// Returns the previous in-order FileID or an invalid FileID if there
513 /// is no previous one.
514 FileID SourceManager::getPreviousFileID(FileID FID) const {
525 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
529 return FileID::get(ID-1);
532 /// Returns the next in-order FileID or an invalid FileID if there is
534 FileID SourceManager::getNextFileID(FileID FID) const {
540 if (unsigned(ID+1) >= local_sloc_entry_size())
542 } else if (ID+1 >= -1) {
546 return FileID::get(ID+1);
549 //===----------------------------------------------------------------------===//
550 // Methods to create new FileID's and macro expansions.
551 //===----------------------------------------------------------------------===//
553 /// createFileID - Create a new FileID for the specified ContentCache and
554 /// include position. This works regardless of whether the ContentCache
555 /// corresponds to a file or some other input source.
556 FileID SourceManager::createFileID(const ContentCache *File, StringRef Filename,
557 SourceLocation IncludePos,
558 SrcMgr::CharacteristicKind FileCharacter,
559 int LoadedID, unsigned LoadedOffset) {
561 assert(LoadedID != -1 && "Loading sentinel FileID");
562 unsigned Index = unsigned(-LoadedID) - 2;
563 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
564 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
565 LoadedSLocEntryTable[Index] = SLocEntry::get(
566 LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
567 SLocEntryLoaded[Index] = true;
568 return FileID::get(LoadedID);
570 LocalSLocEntryTable.push_back(
571 SLocEntry::get(NextLocalOffset,
572 FileInfo::get(IncludePos, File, FileCharacter, Filename)));
573 unsigned FileSize = File->getSize();
574 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
575 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
576 "Ran out of source locations!");
577 // We do a +1 here because we want a SourceLocation that means "the end of the
578 // file", e.g. for the "no newline at the end of the file" diagnostic.
579 NextLocalOffset += FileSize + 1;
581 // Set LastFileIDLookup to the newly created file. The next getFileID call is
582 // almost guaranteed to be from that file.
583 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
584 return LastFileIDLookup = FID;
588 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
589 SourceLocation ExpansionLoc,
590 unsigned TokLength) {
591 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
593 return createExpansionLocImpl(Info, TokLength);
597 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
598 SourceLocation ExpansionLocStart,
599 SourceLocation ExpansionLocEnd,
601 bool ExpansionIsTokenRange,
603 unsigned LoadedOffset) {
604 ExpansionInfo Info = ExpansionInfo::create(
605 SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
606 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
609 SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
610 SourceLocation TokenStart,
611 SourceLocation TokenEnd) {
612 assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
613 "token spans multiple files");
614 return createExpansionLocImpl(
615 ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
616 TokenEnd.getOffset() - TokenStart.getOffset());
620 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
623 unsigned LoadedOffset) {
625 assert(LoadedID != -1 && "Loading sentinel FileID");
626 unsigned Index = unsigned(-LoadedID) - 2;
627 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
628 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
629 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
630 SLocEntryLoaded[Index] = true;
631 return SourceLocation::getMacroLoc(LoadedOffset);
633 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
634 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
635 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
636 "Ran out of source locations!");
637 // See createFileID for that +1.
638 NextLocalOffset += TokLength + 1;
639 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
642 const llvm::MemoryBuffer *
643 SourceManager::getMemoryBufferForFile(const FileEntry *File, bool *Invalid) {
644 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
645 assert(IR && "getOrCreateContentCache() cannot return NULL");
646 return IR->getBuffer(Diag, getFileManager(), SourceLocation(), Invalid);
649 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
650 llvm::MemoryBuffer *Buffer,
652 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
653 assert(IR && "getOrCreateContentCache() cannot return NULL");
655 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
656 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
658 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
661 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
662 const FileEntry *NewFile) {
663 assert(SourceFile->getSize() == NewFile->getSize() &&
664 "Different sizes, use the FileManager to create a virtual file with "
666 assert(FileInfos.count(SourceFile) == 0 &&
667 "This function should be called at the initialization stage, before "
668 "any parsing occurs.");
669 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
673 SourceManager::bypassFileContentsOverride(const FileEntry &File) {
674 assert(isFileOverridden(&File));
675 llvm::Optional<FileEntryRef> BypassFile =
676 FileMgr.getBypassFile(FileEntryRef(File.getName(), File));
678 // If the file can't be found in the FS, give up.
682 const FileEntry *FE = &BypassFile->getFileEntry();
683 (void)getOrCreateContentCache(FE);
687 void SourceManager::setFileIsTransient(const FileEntry *File) {
688 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
689 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
692 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
693 bool MyInvalid = false;
694 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
695 if (!SLoc.isFile() || MyInvalid) {
698 return "<<<<<INVALID SOURCE LOCATION>>>>>";
701 const llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
702 Diag, getFileManager(), SourceLocation(), &MyInvalid);
704 *Invalid = MyInvalid;
707 return "<<<<<INVALID SOURCE LOCATION>>>>>";
709 return Buf->getBuffer();
712 //===----------------------------------------------------------------------===//
713 // SourceLocation manipulation methods.
714 //===----------------------------------------------------------------------===//
716 /// Return the FileID for a SourceLocation.
718 /// This is the cache-miss path of getFileID. Not as hot as that function, but
719 /// still very important. It is responsible for finding the entry in the
720 /// SLocEntry tables that contains the specified location.
721 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
723 return FileID::get(0);
725 // Now it is time to search for the correct file. See where the SLocOffset
726 // sits in the global view and consult local or loaded buffers for it.
727 if (SLocOffset < NextLocalOffset)
728 return getFileIDLocal(SLocOffset);
729 return getFileIDLoaded(SLocOffset);
732 /// Return the FileID for a SourceLocation with a low offset.
734 /// This function knows that the SourceLocation is in a local buffer, not a
736 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
737 assert(SLocOffset < NextLocalOffset && "Bad function choice");
739 // After the first and second level caches, I see two common sorts of
740 // behavior: 1) a lot of searched FileID's are "near" the cached file
741 // location or are "near" the cached expansion location. 2) others are just
742 // completely random and may be a very long way away.
744 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
745 // then we fall back to a less cache efficient, but more scalable, binary
746 // search to find the location.
748 // See if this is near the file point - worst case we start scanning from the
749 // most newly created FileID.
750 const SrcMgr::SLocEntry *I;
752 if (LastFileIDLookup.ID < 0 ||
753 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
754 // Neither loc prunes our search.
755 I = LocalSLocEntryTable.end();
757 // Perhaps it is near the file point.
758 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
761 // Find the FileID that contains this. "I" is an iterator that points to a
762 // FileID whose offset is known to be larger than SLocOffset.
763 unsigned NumProbes = 0;
766 if (I->getOffset() <= SLocOffset) {
767 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
769 // If this isn't an expansion, remember it. We have good locality across
771 if (!I->isExpansion())
772 LastFileIDLookup = Res;
773 NumLinearScans += NumProbes+1;
776 if (++NumProbes == 8)
780 // Convert "I" back into an index. We know that it is an entry whose index is
781 // larger than the offset we are looking for.
782 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
783 // LessIndex - This is the lower bound of the range that we're searching.
784 // We know that the offset corresponding to the FileID is is less than
786 unsigned LessIndex = 0;
789 bool Invalid = false;
790 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
791 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
793 return FileID::get(0);
797 // If the offset of the midpoint is too large, chop the high side of the
798 // range to the midpoint.
799 if (MidOffset > SLocOffset) {
800 GreaterIndex = MiddleIndex;
804 // If the middle index contains the value, succeed and return.
805 // FIXME: This could be made faster by using a function that's aware of
806 // being in the local area.
807 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
808 FileID Res = FileID::get(MiddleIndex);
810 // If this isn't a macro expansion, remember it. We have good locality
811 // across FileID lookups.
812 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
813 LastFileIDLookup = Res;
814 NumBinaryProbes += NumProbes;
818 // Otherwise, move the low-side up to the middle index.
819 LessIndex = MiddleIndex;
823 /// Return the FileID for a SourceLocation with a high offset.
825 /// This function knows that the SourceLocation is in a loaded buffer, not a
827 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
828 // Sanity checking, otherwise a bug may lead to hanging in release build.
829 if (SLocOffset < CurrentLoadedOffset) {
830 assert(0 && "Invalid SLocOffset or bad function choice");
834 // Essentially the same as the local case, but the loaded array is sorted
835 // in the other direction.
837 // First do a linear scan from the last lookup position, if possible.
839 int LastID = LastFileIDLookup.ID;
840 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
843 I = (-LastID - 2) + 1;
846 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
847 // Make sure the entry is loaded!
848 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
849 if (E.getOffset() <= SLocOffset) {
850 FileID Res = FileID::get(-int(I) - 2);
852 if (!E.isExpansion())
853 LastFileIDLookup = Res;
854 NumLinearScans += NumProbes + 1;
859 // Linear scan failed. Do the binary search. Note the reverse sorting of the
860 // table: GreaterIndex is the one where the offset is greater, which is
861 // actually a lower index!
862 unsigned GreaterIndex = I;
863 unsigned LessIndex = LoadedSLocEntryTable.size();
867 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
868 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
869 if (E.getOffset() == 0)
870 return FileID(); // invalid entry.
874 if (E.getOffset() > SLocOffset) {
875 // Sanity checking, otherwise a bug may lead to hanging in release build.
876 if (GreaterIndex == MiddleIndex) {
877 assert(0 && "binary search missed the entry");
880 GreaterIndex = MiddleIndex;
884 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
885 FileID Res = FileID::get(-int(MiddleIndex) - 2);
886 if (!E.isExpansion())
887 LastFileIDLookup = Res;
888 NumBinaryProbes += NumProbes;
892 // Sanity checking, otherwise a bug may lead to hanging in release build.
893 if (LessIndex == MiddleIndex) {
894 assert(0 && "binary search missed the entry");
897 LessIndex = MiddleIndex;
901 SourceLocation SourceManager::
902 getExpansionLocSlowCase(SourceLocation Loc) const {
904 // Note: If Loc indicates an offset into a token that came from a macro
905 // expansion (e.g. the 5th character of the token) we do not want to add
906 // this offset when going to the expansion location. The expansion
907 // location is the macro invocation, which the offset has nothing to do
908 // with. This is unlike when we get the spelling loc, because the offset
909 // directly correspond to the token whose spelling we're inspecting.
910 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
911 } while (!Loc.isFileID());
916 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
918 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
919 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
920 Loc = Loc.getLocWithOffset(LocInfo.second);
921 } while (!Loc.isFileID());
925 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
927 if (isMacroArgExpansion(Loc))
928 Loc = getImmediateSpellingLoc(Loc);
930 Loc = getImmediateExpansionRange(Loc).getBegin();
931 } while (!Loc.isFileID());
936 std::pair<FileID, unsigned>
937 SourceManager::getDecomposedExpansionLocSlowCase(
938 const SrcMgr::SLocEntry *E) const {
939 // If this is an expansion record, walk through all the expansion points.
944 Loc = E->getExpansion().getExpansionLocStart();
946 FID = getFileID(Loc);
947 E = &getSLocEntry(FID);
948 Offset = Loc.getOffset()-E->getOffset();
949 } while (!Loc.isFileID());
951 return std::make_pair(FID, Offset);
954 std::pair<FileID, unsigned>
955 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
956 unsigned Offset) const {
957 // If this is an expansion record, walk through all the expansion points.
961 Loc = E->getExpansion().getSpellingLoc();
962 Loc = Loc.getLocWithOffset(Offset);
964 FID = getFileID(Loc);
965 E = &getSLocEntry(FID);
966 Offset = Loc.getOffset()-E->getOffset();
967 } while (!Loc.isFileID());
969 return std::make_pair(FID, Offset);
972 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
973 /// spelling location referenced by the ID. This is the first level down
974 /// towards the place where the characters that make up the lexed token can be
975 /// found. This should not generally be used by clients.
976 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
977 if (Loc.isFileID()) return Loc;
978 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
979 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
980 return Loc.getLocWithOffset(LocInfo.second);
983 /// getImmediateExpansionRange - Loc is required to be an expansion location.
984 /// Return the start/end of the expansion information.
986 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
987 assert(Loc.isMacroID() && "Not a macro expansion loc!");
988 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
989 return Expansion.getExpansionLocRange();
992 SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
993 while (isMacroArgExpansion(Loc))
994 Loc = getImmediateSpellingLoc(Loc);
998 /// getExpansionRange - Given a SourceLocation object, return the range of
999 /// tokens covered by the expansion in the ultimate file.
1000 CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
1002 return CharSourceRange(SourceRange(Loc, Loc), true);
1004 CharSourceRange Res = getImmediateExpansionRange(Loc);
1006 // Fully resolve the start and end locations to their ultimate expansion
1008 while (!Res.getBegin().isFileID())
1009 Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
1010 while (!Res.getEnd().isFileID()) {
1011 CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
1012 Res.setEnd(EndRange.getEnd());
1013 Res.setTokenRange(EndRange.isTokenRange());
1018 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1019 SourceLocation *StartLoc) const {
1020 if (!Loc.isMacroID()) return false;
1022 FileID FID = getFileID(Loc);
1023 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1024 if (!Expansion.isMacroArgExpansion()) return false;
1027 *StartLoc = Expansion.getExpansionLocStart();
1031 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1032 if (!Loc.isMacroID()) return false;
1034 FileID FID = getFileID(Loc);
1035 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1036 return Expansion.isMacroBodyExpansion();
1039 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1040 SourceLocation *MacroBegin) const {
1041 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1043 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1044 if (DecompLoc.second > 0)
1045 return false; // Does not point at the start of expansion range.
1047 bool Invalid = false;
1048 const SrcMgr::ExpansionInfo &ExpInfo =
1049 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1052 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1054 if (ExpInfo.isMacroArgExpansion()) {
1055 // For macro argument expansions, check if the previous FileID is part of
1056 // the same argument expansion, in which case this Loc is not at the
1057 // beginning of the expansion.
1058 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1059 if (!PrevFID.isInvalid()) {
1060 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1063 if (PrevEntry.isExpansion() &&
1064 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1070 *MacroBegin = ExpLoc;
1074 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1075 SourceLocation *MacroEnd) const {
1076 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1078 FileID FID = getFileID(Loc);
1079 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1080 if (isInFileID(NextLoc, FID))
1081 return false; // Does not point at the end of expansion range.
1083 bool Invalid = false;
1084 const SrcMgr::ExpansionInfo &ExpInfo =
1085 getSLocEntry(FID, &Invalid).getExpansion();
1089 if (ExpInfo.isMacroArgExpansion()) {
1090 // For macro argument expansions, check if the next FileID is part of the
1091 // same argument expansion, in which case this Loc is not at the end of the
1093 FileID NextFID = getNextFileID(FID);
1094 if (!NextFID.isInvalid()) {
1095 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1098 if (NextEntry.isExpansion() &&
1099 NextEntry.getExpansion().getExpansionLocStart() ==
1100 ExpInfo.getExpansionLocStart())
1106 *MacroEnd = ExpInfo.getExpansionLocEnd();
1110 //===----------------------------------------------------------------------===//
1111 // Queries about the code at a SourceLocation.
1112 //===----------------------------------------------------------------------===//
1114 /// getCharacterData - Return a pointer to the start of the specified location
1115 /// in the appropriate MemoryBuffer.
1116 const char *SourceManager::getCharacterData(SourceLocation SL,
1117 bool *Invalid) const {
1118 // Note that this is a hot function in the getSpelling() path, which is
1119 // heavily used by -E mode.
1120 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1122 // Note that calling 'getBuffer()' may lazily page in a source file.
1123 bool CharDataInvalid = false;
1124 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1125 if (CharDataInvalid || !Entry.isFile()) {
1129 return "<<<<INVALID BUFFER>>>>";
1131 const llvm::MemoryBuffer *Buffer =
1132 Entry.getFile().getContentCache()->getBuffer(
1133 Diag, getFileManager(), SourceLocation(), &CharDataInvalid);
1135 *Invalid = CharDataInvalid;
1136 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
1139 /// getColumnNumber - Return the column # for the specified file position.
1140 /// this is significantly cheaper to compute than the line number.
1141 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1142 bool *Invalid) const {
1143 bool MyInvalid = false;
1144 const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1146 *Invalid = MyInvalid;
1151 // It is okay to request a position just past the end of the buffer.
1152 if (FilePos > MemBuf->getBufferSize()) {
1158 const char *Buf = MemBuf->getBufferStart();
1159 // See if we just calculated the line number for this FilePos and can use
1160 // that to lookup the start of the line instead of searching for it.
1161 if (LastLineNoFileIDQuery == FID &&
1162 LastLineNoContentCache->SourceLineCache != nullptr &&
1163 LastLineNoResult < LastLineNoContentCache->NumLines) {
1164 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1165 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1166 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1167 if (FilePos >= LineStart && FilePos < LineEnd) {
1168 // LineEnd is the LineStart of the next line.
1169 // A line ends with separator LF or CR+LF on Windows.
1170 // FilePos might point to the last separator,
1171 // but we need a column number at most 1 + the last column.
1172 if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1173 if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1176 return FilePos - LineStart + 1;
1180 unsigned LineStart = FilePos;
1181 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1183 return FilePos-LineStart+1;
1186 // isInvalid - Return the result of calling loc.isInvalid(), and
1187 // if Invalid is not null, set its value to same.
1188 template<typename LocType>
1189 static bool isInvalid(LocType Loc, bool *Invalid) {
1190 bool MyInvalid = Loc.isInvalid();
1192 *Invalid = MyInvalid;
1196 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1197 bool *Invalid) const {
1198 if (isInvalid(Loc, Invalid)) return 0;
1199 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1200 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1203 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1204 bool *Invalid) const {
1205 if (isInvalid(Loc, Invalid)) return 0;
1206 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1207 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1210 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1211 bool *Invalid) const {
1212 PresumedLoc PLoc = getPresumedLoc(Loc);
1213 if (isInvalid(PLoc, Invalid)) return 0;
1214 return PLoc.getColumn();
1218 #include <emmintrin.h>
1221 static LLVM_ATTRIBUTE_NOINLINE void
1222 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1223 llvm::BumpPtrAllocator &Alloc,
1224 const SourceManager &SM, bool &Invalid);
1225 static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1226 llvm::BumpPtrAllocator &Alloc,
1227 const SourceManager &SM, bool &Invalid) {
1228 // Note that calling 'getBuffer()' may lazily page in the file.
1229 const MemoryBuffer *Buffer =
1230 FI->getBuffer(Diag, SM.getFileManager(), SourceLocation(), &Invalid);
1234 // Find the file offsets of all of the *physical* source lines. This does
1235 // not look at trigraphs, escaped newlines, or anything else tricky.
1236 SmallVector<unsigned, 256> LineOffsets;
1238 // Line #1 starts at char 0.
1239 LineOffsets.push_back(0);
1241 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1242 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1245 // Skip over the contents of the line.
1246 while (Buf[I] != '\n' && Buf[I] != '\r' && Buf[I] != '\0')
1249 if (Buf[I] == '\n' || Buf[I] == '\r') {
1250 // If this is \r\n, skip both characters.
1251 if (Buf[I] == '\r' && Buf[I+1] == '\n')
1254 LineOffsets.push_back(I);
1256 // Otherwise, this is a NUL. If end of file, exit.
1257 if (Buf+I == End) break;
1262 // Copy the offsets into the FileInfo structure.
1263 FI->NumLines = LineOffsets.size();
1264 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1265 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1268 /// getLineNumber - Given a SourceLocation, return the spelling line number
1269 /// for the position indicated. This requires building and caching a table of
1270 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1271 /// about to emit a diagnostic.
1272 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1273 bool *Invalid) const {
1274 if (FID.isInvalid()) {
1280 ContentCache *Content;
1281 if (LastLineNoFileIDQuery == FID)
1282 Content = LastLineNoContentCache;
1284 bool MyInvalid = false;
1285 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1286 if (MyInvalid || !Entry.isFile()) {
1292 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1295 // If this is the first use of line information for this buffer, compute the
1296 /// SourceLineCache for it on demand.
1297 if (!Content->SourceLineCache) {
1298 bool MyInvalid = false;
1299 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1301 *Invalid = MyInvalid;
1307 // Okay, we know we have a line number table. Do a binary search to find the
1308 // line number that this character position lands on.
1309 unsigned *SourceLineCache = Content->SourceLineCache;
1310 unsigned *SourceLineCacheStart = SourceLineCache;
1311 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1313 unsigned QueriedFilePos = FilePos+1;
1315 // FIXME: I would like to be convinced that this code is worth being as
1316 // complicated as it is, binary search isn't that slow.
1318 // If it is worth being optimized, then in my opinion it could be more
1319 // performant, simpler, and more obviously correct by just "galloping" outward
1320 // from the queried file position. In fact, this could be incorporated into a
1321 // generic algorithm such as lower_bound_with_hint.
1323 // If someone gives me a test case where this matters, and I will do it! - DWD
1325 // If the previous query was to the same file, we know both the file pos from
1326 // that query and the line number returned. This allows us to narrow the
1327 // search space from the entire file to something near the match.
1328 if (LastLineNoFileIDQuery == FID) {
1329 if (QueriedFilePos >= LastLineNoFilePos) {
1330 // FIXME: Potential overflow?
1331 SourceLineCache = SourceLineCache+LastLineNoResult-1;
1333 // The query is likely to be nearby the previous one. Here we check to
1334 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1335 // where big comment blocks and vertical whitespace eat up lines but
1336 // contribute no tokens.
1337 if (SourceLineCache+5 < SourceLineCacheEnd) {
1338 if (SourceLineCache[5] > QueriedFilePos)
1339 SourceLineCacheEnd = SourceLineCache+5;
1340 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1341 if (SourceLineCache[10] > QueriedFilePos)
1342 SourceLineCacheEnd = SourceLineCache+10;
1343 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1344 if (SourceLineCache[20] > QueriedFilePos)
1345 SourceLineCacheEnd = SourceLineCache+20;
1350 if (LastLineNoResult < Content->NumLines)
1351 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1356 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1357 unsigned LineNo = Pos-SourceLineCacheStart;
1359 LastLineNoFileIDQuery = FID;
1360 LastLineNoContentCache = Content;
1361 LastLineNoFilePos = QueriedFilePos;
1362 LastLineNoResult = LineNo;
1366 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1367 bool *Invalid) const {
1368 if (isInvalid(Loc, Invalid)) return 0;
1369 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1370 return getLineNumber(LocInfo.first, LocInfo.second);
1372 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1373 bool *Invalid) const {
1374 if (isInvalid(Loc, Invalid)) return 0;
1375 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1376 return getLineNumber(LocInfo.first, LocInfo.second);
1378 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1379 bool *Invalid) const {
1380 PresumedLoc PLoc = getPresumedLoc(Loc);
1381 if (isInvalid(PLoc, Invalid)) return 0;
1382 return PLoc.getLine();
1385 /// getFileCharacteristic - return the file characteristic of the specified
1386 /// source location, indicating whether this is a normal file, a system
1387 /// header, or an "implicit extern C" system header.
1389 /// This state can be modified with flags on GNU linemarker directives like:
1391 /// which changes all source locations in the current file after that to be
1392 /// considered to be from a system header.
1393 SrcMgr::CharacteristicKind
1394 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1395 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1396 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1397 bool Invalid = false;
1398 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1399 if (Invalid || !SEntry.isFile())
1402 const SrcMgr::FileInfo &FI = SEntry.getFile();
1404 // If there are no #line directives in this file, just return the whole-file
1406 if (!FI.hasLineDirectives())
1407 return FI.getFileCharacteristic();
1409 assert(LineTable && "Can't have linetable entries without a LineTable!");
1410 // See if there is a #line directive before the location.
1411 const LineEntry *Entry =
1412 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1414 // If this is before the first line marker, use the file characteristic.
1416 return FI.getFileCharacteristic();
1418 return Entry->FileKind;
1421 /// Return the filename or buffer identifier of the buffer the location is in.
1422 /// Note that this name does not respect \#line directives. Use getPresumedLoc
1423 /// for normal clients.
1424 StringRef SourceManager::getBufferName(SourceLocation Loc,
1425 bool *Invalid) const {
1426 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1428 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1431 /// getPresumedLoc - This method returns the "presumed" location of a
1432 /// SourceLocation specifies. A "presumed location" can be modified by \#line
1433 /// or GNU line marker directives. This provides a view on the data that a
1434 /// user should see in diagnostics, for example.
1436 /// Note that a presumed location is always given as the expansion point of an
1437 /// expansion location, not at the spelling location.
1438 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1439 bool UseLineDirectives) const {
1440 if (Loc.isInvalid()) return PresumedLoc();
1442 // Presumed locations are always for expansion points.
1443 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1445 bool Invalid = false;
1446 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1447 if (Invalid || !Entry.isFile())
1448 return PresumedLoc();
1450 const SrcMgr::FileInfo &FI = Entry.getFile();
1451 const SrcMgr::ContentCache *C = FI.getContentCache();
1453 // To get the source name, first consult the FileEntry (if one exists)
1454 // before the MemBuffer as this will avoid unnecessarily paging in the
1456 FileID FID = LocInfo.first;
1459 Filename = C->OrigEntry->getName();
1461 Filename = C->getBuffer(Diag, getFileManager())->getBufferIdentifier();
1463 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1465 return PresumedLoc();
1466 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1468 return PresumedLoc();
1470 SourceLocation IncludeLoc = FI.getIncludeLoc();
1472 // If we have #line directives in this file, update and overwrite the physical
1473 // location info if appropriate.
1474 if (UseLineDirectives && FI.hasLineDirectives()) {
1475 assert(LineTable && "Can't have linetable entries without a LineTable!");
1476 // See if there is a #line directive before this. If so, get it.
1477 if (const LineEntry *Entry =
1478 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1479 // If the LineEntry indicates a filename, use it.
1480 if (Entry->FilenameID != -1) {
1481 Filename = LineTable->getFilename(Entry->FilenameID);
1482 // The contents of files referenced by #line are not in the
1484 FID = FileID::get(0);
1487 // Use the line number specified by the LineEntry. This line number may
1488 // be multiple lines down from the line entry. Add the difference in
1489 // physical line numbers from the query point and the line marker to the
1491 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1492 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1494 // Note that column numbers are not molested by line markers.
1496 // Handle virtual #include manipulation.
1497 if (Entry->IncludeOffset) {
1498 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1499 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1504 return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1507 /// Returns whether the PresumedLoc for a given SourceLocation is
1508 /// in the main file.
1510 /// This computes the "presumed" location for a SourceLocation, then checks
1511 /// whether it came from a file other than the main file. This is different
1512 /// from isWrittenInMainFile() because it takes line marker directives into
1514 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1515 if (Loc.isInvalid()) return false;
1517 // Presumed locations are always for expansion points.
1518 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1520 bool Invalid = false;
1521 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1522 if (Invalid || !Entry.isFile())
1525 const SrcMgr::FileInfo &FI = Entry.getFile();
1527 // Check if there is a line directive for this location.
1528 if (FI.hasLineDirectives())
1529 if (const LineEntry *Entry =
1530 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1531 if (Entry->IncludeOffset)
1534 return FI.getIncludeLoc().isInvalid();
1537 /// The size of the SLocEntry that \p FID represents.
1538 unsigned SourceManager::getFileIDSize(FileID FID) const {
1539 bool Invalid = false;
1540 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1545 unsigned NextOffset;
1546 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1547 NextOffset = getNextLocalOffset();
1548 else if (ID+1 == -1)
1549 NextOffset = MaxLoadedOffset;
1551 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1553 return NextOffset - Entry.getOffset() - 1;
1556 //===----------------------------------------------------------------------===//
1557 // Other miscellaneous methods.
1558 //===----------------------------------------------------------------------===//
1560 /// Get the source location for the given file:line:col triplet.
1562 /// If the source file is included multiple times, the source location will
1563 /// be based upon an arbitrary inclusion.
1564 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1566 unsigned Col) const {
1567 assert(SourceFile && "Null source file!");
1568 assert(Line && Col && "Line and column should start from 1!");
1570 FileID FirstFID = translateFile(SourceFile);
1571 return translateLineCol(FirstFID, Line, Col);
1574 /// Get the FileID for the given file.
1576 /// If the source file is included multiple times, the FileID will be the
1577 /// first inclusion.
1578 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1579 assert(SourceFile && "Null source file!");
1581 // First, check the main file ID, since it is common to look for a
1582 // location in the main file.
1583 if (MainFileID.isValid()) {
1584 bool Invalid = false;
1585 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1589 if (MainSLoc.isFile()) {
1590 const ContentCache *MainContentCache =
1591 MainSLoc.getFile().getContentCache();
1592 if (MainContentCache && MainContentCache->OrigEntry == SourceFile)
1597 // The location we're looking for isn't in the main file; look
1598 // through all of the local source locations.
1599 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1600 bool Invalid = false;
1601 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1605 if (SLoc.isFile() && SLoc.getFile().getContentCache() &&
1606 SLoc.getFile().getContentCache()->OrigEntry == SourceFile)
1607 return FileID::get(I);
1610 // If that still didn't help, try the modules.
1611 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1612 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1613 if (SLoc.isFile() && SLoc.getFile().getContentCache() &&
1614 SLoc.getFile().getContentCache()->OrigEntry == SourceFile)
1615 return FileID::get(-int(I) - 2);
1621 /// Get the source location in \arg FID for the given line:col.
1622 /// Returns null location if \arg FID is not a file SLocEntry.
1623 SourceLocation SourceManager::translateLineCol(FileID FID,
1625 unsigned Col) const {
1626 // Lines are used as a one-based index into a zero-based array. This assert
1627 // checks for possible buffer underruns.
1628 assert(Line && Col && "Line and column should start from 1!");
1630 if (FID.isInvalid())
1631 return SourceLocation();
1633 bool Invalid = false;
1634 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1636 return SourceLocation();
1638 if (!Entry.isFile())
1639 return SourceLocation();
1641 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1643 if (Line == 1 && Col == 1)
1646 ContentCache *Content
1647 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1649 return SourceLocation();
1651 // If this is the first use of line information for this buffer, compute the
1652 // SourceLineCache for it on demand.
1653 if (!Content->SourceLineCache) {
1654 bool MyInvalid = false;
1655 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1657 return SourceLocation();
1660 if (Line > Content->NumLines) {
1661 unsigned Size = Content->getBuffer(Diag, getFileManager())->getBufferSize();
1664 return FileLoc.getLocWithOffset(Size);
1667 const llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, getFileManager());
1668 unsigned FilePos = Content->SourceLineCache[Line - 1];
1669 const char *Buf = Buffer->getBufferStart() + FilePos;
1670 unsigned BufLength = Buffer->getBufferSize() - FilePos;
1672 return FileLoc.getLocWithOffset(FilePos);
1676 // Check that the given column is valid.
1677 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1679 return FileLoc.getLocWithOffset(FilePos + i);
1682 /// Compute a map of macro argument chunks to their expanded source
1683 /// location. Chunks that are not part of a macro argument will map to an
1684 /// invalid source location. e.g. if a file contains one macro argument at
1685 /// offset 100 with length 10, this is how the map will be formed:
1686 /// 0 -> SourceLocation()
1687 /// 100 -> Expanded macro arg location
1688 /// 110 -> SourceLocation()
1689 void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1691 assert(FID.isValid());
1693 // Initially no macro argument chunk is present.
1694 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1699 // Stop if there are no more FileIDs to check.
1701 if (unsigned(ID) >= local_sloc_entry_size())
1703 } else if (ID == -1) {
1707 bool Invalid = false;
1708 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1711 if (Entry.isFile()) {
1712 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1713 if (IncludeLoc.isInvalid())
1715 if (!isInFileID(IncludeLoc, FID))
1716 return; // No more files/macros that may be "contained" in this file.
1718 // Skip the files/macros of the #include'd file, we only care about macros
1719 // that lexed macro arguments from our file.
1720 if (Entry.getFile().NumCreatedFIDs)
1721 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1725 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1727 if (ExpInfo.getExpansionLocStart().isFileID()) {
1728 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1729 return; // No more files/macros that may be "contained" in this file.
1732 if (!ExpInfo.isMacroArgExpansion())
1735 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1736 ExpInfo.getSpellingLoc(),
1737 SourceLocation::getMacroLoc(Entry.getOffset()),
1738 getFileIDSize(FileID::get(ID)));
1742 void SourceManager::associateFileChunkWithMacroArgExp(
1743 MacroArgsMap &MacroArgsCache,
1745 SourceLocation SpellLoc,
1746 SourceLocation ExpansionLoc,
1747 unsigned ExpansionLength) const {
1748 if (!SpellLoc.isFileID()) {
1749 unsigned SpellBeginOffs = SpellLoc.getOffset();
1750 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1752 // The spelling range for this macro argument expansion can span multiple
1753 // consecutive FileID entries. Go through each entry contained in the
1754 // spelling range and if one is itself a macro argument expansion, recurse
1755 // and associate the file chunk that it represents.
1757 FileID SpellFID; // Current FileID in the spelling range.
1758 unsigned SpellRelativeOffs;
1759 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1761 const SLocEntry &Entry = getSLocEntry(SpellFID);
1762 unsigned SpellFIDBeginOffs = Entry.getOffset();
1763 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1764 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1765 const ExpansionInfo &Info = Entry.getExpansion();
1766 if (Info.isMacroArgExpansion()) {
1767 unsigned CurrSpellLength;
1768 if (SpellFIDEndOffs < SpellEndOffs)
1769 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1771 CurrSpellLength = ExpansionLength;
1772 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1773 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1774 ExpansionLoc, CurrSpellLength);
1777 if (SpellFIDEndOffs >= SpellEndOffs)
1778 return; // we covered all FileID entries in the spelling range.
1780 // Move to the next FileID entry in the spelling range.
1781 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1782 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1783 ExpansionLength -= advance;
1785 SpellRelativeOffs = 0;
1789 assert(SpellLoc.isFileID());
1792 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1795 unsigned EndOffs = BeginOffs + ExpansionLength;
1797 // Add a new chunk for this macro argument. A previous macro argument chunk
1798 // may have been lexed again, so e.g. if the map is
1799 // 0 -> SourceLocation()
1800 // 100 -> Expanded loc #1
1801 // 110 -> SourceLocation()
1802 // and we found a new macro FileID that lexed from offset 105 with length 3,
1803 // the new map will be:
1804 // 0 -> SourceLocation()
1805 // 100 -> Expanded loc #1
1806 // 105 -> Expanded loc #2
1807 // 108 -> Expanded loc #1
1808 // 110 -> SourceLocation()
1810 // Since re-lexed macro chunks will always be the same size or less of
1811 // previous chunks, we only need to find where the ending of the new macro
1812 // chunk is mapped to and update the map with new begin/end mappings.
1814 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1816 SourceLocation EndOffsMappedLoc = I->second;
1817 MacroArgsCache[BeginOffs] = ExpansionLoc;
1818 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1821 /// If \arg Loc points inside a function macro argument, the returned
1822 /// location will be the macro location in which the argument was expanded.
1823 /// If a macro argument is used multiple times, the expanded location will
1824 /// be at the first expansion of the argument.
1828 /// Passing a file location pointing at 'foo', will yield a macro location
1829 /// where 'foo' was expanded into.
1831 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1832 if (Loc.isInvalid() || !Loc.isFileID())
1837 std::tie(FID, Offset) = getDecomposedLoc(Loc);
1838 if (FID.isInvalid())
1841 std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1842 if (!MacroArgsCache) {
1843 MacroArgsCache = std::make_unique<MacroArgsMap>();
1844 computeMacroArgsCache(*MacroArgsCache, FID);
1847 assert(!MacroArgsCache->empty());
1848 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1851 unsigned MacroArgBeginOffs = I->first;
1852 SourceLocation MacroArgExpandedLoc = I->second;
1853 if (MacroArgExpandedLoc.isValid())
1854 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1859 std::pair<FileID, unsigned>
1860 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1861 if (FID.isInvalid())
1862 return std::make_pair(FileID(), 0);
1864 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1866 using DecompTy = std::pair<FileID, unsigned>;
1867 auto InsertOp = IncludedLocMap.try_emplace(FID);
1868 DecompTy &DecompLoc = InsertOp.first->second;
1869 if (!InsertOp.second)
1870 return DecompLoc; // already in map.
1872 SourceLocation UpperLoc;
1873 bool Invalid = false;
1874 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1876 if (Entry.isExpansion())
1877 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1879 UpperLoc = Entry.getFile().getIncludeLoc();
1882 if (UpperLoc.isValid())
1883 DecompLoc = getDecomposedLoc(UpperLoc);
1888 /// Given a decomposed source location, move it up the include/expansion stack
1889 /// to the parent source location. If this is possible, return the decomposed
1890 /// version of the parent in Loc and return false. If Loc is the top-level
1891 /// entry, return true and don't modify it.
1892 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1893 const SourceManager &SM) {
1894 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1895 if (UpperLoc.first.isInvalid())
1896 return true; // We reached the top.
1902 /// Return the cache entry for comparing the given file IDs
1903 /// for isBeforeInTranslationUnit.
1904 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1905 FileID RFID) const {
1906 // This is a magic number for limiting the cache size. It was experimentally
1907 // derived from a small Objective-C project (where the cache filled
1908 // out to ~250 items). We can make it larger if necessary.
1909 enum { MagicCacheSize = 300 };
1910 IsBeforeInTUCacheKey Key(LFID, RFID);
1912 // If the cache size isn't too large, do a lookup and if necessary default
1913 // construct an entry. We can then return it to the caller for direct
1914 // use. When they update the value, the cache will get automatically
1916 if (IBTUCache.size() < MagicCacheSize)
1917 return IBTUCache[Key];
1919 // Otherwise, do a lookup that will not construct a new value.
1920 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
1921 if (I != IBTUCache.end())
1924 // Fall back to the overflow value.
1925 return IBTUCacheOverflow;
1928 /// Determines the order of 2 source locations in the translation unit.
1930 /// \returns true if LHS source location comes before RHS, false otherwise.
1931 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1932 SourceLocation RHS) const {
1933 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1937 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1938 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
1940 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
1941 // is a serialized one referring to a file that was removed after we loaded
1943 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
1944 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
1946 std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
1948 return InSameTU.second;
1950 // If we arrived here, the location is either in a built-ins buffer or
1951 // associated with global inline asm. PR5662 and PR22576 are examples.
1953 StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
1954 StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
1955 bool LIsBuiltins = LB == "<built-in>";
1956 bool RIsBuiltins = RB == "<built-in>";
1957 // Sort built-in before non-built-in.
1958 if (LIsBuiltins || RIsBuiltins) {
1959 if (LIsBuiltins != RIsBuiltins)
1961 // Both are in built-in buffers, but from different files. We just claim that
1962 // lower IDs come first.
1963 return LOffs.first < ROffs.first;
1965 bool LIsAsm = LB == "<inline asm>";
1966 bool RIsAsm = RB == "<inline asm>";
1967 // Sort assembler after built-ins, but before the rest.
1968 if (LIsAsm || RIsAsm) {
1969 if (LIsAsm != RIsAsm)
1971 assert(LOffs.first == ROffs.first);
1974 bool LIsScratch = LB == "<scratch space>";
1975 bool RIsScratch = RB == "<scratch space>";
1976 // Sort scratch after inline asm, but before the rest.
1977 if (LIsScratch || RIsScratch) {
1978 if (LIsScratch != RIsScratch)
1980 return LOffs.second < ROffs.second;
1982 llvm_unreachable("Unsortable locations found");
1985 std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
1986 std::pair<FileID, unsigned> &LOffs,
1987 std::pair<FileID, unsigned> &ROffs) const {
1988 // If the source locations are in the same file, just compare offsets.
1989 if (LOffs.first == ROffs.first)
1990 return std::make_pair(true, LOffs.second < ROffs.second);
1992 // If we are comparing a source location with multiple locations in the same
1993 // file, we get a big win by caching the result.
1994 InBeforeInTUCacheEntry &IsBeforeInTUCache =
1995 getInBeforeInTUCache(LOffs.first, ROffs.first);
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 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2000 return std::make_pair(
2001 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2003 // Okay, we missed in the cache, start updating the cache for this query.
2004 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2005 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2007 // We need to find the common ancestor. The only way of doing this is to
2008 // build the complete include chain for one and then walking up the chain
2009 // of the other looking for a match.
2010 // We use a map from FileID to Offset to store the chain. Easier than writing
2011 // a custom set hash info that only depends on the first part of a pair.
2012 using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
2015 LChain.insert(LOffs);
2016 // We catch the case where LOffs is in a file included by ROffs and
2017 // quit early. The other way round unfortunately remains suboptimal.
2018 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2020 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2021 if (MoveUpIncludeHierarchy(ROffs, *this))
2022 break; // Met at topmost file.
2024 if (I != LChain.end())
2027 // If we exited because we found a nearest common ancestor, compare the
2028 // locations within the common file and cache them.
2029 if (LOffs.first == ROffs.first) {
2030 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2031 return std::make_pair(
2032 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2034 // Clear the lookup cache, it depends on a common location.
2035 IsBeforeInTUCache.clear();
2036 return std::make_pair(false, false);
2039 void SourceManager::PrintStats() const {
2040 llvm::errs() << "\n*** Source Manager Stats:\n";
2041 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2042 << " mem buffers mapped.\n";
2043 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2044 << llvm::capacity_in_bytes(LocalSLocEntryTable)
2045 << " bytes of capacity), "
2046 << NextLocalOffset << "B of Sloc address space used.\n";
2047 llvm::errs() << LoadedSLocEntryTable.size()
2048 << " loaded SLocEntries allocated, "
2049 << MaxLoadedOffset - CurrentLoadedOffset
2050 << "B of Sloc address space used.\n";
2052 unsigned NumLineNumsComputed = 0;
2053 unsigned NumFileBytesMapped = 0;
2054 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2055 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2056 NumFileBytesMapped += I->second->getSizeBytesMapped();
2058 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2060 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2061 << NumLineNumsComputed << " files with line #'s computed, "
2062 << NumMacroArgsComputed << " files with macro args computed.\n";
2063 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2064 << NumBinaryProbes << " binary.\n";
2067 LLVM_DUMP_METHOD void SourceManager::dump() const {
2068 llvm::raw_ostream &out = llvm::errs();
2070 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2071 llvm::Optional<unsigned> NextStart) {
2072 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2073 << " <SourceLocation " << Entry.getOffset() << ":";
2075 out << *NextStart << ">\n";
2078 if (Entry.isFile()) {
2079 auto &FI = Entry.getFile();
2080 if (FI.NumCreatedFIDs)
2081 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2083 if (FI.getIncludeLoc().isValid())
2084 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2085 if (auto *CC = FI.getContentCache()) {
2086 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2088 if (CC->BufferOverridden)
2089 out << " contents overridden\n";
2090 if (CC->ContentsEntry != CC->OrigEntry) {
2091 out << " contents from "
2092 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2097 auto &EI = Entry.getExpansion();
2098 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2099 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2100 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2101 << EI.getExpansionLocEnd().getOffset() << ">\n";
2105 // Dump local SLocEntries.
2106 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2107 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2108 ID == NumIDs - 1 ? NextLocalOffset
2109 : LocalSLocEntryTable[ID + 1].getOffset());
2111 // Dump loaded SLocEntries.
2112 llvm::Optional<unsigned> NextStart;
2113 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2114 int ID = -(int)Index - 2;
2115 if (SLocEntryLoaded[Index]) {
2116 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2117 NextStart = LoadedSLocEntryTable[Index].getOffset();
2124 ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2126 /// Return the amount of memory used by memory buffers, breaking down
2127 /// by heap-backed versus mmap'ed memory.
2128 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2129 size_t malloc_bytes = 0;
2130 size_t mmap_bytes = 0;
2132 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2133 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2134 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2135 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2136 mmap_bytes += sized_mapped;
2138 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2139 malloc_bytes += sized_mapped;
2143 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2146 size_t SourceManager::getDataStructureSizes() const {
2147 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2148 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2149 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2150 + llvm::capacity_in_bytes(SLocEntryLoaded)
2151 + llvm::capacity_in_bytes(FileInfos);
2153 if (OverriddenFilesInfo)
2154 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2159 SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2160 StringRef Content) {
2161 // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2163 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2164 new llvm::vfs::InMemoryFileSystem);
2165 InMemoryFileSystem->addFile(
2167 llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2168 /*RequiresNullTerminator=*/false));
2169 // This is passed to `SM` as reference, so the pointer has to be referenced
2170 // in `Environment` so that `FileMgr` can out-live this function scope.
2172 std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2173 // This is passed to `SM` as reference, so the pointer has to be referenced
2174 // by `Environment` due to the same reason above.
2175 Diagnostics = std::make_unique<DiagnosticsEngine>(
2176 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2177 new DiagnosticOptions);
2178 SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2179 FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
2180 SourceLocation(), clang::SrcMgr::C_User);
2181 assert(ID.isValid());
2182 SourceMgr->setMainFileID(ID);