Path: blob/main/contrib/llvm-project/clang/lib/Basic/SourceManager.cpp
35232 views
//===- SourceManager.cpp - Track and cache source files -------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the SourceManager interface.9//10//===----------------------------------------------------------------------===//1112#include "clang/Basic/SourceManager.h"13#include "clang/Basic/Diagnostic.h"14#include "clang/Basic/FileManager.h"15#include "clang/Basic/LLVM.h"16#include "clang/Basic/SourceLocation.h"17#include "clang/Basic/SourceManagerInternals.h"18#include "llvm/ADT/DenseMap.h"19#include "llvm/ADT/MapVector.h"20#include "llvm/ADT/STLExtras.h"21#include "llvm/ADT/SmallVector.h"22#include "llvm/ADT/Statistic.h"23#include "llvm/ADT/StringRef.h"24#include "llvm/ADT/StringSwitch.h"25#include "llvm/Support/Allocator.h"26#include "llvm/Support/Capacity.h"27#include "llvm/Support/Compiler.h"28#include "llvm/Support/Endian.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"35#include <algorithm>36#include <cassert>37#include <cstddef>38#include <cstdint>39#include <memory>40#include <optional>41#include <tuple>42#include <utility>43#include <vector>4445using namespace clang;46using namespace SrcMgr;47using llvm::MemoryBuffer;4849#define DEBUG_TYPE "source-manager"5051// Reaching a limit of 2^31 results in a hard error. This metric allows to track52// if particular invocation of the compiler is close to it.53STATISTIC(MaxUsedSLocBytes, "Maximum number of bytes used by source locations "54"(both loaded and local).");5556//===----------------------------------------------------------------------===//57// SourceManager Helper Classes58//===----------------------------------------------------------------------===//5960/// getSizeBytesMapped - Returns the number of bytes actually mapped for this61/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.62unsigned ContentCache::getSizeBytesMapped() const {63return Buffer ? Buffer->getBufferSize() : 0;64}6566/// Returns the kind of memory used to back the memory buffer for67/// this content cache. This is used for performance analysis.68llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {69if (Buffer == nullptr) {70assert(0 && "Buffer should never be null");71return llvm::MemoryBuffer::MemoryBuffer_Malloc;72}73return Buffer->getBufferKind();74}7576/// 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 arbitrary78/// scratch buffer. If the ContentCache encapsulates a source file, that79/// file is not lazily brought in from disk to satisfy this query.80unsigned ContentCache::getSize() const {81return Buffer ? (unsigned)Buffer->getBufferSize()82: (unsigned)ContentsEntry->getSize();83}8485const char *ContentCache::getInvalidBOM(StringRef BufStr) {86// If the buffer is valid, check to see if it has a UTF Byte Order Mark87// (BOM). We only support UTF-8 with and without a BOM right now. See88// http://en.wikipedia.org/wiki/Byte_order_mark for more information.89const char *InvalidBOM =90llvm::StringSwitch<const char *>(BufStr)91.StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),92"UTF-32 (BE)")93.StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),94"UTF-32 (LE)")95.StartsWith("\xFE\xFF", "UTF-16 (BE)")96.StartsWith("\xFF\xFE", "UTF-16 (LE)")97.StartsWith("\x2B\x2F\x76", "UTF-7")98.StartsWith("\xF7\x64\x4C", "UTF-1")99.StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")100.StartsWith("\x0E\xFE\xFF", "SCSU")101.StartsWith("\xFB\xEE\x28", "BOCU-1")102.StartsWith("\x84\x31\x95\x33", "GB-18030")103.Default(nullptr);104105return InvalidBOM;106}107108std::optional<llvm::MemoryBufferRef>109ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,110SourceLocation Loc) const {111// Lazily create the Buffer for ContentCaches that wrap files. If we already112// computed it, just return what we have.113if (IsBufferInvalid)114return std::nullopt;115if (Buffer)116return Buffer->getMemBufferRef();117if (!ContentsEntry)118return std::nullopt;119120// Start with the assumption that the buffer is invalid to simplify early121// return paths.122IsBufferInvalid = true;123124auto BufferOrError = FM.getBufferForFile(*ContentsEntry, IsFileVolatile);125126// If we were unable to open the file, then we are in an inconsistent127// situation where the content cache referenced a file which no longer128// exists. Most likely, we were using a stat cache with an invalid entry but129// the file could also have been removed during processing. Since we can't130// really deal with this situation, just create an empty buffer.131if (!BufferOrError) {132if (Diag.isDiagnosticInFlight())133Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,134ContentsEntry->getName(),135BufferOrError.getError().message());136else137Diag.Report(Loc, diag::err_cannot_open_file)138<< ContentsEntry->getName() << BufferOrError.getError().message();139140return std::nullopt;141}142143Buffer = std::move(*BufferOrError);144145// Check that the file's size fits in an 'unsigned' (with room for a146// past-the-end value). This is deeply regrettable, but various parts of147// Clang (including elsewhere in this file!) use 'unsigned' to represent file148// offsets, line numbers, string literal lengths, and so on, and fail149// miserably on large source files.150//151// Note: ContentsEntry could be a named pipe, in which case152// ContentsEntry::getSize() could have the wrong size. Use153// MemoryBuffer::getBufferSize() instead.154if (Buffer->getBufferSize() >= std::numeric_limits<unsigned>::max()) {155if (Diag.isDiagnosticInFlight())156Diag.SetDelayedDiagnostic(diag::err_file_too_large,157ContentsEntry->getName());158else159Diag.Report(Loc, diag::err_file_too_large)160<< ContentsEntry->getName();161162return std::nullopt;163}164165// Unless this is a named pipe (in which case we can handle a mismatch),166// check that the file's size is the same as in the file entry (which may167// have come from a stat cache).168if (!ContentsEntry->isNamedPipe() &&169Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()) {170if (Diag.isDiagnosticInFlight())171Diag.SetDelayedDiagnostic(diag::err_file_modified,172ContentsEntry->getName());173else174Diag.Report(Loc, diag::err_file_modified)175<< ContentsEntry->getName();176177return std::nullopt;178}179180// If the buffer is valid, check to see if it has a UTF Byte Order Mark181// (BOM). We only support UTF-8 with and without a BOM right now. See182// http://en.wikipedia.org/wiki/Byte_order_mark for more information.183StringRef BufStr = Buffer->getBuffer();184const char *InvalidBOM = getInvalidBOM(BufStr);185186if (InvalidBOM) {187Diag.Report(Loc, diag::err_unsupported_bom)188<< InvalidBOM << ContentsEntry->getName();189return std::nullopt;190}191192// Buffer has been validated.193IsBufferInvalid = false;194return Buffer->getMemBufferRef();195}196197unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {198auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());199if (IterBool.second)200FilenamesByID.push_back(&*IterBool.first);201return IterBool.first->second;202}203204/// Add a line note to the line table that indicates that there is a \#line or205/// GNU line marker at the specified FID/Offset location which changes the206/// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't207/// change the presumed \#include stack. If it is 1, this is a file entry, if208/// it is 2 then this is a file exit. FileKind specifies whether this is a209/// system header or extern C system header.210void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,211int FilenameID, unsigned EntryExit,212SrcMgr::CharacteristicKind FileKind) {213std::vector<LineEntry> &Entries = LineEntries[FID];214215assert((Entries.empty() || Entries.back().FileOffset < Offset) &&216"Adding line entries out of order!");217218unsigned IncludeOffset = 0;219if (EntryExit == 1) {220// Push #include221IncludeOffset = Offset-1;222} else {223const auto *PrevEntry = Entries.empty() ? nullptr : &Entries.back();224if (EntryExit == 2) {225// Pop #include226assert(PrevEntry && PrevEntry->IncludeOffset &&227"PPDirectives should have caught case when popping empty include "228"stack");229PrevEntry = FindNearestLineEntry(FID, PrevEntry->IncludeOffset);230}231if (PrevEntry) {232IncludeOffset = PrevEntry->IncludeOffset;233if (FilenameID == -1) {234// An unspecified FilenameID means use the previous (or containing)235// filename if available, or the main source file otherwise.236FilenameID = PrevEntry->FilenameID;237}238}239}240241Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,242IncludeOffset));243}244245/// FindNearestLineEntry - Find the line entry nearest to FID that is before246/// it. If there is no line entry before Offset in FID, return null.247const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,248unsigned Offset) {249const std::vector<LineEntry> &Entries = LineEntries[FID];250assert(!Entries.empty() && "No #line entries for this FID after all!");251252// It is very common for the query to be after the last #line, check this253// first.254if (Entries.back().FileOffset <= Offset)255return &Entries.back();256257// Do a binary search to find the maximal element that is still before Offset.258std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);259if (I == Entries.begin())260return nullptr;261return &*--I;262}263264/// Add a new line entry that has already been encoded into265/// the internal representation of the line table.266void LineTableInfo::AddEntry(FileID FID,267const std::vector<LineEntry> &Entries) {268LineEntries[FID] = Entries;269}270271/// getLineTableFilenameID - Return the uniqued ID for the specified filename.272unsigned SourceManager::getLineTableFilenameID(StringRef Name) {273return getLineTable().getLineTableFilenameID(Name);274}275276/// AddLineNote - Add a line note to the line table for the FileID and offset277/// specified by Loc. If FilenameID is -1, it is considered to be278/// unspecified.279void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,280int FilenameID, bool IsFileEntry,281bool IsFileExit,282SrcMgr::CharacteristicKind FileKind) {283std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);284285bool Invalid = false;286SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);287if (!Entry.isFile() || Invalid)288return;289290SrcMgr::FileInfo &FileInfo = Entry.getFile();291292// Remember that this file has #line directives now if it doesn't already.293FileInfo.setHasLineDirectives();294295(void) getLineTable();296297unsigned EntryExit = 0;298if (IsFileEntry)299EntryExit = 1;300else if (IsFileExit)301EntryExit = 2;302303LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,304EntryExit, FileKind);305}306307LineTableInfo &SourceManager::getLineTable() {308if (!LineTable)309LineTable.reset(new LineTableInfo());310return *LineTable;311}312313//===----------------------------------------------------------------------===//314// Private 'Create' methods.315//===----------------------------------------------------------------------===//316317SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,318bool UserFilesAreVolatile)319: Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {320clearIDTables();321Diag.setSourceManager(this);322}323324SourceManager::~SourceManager() {325// Delete FileEntry objects corresponding to content caches. Since the actual326// content cache objects are bump pointer allocated, we just have to run the327// dtors, but we call the deallocate method for completeness.328for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {329if (MemBufferInfos[i]) {330MemBufferInfos[i]->~ContentCache();331ContentCacheAlloc.Deallocate(MemBufferInfos[i]);332}333}334for (auto I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {335if (I->second) {336I->second->~ContentCache();337ContentCacheAlloc.Deallocate(I->second);338}339}340}341342void SourceManager::clearIDTables() {343MainFileID = FileID();344LocalSLocEntryTable.clear();345LoadedSLocEntryTable.clear();346SLocEntryLoaded.clear();347SLocEntryOffsetLoaded.clear();348LastLineNoFileIDQuery = FileID();349LastLineNoContentCache = nullptr;350LastFileIDLookup = FileID();351352if (LineTable)353LineTable->clear();354355// Use up FileID #0 as an invalid expansion.356NextLocalOffset = 0;357CurrentLoadedOffset = MaxLoadedOffset;358createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);359}360361bool SourceManager::isMainFile(const FileEntry &SourceFile) {362assert(MainFileID.isValid() && "expected initialized SourceManager");363if (auto *FE = getFileEntryForID(MainFileID))364return FE->getUID() == SourceFile.getUID();365return false;366}367368void SourceManager::initializeForReplay(const SourceManager &Old) {369assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");370371auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {372auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;373Clone->OrigEntry = Cache->OrigEntry;374Clone->ContentsEntry = Cache->ContentsEntry;375Clone->BufferOverridden = Cache->BufferOverridden;376Clone->IsFileVolatile = Cache->IsFileVolatile;377Clone->IsTransient = Cache->IsTransient;378Clone->setUnownedBuffer(Cache->getBufferIfLoaded());379return Clone;380};381382// Ensure all SLocEntries are loaded from the external source.383for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)384if (!Old.SLocEntryLoaded[I])385Old.loadSLocEntry(I, nullptr);386387// Inherit any content cache data from the old source manager.388for (auto &FileInfo : Old.FileInfos) {389SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];390if (Slot)391continue;392Slot = CloneContentCache(FileInfo.second);393}394}395396ContentCache &SourceManager::getOrCreateContentCache(FileEntryRef FileEnt,397bool isSystemFile) {398// Do we already have information about this file?399ContentCache *&Entry = FileInfos[FileEnt];400if (Entry)401return *Entry;402403// Nope, create a new Cache entry.404Entry = ContentCacheAlloc.Allocate<ContentCache>();405406if (OverriddenFilesInfo) {407// If the file contents are overridden with contents from another file,408// pass that file to ContentCache.409auto overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);410if (overI == OverriddenFilesInfo->OverriddenFiles.end())411new (Entry) ContentCache(FileEnt);412else413new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt414: overI->second,415overI->second);416} else {417new (Entry) ContentCache(FileEnt);418}419420Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;421Entry->IsTransient = FilesAreTransient;422Entry->BufferOverridden |= FileEnt.isNamedPipe();423424return *Entry;425}426427/// Create a new ContentCache for the specified memory buffer.428/// This does no caching.429ContentCache &SourceManager::createMemBufferContentCache(430std::unique_ptr<llvm::MemoryBuffer> Buffer) {431// Add a new ContentCache to the MemBufferInfos list and return it.432ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();433new (Entry) ContentCache();434MemBufferInfos.push_back(Entry);435Entry->setBuffer(std::move(Buffer));436return *Entry;437}438439const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,440bool *Invalid) const {441return const_cast<SourceManager *>(this)->loadSLocEntry(Index, Invalid);442}443444SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index, bool *Invalid) {445assert(!SLocEntryLoaded[Index]);446if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {447if (Invalid)448*Invalid = true;449// If the file of the SLocEntry changed we could still have loaded it.450if (!SLocEntryLoaded[Index]) {451// Try to recover; create a SLocEntry so the rest of clang can handle it.452if (!FakeSLocEntryForRecovery)453FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(SLocEntry::get(4540, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),455SrcMgr::C_User, "")));456return *FakeSLocEntryForRecovery;457}458}459460return LoadedSLocEntryTable[Index];461}462463std::pair<int, SourceLocation::UIntTy>464SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,465SourceLocation::UIntTy TotalSize) {466assert(ExternalSLocEntries && "Don't have an external sloc source");467// Make sure we're not about to run out of source locations.468if (CurrentLoadedOffset < TotalSize ||469CurrentLoadedOffset - TotalSize < NextLocalOffset) {470return std::make_pair(0, 0);471}472LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);473SLocEntryLoaded.resize(LoadedSLocEntryTable.size());474SLocEntryOffsetLoaded.resize(LoadedSLocEntryTable.size());475CurrentLoadedOffset -= TotalSize;476updateSlocUsageStats();477int BaseID = -int(LoadedSLocEntryTable.size()) - 1;478LoadedSLocEntryAllocBegin.push_back(FileID::get(BaseID));479return std::make_pair(BaseID, CurrentLoadedOffset);480}481482/// As part of recovering from missing or changed content, produce a483/// fake, non-empty buffer.484llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery() const {485if (!FakeBufferForRecovery)486FakeBufferForRecovery =487llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");488489return *FakeBufferForRecovery;490}491492/// As part of recovering from missing or changed content, produce a493/// fake content cache.494SrcMgr::ContentCache &SourceManager::getFakeContentCacheForRecovery() const {495if (!FakeContentCacheForRecovery) {496FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();497FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery());498}499return *FakeContentCacheForRecovery;500}501502/// Returns the previous in-order FileID or an invalid FileID if there503/// is no previous one.504FileID SourceManager::getPreviousFileID(FileID FID) const {505if (FID.isInvalid())506return FileID();507508int ID = FID.ID;509if (ID == -1)510return FileID();511512if (ID > 0) {513if (ID-1 == 0)514return FileID();515} else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {516return FileID();517}518519return FileID::get(ID-1);520}521522/// Returns the next in-order FileID or an invalid FileID if there is523/// no next one.524FileID SourceManager::getNextFileID(FileID FID) const {525if (FID.isInvalid())526return FileID();527528int ID = FID.ID;529if (ID > 0) {530if (unsigned(ID+1) >= local_sloc_entry_size())531return FileID();532} else if (ID+1 >= -1) {533return FileID();534}535536return FileID::get(ID+1);537}538539//===----------------------------------------------------------------------===//540// Methods to create new FileID's and macro expansions.541//===----------------------------------------------------------------------===//542543/// Create a new FileID that represents the specified file544/// being \#included from the specified IncludePosition.545FileID SourceManager::createFileID(FileEntryRef SourceFile,546SourceLocation IncludePos,547SrcMgr::CharacteristicKind FileCharacter,548int LoadedID,549SourceLocation::UIntTy LoadedOffset) {550SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile,551isSystem(FileCharacter));552553// If this is a named pipe, immediately load the buffer to ensure subsequent554// calls to ContentCache::getSize() are accurate.555if (IR.ContentsEntry->isNamedPipe())556(void)IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());557558return createFileIDImpl(IR, SourceFile.getName(), IncludePos, FileCharacter,559LoadedID, LoadedOffset);560}561562/// Create a new FileID that represents the specified memory buffer.563///564/// This does no caching of the buffer and takes ownership of the565/// MemoryBuffer, so only pass a MemoryBuffer to this once.566FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,567SrcMgr::CharacteristicKind FileCharacter,568int LoadedID,569SourceLocation::UIntTy LoadedOffset,570SourceLocation IncludeLoc) {571StringRef Name = Buffer->getBufferIdentifier();572return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name,573IncludeLoc, FileCharacter, LoadedID, LoadedOffset);574}575576/// Create a new FileID that represents the specified memory buffer.577///578/// This does not take ownership of the MemoryBuffer. The memory buffer must579/// outlive the SourceManager.580FileID SourceManager::createFileID(const llvm::MemoryBufferRef &Buffer,581SrcMgr::CharacteristicKind FileCharacter,582int LoadedID,583SourceLocation::UIntTy LoadedOffset,584SourceLocation IncludeLoc) {585return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter,586LoadedID, LoadedOffset, IncludeLoc);587}588589/// Get the FileID for \p SourceFile if it exists. Otherwise, create a590/// new FileID for the \p SourceFile.591FileID592SourceManager::getOrCreateFileID(FileEntryRef SourceFile,593SrcMgr::CharacteristicKind FileCharacter) {594FileID ID = translateFile(SourceFile);595return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(),596FileCharacter);597}598599/// createFileID - Create a new FileID for the specified ContentCache and600/// include position. This works regardless of whether the ContentCache601/// corresponds to a file or some other input source.602FileID SourceManager::createFileIDImpl(ContentCache &File, StringRef Filename,603SourceLocation IncludePos,604SrcMgr::CharacteristicKind FileCharacter,605int LoadedID,606SourceLocation::UIntTy LoadedOffset) {607if (LoadedID < 0) {608assert(LoadedID != -1 && "Loading sentinel FileID");609unsigned Index = unsigned(-LoadedID) - 2;610assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");611assert(!SLocEntryLoaded[Index] && "FileID already loaded");612LoadedSLocEntryTable[Index] = SLocEntry::get(613LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));614SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] = true;615return FileID::get(LoadedID);616}617unsigned FileSize = File.getSize();618if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&619NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {620Diag.Report(IncludePos, diag::err_sloc_space_too_large);621noteSLocAddressSpaceUsage(Diag);622return FileID();623}624LocalSLocEntryTable.push_back(625SLocEntry::get(NextLocalOffset,626FileInfo::get(IncludePos, File, FileCharacter, Filename)));627// We do a +1 here because we want a SourceLocation that means "the end of the628// file", e.g. for the "no newline at the end of the file" diagnostic.629NextLocalOffset += FileSize + 1;630updateSlocUsageStats();631632// Set LastFileIDLookup to the newly created file. The next getFileID call is633// almost guaranteed to be from that file.634FileID FID = FileID::get(LocalSLocEntryTable.size()-1);635return LastFileIDLookup = FID;636}637638SourceLocation SourceManager::createMacroArgExpansionLoc(639SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned Length) {640ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,641ExpansionLoc);642return createExpansionLocImpl(Info, Length);643}644645SourceLocation SourceManager::createExpansionLoc(646SourceLocation SpellingLoc, SourceLocation ExpansionLocStart,647SourceLocation ExpansionLocEnd, unsigned Length,648bool ExpansionIsTokenRange, int LoadedID,649SourceLocation::UIntTy LoadedOffset) {650ExpansionInfo Info = ExpansionInfo::create(651SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);652return createExpansionLocImpl(Info, Length, LoadedID, LoadedOffset);653}654655SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,656SourceLocation TokenStart,657SourceLocation TokenEnd) {658assert(getFileID(TokenStart) == getFileID(TokenEnd) &&659"token spans multiple files");660return createExpansionLocImpl(661ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),662TokenEnd.getOffset() - TokenStart.getOffset());663}664665SourceLocation666SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,667unsigned Length, int LoadedID,668SourceLocation::UIntTy LoadedOffset) {669if (LoadedID < 0) {670assert(LoadedID != -1 && "Loading sentinel FileID");671unsigned Index = unsigned(-LoadedID) - 2;672assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");673assert(!SLocEntryLoaded[Index] && "FileID already loaded");674LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);675SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] = true;676return SourceLocation::getMacroLoc(LoadedOffset);677}678LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));679if (NextLocalOffset + Length + 1 <= NextLocalOffset ||680NextLocalOffset + Length + 1 > CurrentLoadedOffset) {681Diag.Report(SourceLocation(), diag::err_sloc_space_too_large);682// FIXME: call `noteSLocAddressSpaceUsage` to report details to users and683// use a source location from `Info` to point at an error.684// Currently, both cause Clang to run indefinitely, this needs to be fixed.685// FIXME: return an error instead of crashing. Returning invalid source686// locations causes compiler to run indefinitely.687llvm::report_fatal_error("ran out of source locations");688}689// See createFileID for that +1.690NextLocalOffset += Length + 1;691updateSlocUsageStats();692return SourceLocation::getMacroLoc(NextLocalOffset - (Length + 1));693}694695std::optional<llvm::MemoryBufferRef>696SourceManager::getMemoryBufferForFileOrNone(FileEntryRef File) {697SrcMgr::ContentCache &IR = getOrCreateContentCache(File);698return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());699}700701void SourceManager::overrideFileContents(702FileEntryRef SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) {703SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile);704705IR.setBuffer(std::move(Buffer));706IR.BufferOverridden = true;707708getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);709}710711void SourceManager::overrideFileContents(const FileEntry *SourceFile,712FileEntryRef NewFile) {713assert(SourceFile->getSize() == NewFile.getSize() &&714"Different sizes, use the FileManager to create a virtual file with "715"the correct size");716assert(FileInfos.find_as(SourceFile) == FileInfos.end() &&717"This function should be called at the initialization stage, before "718"any parsing occurs.");719// FileEntryRef is not default-constructible.720auto Pair = getOverriddenFilesInfo().OverriddenFiles.insert(721std::make_pair(SourceFile, NewFile));722if (!Pair.second)723Pair.first->second = NewFile;724}725726OptionalFileEntryRef727SourceManager::bypassFileContentsOverride(FileEntryRef File) {728assert(isFileOverridden(&File.getFileEntry()));729OptionalFileEntryRef BypassFile = FileMgr.getBypassFile(File);730731// If the file can't be found in the FS, give up.732if (!BypassFile)733return std::nullopt;734735(void)getOrCreateContentCache(*BypassFile);736return BypassFile;737}738739void SourceManager::setFileIsTransient(FileEntryRef File) {740getOrCreateContentCache(File).IsTransient = true;741}742743std::optional<StringRef>744SourceManager::getNonBuiltinFilenameForID(FileID FID) const {745if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))746if (Entry->getFile().getContentCache().OrigEntry)747return Entry->getFile().getName();748return std::nullopt;749}750751StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {752auto B = getBufferDataOrNone(FID);753if (Invalid)754*Invalid = !B;755return B ? *B : "<<<<<INVALID SOURCE LOCATION>>>>>";756}757758std::optional<StringRef>759SourceManager::getBufferDataIfLoaded(FileID FID) const {760if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))761return Entry->getFile().getContentCache().getBufferDataIfLoaded();762return std::nullopt;763}764765std::optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const {766if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))767if (auto B = Entry->getFile().getContentCache().getBufferOrNone(768Diag, getFileManager(), SourceLocation()))769return B->getBuffer();770return std::nullopt;771}772773//===----------------------------------------------------------------------===//774// SourceLocation manipulation methods.775//===----------------------------------------------------------------------===//776777/// Return the FileID for a SourceLocation.778///779/// This is the cache-miss path of getFileID. Not as hot as that function, but780/// still very important. It is responsible for finding the entry in the781/// SLocEntry tables that contains the specified location.782FileID SourceManager::getFileIDSlow(SourceLocation::UIntTy SLocOffset) const {783if (!SLocOffset)784return FileID::get(0);785786// Now it is time to search for the correct file. See where the SLocOffset787// sits in the global view and consult local or loaded buffers for it.788if (SLocOffset < NextLocalOffset)789return getFileIDLocal(SLocOffset);790return getFileIDLoaded(SLocOffset);791}792793/// Return the FileID for a SourceLocation with a low offset.794///795/// This function knows that the SourceLocation is in a local buffer, not a796/// loaded one.797FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {798assert(SLocOffset < NextLocalOffset && "Bad function choice");799800// After the first and second level caches, I see two common sorts of801// behavior: 1) a lot of searched FileID's are "near" the cached file802// location or are "near" the cached expansion location. 2) others are just803// completely random and may be a very long way away.804//805// To handle this, we do a linear search for up to 8 steps to catch #1 quickly806// then we fall back to a less cache efficient, but more scalable, binary807// search to find the location.808809// See if this is near the file point - worst case we start scanning from the810// most newly created FileID.811812// LessIndex - This is the lower bound of the range that we're searching.813// We know that the offset corresponding to the FileID is less than814// SLocOffset.815unsigned LessIndex = 0;816// upper bound of the search range.817unsigned GreaterIndex = LocalSLocEntryTable.size();818if (LastFileIDLookup.ID >= 0) {819// Use the LastFileIDLookup to prune the search space.820if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)821LessIndex = LastFileIDLookup.ID;822else823GreaterIndex = LastFileIDLookup.ID;824}825826// Find the FileID that contains this.827unsigned NumProbes = 0;828while (true) {829--GreaterIndex;830assert(GreaterIndex < LocalSLocEntryTable.size());831if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {832FileID Res = FileID::get(int(GreaterIndex));833// Remember it. We have good locality across FileID lookups.834LastFileIDLookup = Res;835NumLinearScans += NumProbes+1;836return Res;837}838if (++NumProbes == 8)839break;840}841842NumProbes = 0;843while (true) {844unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;845SourceLocation::UIntTy MidOffset =846getLocalSLocEntry(MiddleIndex).getOffset();847848++NumProbes;849850// If the offset of the midpoint is too large, chop the high side of the851// range to the midpoint.852if (MidOffset > SLocOffset) {853GreaterIndex = MiddleIndex;854continue;855}856857// If the middle index contains the value, succeed and return.858if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||859SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {860FileID Res = FileID::get(MiddleIndex);861862// Remember it. We have good locality across FileID lookups.863LastFileIDLookup = Res;864NumBinaryProbes += NumProbes;865return Res;866}867868// Otherwise, move the low-side up to the middle index.869LessIndex = MiddleIndex;870}871}872873/// Return the FileID for a SourceLocation with a high offset.874///875/// This function knows that the SourceLocation is in a loaded buffer, not a876/// local one.877FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const {878if (SLocOffset < CurrentLoadedOffset) {879assert(0 && "Invalid SLocOffset or bad function choice");880return FileID();881}882883return FileID::get(ExternalSLocEntries->getSLocEntryID(SLocOffset));884}885886SourceLocation SourceManager::887getExpansionLocSlowCase(SourceLocation Loc) const {888do {889// Note: If Loc indicates an offset into a token that came from a macro890// expansion (e.g. the 5th character of the token) we do not want to add891// this offset when going to the expansion location. The expansion892// location is the macro invocation, which the offset has nothing to do893// with. This is unlike when we get the spelling loc, because the offset894// directly correspond to the token whose spelling we're inspecting.895Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();896} while (!Loc.isFileID());897898return Loc;899}900901SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {902do {903std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);904Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();905Loc = Loc.getLocWithOffset(LocInfo.second);906} while (!Loc.isFileID());907return Loc;908}909910SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {911do {912if (isMacroArgExpansion(Loc))913Loc = getImmediateSpellingLoc(Loc);914else915Loc = getImmediateExpansionRange(Loc).getBegin();916} while (!Loc.isFileID());917return Loc;918}919920921std::pair<FileID, unsigned>922SourceManager::getDecomposedExpansionLocSlowCase(923const SrcMgr::SLocEntry *E) const {924// If this is an expansion record, walk through all the expansion points.925FileID FID;926SourceLocation Loc;927unsigned Offset;928do {929Loc = E->getExpansion().getExpansionLocStart();930931FID = getFileID(Loc);932E = &getSLocEntry(FID);933Offset = Loc.getOffset()-E->getOffset();934} while (!Loc.isFileID());935936return std::make_pair(FID, Offset);937}938939std::pair<FileID, unsigned>940SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,941unsigned Offset) const {942// If this is an expansion record, walk through all the expansion points.943FileID FID;944SourceLocation Loc;945do {946Loc = E->getExpansion().getSpellingLoc();947Loc = Loc.getLocWithOffset(Offset);948949FID = getFileID(Loc);950E = &getSLocEntry(FID);951Offset = Loc.getOffset()-E->getOffset();952} while (!Loc.isFileID());953954return std::make_pair(FID, Offset);955}956957/// getImmediateSpellingLoc - Given a SourceLocation object, return the958/// spelling location referenced by the ID. This is the first level down959/// towards the place where the characters that make up the lexed token can be960/// found. This should not generally be used by clients.961SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{962if (Loc.isFileID()) return Loc;963std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);964Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();965return Loc.getLocWithOffset(LocInfo.second);966}967968/// Return the filename of the file containing a SourceLocation.969StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {970if (OptionalFileEntryRef F = getFileEntryRefForID(getFileID(SpellingLoc)))971return F->getName();972return StringRef();973}974975/// getImmediateExpansionRange - Loc is required to be an expansion location.976/// Return the start/end of the expansion information.977CharSourceRange978SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {979assert(Loc.isMacroID() && "Not a macro expansion loc!");980const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();981return Expansion.getExpansionLocRange();982}983984SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {985while (isMacroArgExpansion(Loc))986Loc = getImmediateSpellingLoc(Loc);987return Loc;988}989990/// getExpansionRange - Given a SourceLocation object, return the range of991/// tokens covered by the expansion in the ultimate file.992CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {993if (Loc.isFileID())994return CharSourceRange(SourceRange(Loc, Loc), true);995996CharSourceRange Res = getImmediateExpansionRange(Loc);997998// Fully resolve the start and end locations to their ultimate expansion999// points.1000while (!Res.getBegin().isFileID())1001Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());1002while (!Res.getEnd().isFileID()) {1003CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());1004Res.setEnd(EndRange.getEnd());1005Res.setTokenRange(EndRange.isTokenRange());1006}1007return Res;1008}10091010bool SourceManager::isMacroArgExpansion(SourceLocation Loc,1011SourceLocation *StartLoc) const {1012if (!Loc.isMacroID()) return false;10131014FileID FID = getFileID(Loc);1015const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();1016if (!Expansion.isMacroArgExpansion()) return false;10171018if (StartLoc)1019*StartLoc = Expansion.getExpansionLocStart();1020return true;1021}10221023bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {1024if (!Loc.isMacroID()) return false;10251026FileID FID = getFileID(Loc);1027const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();1028return Expansion.isMacroBodyExpansion();1029}10301031bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,1032SourceLocation *MacroBegin) const {1033assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");10341035std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);1036if (DecompLoc.second > 0)1037return false; // Does not point at the start of expansion range.10381039bool Invalid = false;1040const SrcMgr::ExpansionInfo &ExpInfo =1041getSLocEntry(DecompLoc.first, &Invalid).getExpansion();1042if (Invalid)1043return false;1044SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();10451046if (ExpInfo.isMacroArgExpansion()) {1047// For macro argument expansions, check if the previous FileID is part of1048// the same argument expansion, in which case this Loc is not at the1049// beginning of the expansion.1050FileID PrevFID = getPreviousFileID(DecompLoc.first);1051if (!PrevFID.isInvalid()) {1052const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);1053if (Invalid)1054return false;1055if (PrevEntry.isExpansion() &&1056PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)1057return false;1058}1059}10601061if (MacroBegin)1062*MacroBegin = ExpLoc;1063return true;1064}10651066bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,1067SourceLocation *MacroEnd) const {1068assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");10691070FileID FID = getFileID(Loc);1071SourceLocation NextLoc = Loc.getLocWithOffset(1);1072if (isInFileID(NextLoc, FID))1073return false; // Does not point at the end of expansion range.10741075bool Invalid = false;1076const SrcMgr::ExpansionInfo &ExpInfo =1077getSLocEntry(FID, &Invalid).getExpansion();1078if (Invalid)1079return false;10801081if (ExpInfo.isMacroArgExpansion()) {1082// For macro argument expansions, check if the next FileID is part of the1083// same argument expansion, in which case this Loc is not at the end of the1084// expansion.1085FileID NextFID = getNextFileID(FID);1086if (!NextFID.isInvalid()) {1087const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);1088if (Invalid)1089return false;1090if (NextEntry.isExpansion() &&1091NextEntry.getExpansion().getExpansionLocStart() ==1092ExpInfo.getExpansionLocStart())1093return false;1094}1095}10961097if (MacroEnd)1098*MacroEnd = ExpInfo.getExpansionLocEnd();1099return true;1100}11011102//===----------------------------------------------------------------------===//1103// Queries about the code at a SourceLocation.1104//===----------------------------------------------------------------------===//11051106/// getCharacterData - Return a pointer to the start of the specified location1107/// in the appropriate MemoryBuffer.1108const char *SourceManager::getCharacterData(SourceLocation SL,1109bool *Invalid) const {1110// Note that this is a hot function in the getSpelling() path, which is1111// heavily used by -E mode.1112std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);11131114// Note that calling 'getBuffer()' may lazily page in a source file.1115bool CharDataInvalid = false;1116const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);1117if (CharDataInvalid || !Entry.isFile()) {1118if (Invalid)1119*Invalid = true;11201121return "<<<<INVALID BUFFER>>>>";1122}1123std::optional<llvm::MemoryBufferRef> Buffer =1124Entry.getFile().getContentCache().getBufferOrNone(Diag, getFileManager(),1125SourceLocation());1126if (Invalid)1127*Invalid = !Buffer;1128return Buffer ? Buffer->getBufferStart() + LocInfo.second1129: "<<<<INVALID BUFFER>>>>";1130}11311132/// getColumnNumber - Return the column # for the specified file position.1133/// this is significantly cheaper to compute than the line number.1134unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,1135bool *Invalid) const {1136std::optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID);1137if (Invalid)1138*Invalid = !MemBuf;11391140if (!MemBuf)1141return 1;11421143// It is okay to request a position just past the end of the buffer.1144if (FilePos > MemBuf->getBufferSize()) {1145if (Invalid)1146*Invalid = true;1147return 1;1148}11491150const char *Buf = MemBuf->getBufferStart();1151// See if we just calculated the line number for this FilePos and can use1152// that to lookup the start of the line instead of searching for it.1153if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache &&1154LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()) {1155const unsigned *SourceLineCache =1156LastLineNoContentCache->SourceLineCache.begin();1157unsigned LineStart = SourceLineCache[LastLineNoResult - 1];1158unsigned LineEnd = SourceLineCache[LastLineNoResult];1159if (FilePos >= LineStart && FilePos < LineEnd) {1160// LineEnd is the LineStart of the next line.1161// A line ends with separator LF or CR+LF on Windows.1162// FilePos might point to the last separator,1163// but we need a column number at most 1 + the last column.1164if (FilePos + 1 == LineEnd && FilePos > LineStart) {1165if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')1166--FilePos;1167}1168return FilePos - LineStart + 1;1169}1170}11711172unsigned LineStart = FilePos;1173while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')1174--LineStart;1175return FilePos-LineStart+1;1176}11771178// isInvalid - Return the result of calling loc.isInvalid(), and1179// if Invalid is not null, set its value to same.1180template<typename LocType>1181static bool isInvalid(LocType Loc, bool *Invalid) {1182bool MyInvalid = Loc.isInvalid();1183if (Invalid)1184*Invalid = MyInvalid;1185return MyInvalid;1186}11871188unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,1189bool *Invalid) const {1190if (isInvalid(Loc, Invalid)) return 0;1191std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);1192return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);1193}11941195unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,1196bool *Invalid) const {1197if (isInvalid(Loc, Invalid)) return 0;1198std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);1199return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);1200}12011202unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,1203bool *Invalid) const {1204PresumedLoc PLoc = getPresumedLoc(Loc);1205if (isInvalid(PLoc, Invalid)) return 0;1206return PLoc.getColumn();1207}12081209// Check if mutli-byte word x has bytes between m and n, included. This may also1210// catch bytes equal to n + 1.1211// The returned value holds a 0x80 at each byte position that holds a match.1212// see http://graphics.stanford.edu/~seander/bithacks.html#HasBetweenInWord1213template <class T>1214static constexpr inline T likelyhasbetween(T x, unsigned char m,1215unsigned char n) {1216return ((x - ~static_cast<T>(0) / 255 * (n + 1)) & ~x &1217((x & ~static_cast<T>(0) / 255 * 127) +1218(~static_cast<T>(0) / 255 * (127 - (m - 1))))) &1219~static_cast<T>(0) / 255 * 128;1220}12211222LineOffsetMapping LineOffsetMapping::get(llvm::MemoryBufferRef Buffer,1223llvm::BumpPtrAllocator &Alloc) {12241225// Find the file offsets of all of the *physical* source lines. This does1226// not look at trigraphs, escaped newlines, or anything else tricky.1227SmallVector<unsigned, 256> LineOffsets;12281229// Line #1 starts at char 0.1230LineOffsets.push_back(0);12311232const unsigned char *Start = (const unsigned char *)Buffer.getBufferStart();1233const unsigned char *End = (const unsigned char *)Buffer.getBufferEnd();1234const unsigned char *Buf = Start;12351236uint64_t Word;12371238// scan sizeof(Word) bytes at a time for new lines.1239// This is much faster than scanning each byte independently.1240if ((unsigned long)(End - Start) > sizeof(Word)) {1241do {1242Word = llvm::support::endian::read64(Buf, llvm::endianness::little);1243// no new line => jump over sizeof(Word) bytes.1244auto Mask = likelyhasbetween(Word, '\n', '\r');1245if (!Mask) {1246Buf += sizeof(Word);1247continue;1248}12491250// At that point, Mask contains 0x80 set at each byte that holds a value1251// in [\n, \r + 1 [12521253// Scan for the next newline - it's very likely there's one.1254unsigned N = llvm::countr_zero(Mask) - 7; // -7 because 0x80 is the marker1255Word >>= N;1256Buf += N / 8 + 1;1257unsigned char Byte = Word;1258switch (Byte) {1259case '\r':1260// If this is \r\n, skip both characters.1261if (*Buf == '\n') {1262++Buf;1263}1264[[fallthrough]];1265case '\n':1266LineOffsets.push_back(Buf - Start);1267};1268} while (Buf < End - sizeof(Word) - 1);1269}12701271// Handle tail using a regular check.1272while (Buf < End) {1273if (*Buf == '\n') {1274LineOffsets.push_back(Buf - Start + 1);1275} else if (*Buf == '\r') {1276// If this is \r\n, skip both characters.1277if (Buf + 1 < End && Buf[1] == '\n') {1278++Buf;1279}1280LineOffsets.push_back(Buf - Start + 1);1281}1282++Buf;1283}12841285return LineOffsetMapping(LineOffsets, Alloc);1286}12871288LineOffsetMapping::LineOffsetMapping(ArrayRef<unsigned> LineOffsets,1289llvm::BumpPtrAllocator &Alloc)1290: Storage(Alloc.Allocate<unsigned>(LineOffsets.size() + 1)) {1291Storage[0] = LineOffsets.size();1292std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1);1293}12941295/// getLineNumber - Given a SourceLocation, return the spelling line number1296/// for the position indicated. This requires building and caching a table of1297/// line offsets for the MemoryBuffer, so this is not cheap: use only when1298/// about to emit a diagnostic.1299unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,1300bool *Invalid) const {1301if (FID.isInvalid()) {1302if (Invalid)1303*Invalid = true;1304return 1;1305}13061307const ContentCache *Content;1308if (LastLineNoFileIDQuery == FID)1309Content = LastLineNoContentCache;1310else {1311bool MyInvalid = false;1312const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);1313if (MyInvalid || !Entry.isFile()) {1314if (Invalid)1315*Invalid = true;1316return 1;1317}13181319Content = &Entry.getFile().getContentCache();1320}13211322// If this is the first use of line information for this buffer, compute the1323// SourceLineCache for it on demand.1324if (!Content->SourceLineCache) {1325std::optional<llvm::MemoryBufferRef> Buffer =1326Content->getBufferOrNone(Diag, getFileManager(), SourceLocation());1327if (Invalid)1328*Invalid = !Buffer;1329if (!Buffer)1330return 1;13311332Content->SourceLineCache =1333LineOffsetMapping::get(*Buffer, ContentCacheAlloc);1334} else if (Invalid)1335*Invalid = false;13361337// Okay, we know we have a line number table. Do a binary search to find the1338// line number that this character position lands on.1339const unsigned *SourceLineCache = Content->SourceLineCache.begin();1340const unsigned *SourceLineCacheStart = SourceLineCache;1341const unsigned *SourceLineCacheEnd = Content->SourceLineCache.end();13421343unsigned QueriedFilePos = FilePos+1;13441345// FIXME: I would like to be convinced that this code is worth being as1346// complicated as it is, binary search isn't that slow.1347//1348// If it is worth being optimized, then in my opinion it could be more1349// performant, simpler, and more obviously correct by just "galloping" outward1350// from the queried file position. In fact, this could be incorporated into a1351// generic algorithm such as lower_bound_with_hint.1352//1353// If someone gives me a test case where this matters, and I will do it! - DWD13541355// If the previous query was to the same file, we know both the file pos from1356// that query and the line number returned. This allows us to narrow the1357// search space from the entire file to something near the match.1358if (LastLineNoFileIDQuery == FID) {1359if (QueriedFilePos >= LastLineNoFilePos) {1360// FIXME: Potential overflow?1361SourceLineCache = SourceLineCache+LastLineNoResult-1;13621363// The query is likely to be nearby the previous one. Here we check to1364// see if it is within 5, 10 or 20 lines. It can be far away in cases1365// where big comment blocks and vertical whitespace eat up lines but1366// contribute no tokens.1367if (SourceLineCache+5 < SourceLineCacheEnd) {1368if (SourceLineCache[5] > QueriedFilePos)1369SourceLineCacheEnd = SourceLineCache+5;1370else if (SourceLineCache+10 < SourceLineCacheEnd) {1371if (SourceLineCache[10] > QueriedFilePos)1372SourceLineCacheEnd = SourceLineCache+10;1373else if (SourceLineCache+20 < SourceLineCacheEnd) {1374if (SourceLineCache[20] > QueriedFilePos)1375SourceLineCacheEnd = SourceLineCache+20;1376}1377}1378}1379} else {1380if (LastLineNoResult < Content->SourceLineCache.size())1381SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;1382}1383}13841385const unsigned *Pos =1386std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);1387unsigned LineNo = Pos-SourceLineCacheStart;13881389LastLineNoFileIDQuery = FID;1390LastLineNoContentCache = Content;1391LastLineNoFilePos = QueriedFilePos;1392LastLineNoResult = LineNo;1393return LineNo;1394}13951396unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,1397bool *Invalid) const {1398if (isInvalid(Loc, Invalid)) return 0;1399std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);1400return getLineNumber(LocInfo.first, LocInfo.second);1401}1402unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,1403bool *Invalid) const {1404if (isInvalid(Loc, Invalid)) return 0;1405std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);1406return getLineNumber(LocInfo.first, LocInfo.second);1407}1408unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,1409bool *Invalid) const {1410PresumedLoc PLoc = getPresumedLoc(Loc);1411if (isInvalid(PLoc, Invalid)) return 0;1412return PLoc.getLine();1413}14141415/// getFileCharacteristic - return the file characteristic of the specified1416/// source location, indicating whether this is a normal file, a system1417/// header, or an "implicit extern C" system header.1418///1419/// This state can be modified with flags on GNU linemarker directives like:1420/// # 4 "foo.h" 31421/// which changes all source locations in the current file after that to be1422/// considered to be from a system header.1423SrcMgr::CharacteristicKind1424SourceManager::getFileCharacteristic(SourceLocation Loc) const {1425assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");1426std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);1427const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first);1428if (!SEntry)1429return C_User;14301431const SrcMgr::FileInfo &FI = SEntry->getFile();14321433// If there are no #line directives in this file, just return the whole-file1434// state.1435if (!FI.hasLineDirectives())1436return FI.getFileCharacteristic();14371438assert(LineTable && "Can't have linetable entries without a LineTable!");1439// See if there is a #line directive before the location.1440const LineEntry *Entry =1441LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);14421443// If this is before the first line marker, use the file characteristic.1444if (!Entry)1445return FI.getFileCharacteristic();14461447return Entry->FileKind;1448}14491450/// Return the filename or buffer identifier of the buffer the location is in.1451/// Note that this name does not respect \#line directives. Use getPresumedLoc1452/// for normal clients.1453StringRef SourceManager::getBufferName(SourceLocation Loc,1454bool *Invalid) const {1455if (isInvalid(Loc, Invalid)) return "<invalid loc>";14561457auto B = getBufferOrNone(getFileID(Loc));1458if (Invalid)1459*Invalid = !B;1460return B ? B->getBufferIdentifier() : "<invalid buffer>";1461}14621463/// getPresumedLoc - This method returns the "presumed" location of a1464/// SourceLocation specifies. A "presumed location" can be modified by \#line1465/// or GNU line marker directives. This provides a view on the data that a1466/// user should see in diagnostics, for example.1467///1468/// Note that a presumed location is always given as the expansion point of an1469/// expansion location, not at the spelling location.1470PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,1471bool UseLineDirectives) const {1472if (Loc.isInvalid()) return PresumedLoc();14731474// Presumed locations are always for expansion points.1475std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);14761477bool Invalid = false;1478const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);1479if (Invalid || !Entry.isFile())1480return PresumedLoc();14811482const SrcMgr::FileInfo &FI = Entry.getFile();1483const SrcMgr::ContentCache *C = &FI.getContentCache();14841485// To get the source name, first consult the FileEntry (if one exists)1486// before the MemBuffer as this will avoid unnecessarily paging in the1487// MemBuffer.1488FileID FID = LocInfo.first;1489StringRef Filename;1490if (C->OrigEntry)1491Filename = C->OrigEntry->getName();1492else if (auto Buffer = C->getBufferOrNone(Diag, getFileManager()))1493Filename = Buffer->getBufferIdentifier();14941495unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);1496if (Invalid)1497return PresumedLoc();1498unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);1499if (Invalid)1500return PresumedLoc();15011502SourceLocation IncludeLoc = FI.getIncludeLoc();15031504// If we have #line directives in this file, update and overwrite the physical1505// location info if appropriate.1506if (UseLineDirectives && FI.hasLineDirectives()) {1507assert(LineTable && "Can't have linetable entries without a LineTable!");1508// See if there is a #line directive before this. If so, get it.1509if (const LineEntry *Entry =1510LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {1511// If the LineEntry indicates a filename, use it.1512if (Entry->FilenameID != -1) {1513Filename = LineTable->getFilename(Entry->FilenameID);1514// The contents of files referenced by #line are not in the1515// SourceManager1516FID = FileID::get(0);1517}15181519// Use the line number specified by the LineEntry. This line number may1520// be multiple lines down from the line entry. Add the difference in1521// physical line numbers from the query point and the line marker to the1522// total.1523unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);1524LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);15251526// Note that column numbers are not molested by line markers.15271528// Handle virtual #include manipulation.1529if (Entry->IncludeOffset) {1530IncludeLoc = getLocForStartOfFile(LocInfo.first);1531IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);1532}1533}1534}15351536return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);1537}15381539/// Returns whether the PresumedLoc for a given SourceLocation is1540/// in the main file.1541///1542/// This computes the "presumed" location for a SourceLocation, then checks1543/// whether it came from a file other than the main file. This is different1544/// from isWrittenInMainFile() because it takes line marker directives into1545/// account.1546bool SourceManager::isInMainFile(SourceLocation Loc) const {1547if (Loc.isInvalid()) return false;15481549// Presumed locations are always for expansion points.1550std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);15511552const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first);1553if (!Entry)1554return false;15551556const SrcMgr::FileInfo &FI = Entry->getFile();15571558// Check if there is a line directive for this location.1559if (FI.hasLineDirectives())1560if (const LineEntry *Entry =1561LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))1562if (Entry->IncludeOffset)1563return false;15641565return FI.getIncludeLoc().isInvalid();1566}15671568/// The size of the SLocEntry that \p FID represents.1569unsigned SourceManager::getFileIDSize(FileID FID) const {1570bool Invalid = false;1571const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);1572if (Invalid)1573return 0;15741575int ID = FID.ID;1576SourceLocation::UIntTy NextOffset;1577if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))1578NextOffset = getNextLocalOffset();1579else if (ID+1 == -1)1580NextOffset = MaxLoadedOffset;1581else1582NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();15831584return NextOffset - Entry.getOffset() - 1;1585}15861587//===----------------------------------------------------------------------===//1588// Other miscellaneous methods.1589//===----------------------------------------------------------------------===//15901591/// Get the source location for the given file:line:col triplet.1592///1593/// If the source file is included multiple times, the source location will1594/// be based upon an arbitrary inclusion.1595SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,1596unsigned Line,1597unsigned Col) const {1598assert(SourceFile && "Null source file!");1599assert(Line && Col && "Line and column should start from 1!");16001601FileID FirstFID = translateFile(SourceFile);1602return translateLineCol(FirstFID, Line, Col);1603}16041605/// Get the FileID for the given file.1606///1607/// If the source file is included multiple times, the FileID will be the1608/// first inclusion.1609FileID SourceManager::translateFile(const FileEntry *SourceFile) const {1610assert(SourceFile && "Null source file!");16111612// First, check the main file ID, since it is common to look for a1613// location in the main file.1614if (MainFileID.isValid()) {1615bool Invalid = false;1616const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);1617if (Invalid)1618return FileID();16191620if (MainSLoc.isFile()) {1621if (MainSLoc.getFile().getContentCache().OrigEntry == SourceFile)1622return MainFileID;1623}1624}16251626// The location we're looking for isn't in the main file; look1627// through all of the local source locations.1628for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {1629const SLocEntry &SLoc = getLocalSLocEntry(I);1630if (SLoc.isFile() &&1631SLoc.getFile().getContentCache().OrigEntry == SourceFile)1632return FileID::get(I);1633}16341635// If that still didn't help, try the modules.1636for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {1637const SLocEntry &SLoc = getLoadedSLocEntry(I);1638if (SLoc.isFile() &&1639SLoc.getFile().getContentCache().OrigEntry == SourceFile)1640return FileID::get(-int(I) - 2);1641}16421643return FileID();1644}16451646/// Get the source location in \arg FID for the given line:col.1647/// Returns null location if \arg FID is not a file SLocEntry.1648SourceLocation SourceManager::translateLineCol(FileID FID,1649unsigned Line,1650unsigned Col) const {1651// Lines are used as a one-based index into a zero-based array. This assert1652// checks for possible buffer underruns.1653assert(Line && Col && "Line and column should start from 1!");16541655if (FID.isInvalid())1656return SourceLocation();16571658bool Invalid = false;1659const SLocEntry &Entry = getSLocEntry(FID, &Invalid);1660if (Invalid)1661return SourceLocation();16621663if (!Entry.isFile())1664return SourceLocation();16651666SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());16671668if (Line == 1 && Col == 1)1669return FileLoc;16701671const ContentCache *Content = &Entry.getFile().getContentCache();16721673// If this is the first use of line information for this buffer, compute the1674// SourceLineCache for it on demand.1675std::optional<llvm::MemoryBufferRef> Buffer =1676Content->getBufferOrNone(Diag, getFileManager());1677if (!Buffer)1678return SourceLocation();1679if (!Content->SourceLineCache)1680Content->SourceLineCache =1681LineOffsetMapping::get(*Buffer, ContentCacheAlloc);16821683if (Line > Content->SourceLineCache.size()) {1684unsigned Size = Buffer->getBufferSize();1685if (Size > 0)1686--Size;1687return FileLoc.getLocWithOffset(Size);1688}16891690unsigned FilePos = Content->SourceLineCache[Line - 1];1691const char *Buf = Buffer->getBufferStart() + FilePos;1692unsigned BufLength = Buffer->getBufferSize() - FilePos;1693if (BufLength == 0)1694return FileLoc.getLocWithOffset(FilePos);16951696unsigned i = 0;16971698// Check that the given column is valid.1699while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')1700++i;1701return FileLoc.getLocWithOffset(FilePos + i);1702}17031704/// Compute a map of macro argument chunks to their expanded source1705/// location. Chunks that are not part of a macro argument will map to an1706/// invalid source location. e.g. if a file contains one macro argument at1707/// offset 100 with length 10, this is how the map will be formed:1708/// 0 -> SourceLocation()1709/// 100 -> Expanded macro arg location1710/// 110 -> SourceLocation()1711void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,1712FileID FID) const {1713assert(FID.isValid());17141715// Initially no macro argument chunk is present.1716MacroArgsCache.insert(std::make_pair(0, SourceLocation()));17171718int ID = FID.ID;1719while (true) {1720++ID;1721// Stop if there are no more FileIDs to check.1722if (ID > 0) {1723if (unsigned(ID) >= local_sloc_entry_size())1724return;1725} else if (ID == -1) {1726return;1727}17281729bool Invalid = false;1730const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);1731if (Invalid)1732return;1733if (Entry.isFile()) {1734auto& File = Entry.getFile();1735if (File.getFileCharacteristic() == C_User_ModuleMap ||1736File.getFileCharacteristic() == C_System_ModuleMap)1737continue;17381739SourceLocation IncludeLoc = File.getIncludeLoc();1740bool IncludedInFID =1741(IncludeLoc.isValid() && isInFileID(IncludeLoc, FID)) ||1742// Predefined header doesn't have a valid include location in main1743// file, but any files created by it should still be skipped when1744// computing macro args expanded in the main file.1745(FID == MainFileID && Entry.getFile().getName() == "<built-in>");1746if (IncludedInFID) {1747// Skip the files/macros of the #include'd file, we only care about1748// macros that lexed macro arguments from our file.1749if (Entry.getFile().NumCreatedFIDs)1750ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;1751continue;1752}1753// If file was included but not from FID, there is no more files/macros1754// that may be "contained" in this file.1755if (IncludeLoc.isValid())1756return;1757continue;1758}17591760const ExpansionInfo &ExpInfo = Entry.getExpansion();17611762if (ExpInfo.getExpansionLocStart().isFileID()) {1763if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))1764return; // No more files/macros that may be "contained" in this file.1765}17661767if (!ExpInfo.isMacroArgExpansion())1768continue;17691770associateFileChunkWithMacroArgExp(MacroArgsCache, FID,1771ExpInfo.getSpellingLoc(),1772SourceLocation::getMacroLoc(Entry.getOffset()),1773getFileIDSize(FileID::get(ID)));1774}1775}17761777void SourceManager::associateFileChunkWithMacroArgExp(1778MacroArgsMap &MacroArgsCache,1779FileID FID,1780SourceLocation SpellLoc,1781SourceLocation ExpansionLoc,1782unsigned ExpansionLength) const {1783if (!SpellLoc.isFileID()) {1784SourceLocation::UIntTy SpellBeginOffs = SpellLoc.getOffset();1785SourceLocation::UIntTy SpellEndOffs = SpellBeginOffs + ExpansionLength;17861787// The spelling range for this macro argument expansion can span multiple1788// consecutive FileID entries. Go through each entry contained in the1789// spelling range and if one is itself a macro argument expansion, recurse1790// and associate the file chunk that it represents.17911792FileID SpellFID; // Current FileID in the spelling range.1793unsigned SpellRelativeOffs;1794std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);1795while (true) {1796const SLocEntry &Entry = getSLocEntry(SpellFID);1797SourceLocation::UIntTy SpellFIDBeginOffs = Entry.getOffset();1798unsigned SpellFIDSize = getFileIDSize(SpellFID);1799SourceLocation::UIntTy SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;1800const ExpansionInfo &Info = Entry.getExpansion();1801if (Info.isMacroArgExpansion()) {1802unsigned CurrSpellLength;1803if (SpellFIDEndOffs < SpellEndOffs)1804CurrSpellLength = SpellFIDSize - SpellRelativeOffs;1805else1806CurrSpellLength = ExpansionLength;1807associateFileChunkWithMacroArgExp(MacroArgsCache, FID,1808Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),1809ExpansionLoc, CurrSpellLength);1810}18111812if (SpellFIDEndOffs >= SpellEndOffs)1813return; // we covered all FileID entries in the spelling range.18141815// Move to the next FileID entry in the spelling range.1816unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;1817ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);1818ExpansionLength -= advance;1819++SpellFID.ID;1820SpellRelativeOffs = 0;1821}1822}18231824assert(SpellLoc.isFileID());18251826unsigned BeginOffs;1827if (!isInFileID(SpellLoc, FID, &BeginOffs))1828return;18291830unsigned EndOffs = BeginOffs + ExpansionLength;18311832// Add a new chunk for this macro argument. A previous macro argument chunk1833// may have been lexed again, so e.g. if the map is1834// 0 -> SourceLocation()1835// 100 -> Expanded loc #11836// 110 -> SourceLocation()1837// and we found a new macro FileID that lexed from offset 105 with length 3,1838// the new map will be:1839// 0 -> SourceLocation()1840// 100 -> Expanded loc #11841// 105 -> Expanded loc #21842// 108 -> Expanded loc #11843// 110 -> SourceLocation()1844//1845// Since re-lexed macro chunks will always be the same size or less of1846// previous chunks, we only need to find where the ending of the new macro1847// chunk is mapped to and update the map with new begin/end mappings.18481849MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);1850--I;1851SourceLocation EndOffsMappedLoc = I->second;1852MacroArgsCache[BeginOffs] = ExpansionLoc;1853MacroArgsCache[EndOffs] = EndOffsMappedLoc;1854}18551856void SourceManager::updateSlocUsageStats() const {1857SourceLocation::UIntTy UsedBytes =1858NextLocalOffset + (MaxLoadedOffset - CurrentLoadedOffset);1859MaxUsedSLocBytes.updateMax(UsedBytes);1860}18611862/// If \arg Loc points inside a function macro argument, the returned1863/// location will be the macro location in which the argument was expanded.1864/// If a macro argument is used multiple times, the expanded location will1865/// be at the first expansion of the argument.1866/// e.g.1867/// MY_MACRO(foo);1868/// ^1869/// Passing a file location pointing at 'foo', will yield a macro location1870/// where 'foo' was expanded into.1871SourceLocation1872SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {1873if (Loc.isInvalid() || !Loc.isFileID())1874return Loc;18751876FileID FID;1877unsigned Offset;1878std::tie(FID, Offset) = getDecomposedLoc(Loc);1879if (FID.isInvalid())1880return Loc;18811882std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];1883if (!MacroArgsCache) {1884MacroArgsCache = std::make_unique<MacroArgsMap>();1885computeMacroArgsCache(*MacroArgsCache, FID);1886}18871888assert(!MacroArgsCache->empty());1889MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);1890// In case every element in MacroArgsCache is greater than Offset we can't1891// decrement the iterator.1892if (I == MacroArgsCache->begin())1893return Loc;18941895--I;18961897SourceLocation::UIntTy MacroArgBeginOffs = I->first;1898SourceLocation MacroArgExpandedLoc = I->second;1899if (MacroArgExpandedLoc.isValid())1900return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);19011902return Loc;1903}19041905std::pair<FileID, unsigned>1906SourceManager::getDecomposedIncludedLoc(FileID FID) const {1907if (FID.isInvalid())1908return std::make_pair(FileID(), 0);19091910// Uses IncludedLocMap to retrieve/cache the decomposed loc.19111912using DecompTy = std::pair<FileID, unsigned>;1913auto InsertOp = IncludedLocMap.try_emplace(FID);1914DecompTy &DecompLoc = InsertOp.first->second;1915if (!InsertOp.second)1916return DecompLoc; // already in map.19171918SourceLocation UpperLoc;1919bool Invalid = false;1920const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);1921if (!Invalid) {1922if (Entry.isExpansion())1923UpperLoc = Entry.getExpansion().getExpansionLocStart();1924else1925UpperLoc = Entry.getFile().getIncludeLoc();1926}19271928if (UpperLoc.isValid())1929DecompLoc = getDecomposedLoc(UpperLoc);19301931return DecompLoc;1932}19331934FileID SourceManager::getUniqueLoadedASTFileID(SourceLocation Loc) const {1935assert(isLoadedSourceLocation(Loc) &&1936"Must be a source location in a loaded PCH/Module file");19371938auto [FID, Ignore] = getDecomposedLoc(Loc);1939// `LoadedSLocEntryAllocBegin` stores the sorted lowest FID of each loaded1940// allocation. Later allocations have lower FileIDs. The call below is to find1941// the lowest FID of a loaded allocation from any FID in the same allocation.1942// The lowest FID is used to identify a loaded allocation.1943const FileID *FirstFID =1944llvm::lower_bound(LoadedSLocEntryAllocBegin, FID, std::greater<FileID>{});19451946assert(FirstFID &&1947"The failure to find the first FileID of a "1948"loaded AST from a loaded source location was unexpected.");1949return *FirstFID;1950}19511952bool SourceManager::isInTheSameTranslationUnitImpl(1953const std::pair<FileID, unsigned> &LOffs,1954const std::pair<FileID, unsigned> &ROffs) const {1955// If one is local while the other is loaded.1956if (isLoadedFileID(LOffs.first) != isLoadedFileID(ROffs.first))1957return false;19581959if (isLoadedFileID(LOffs.first) && isLoadedFileID(ROffs.first)) {1960auto FindSLocEntryAlloc = [this](FileID FID) {1961// Loaded FileIDs are negative, we store the lowest FileID from each1962// allocation, later allocations have lower FileIDs.1963return llvm::lower_bound(LoadedSLocEntryAllocBegin, FID,1964std::greater<FileID>{});1965};19661967// If both are loaded from different AST files.1968if (FindSLocEntryAlloc(LOffs.first) != FindSLocEntryAlloc(ROffs.first))1969return false;1970}19711972return true;1973}19741975/// Given a decomposed source location, move it up the include/expansion stack1976/// to the parent source location within the same translation unit. If this is1977/// possible, return the decomposed version of the parent in Loc and return1978/// false. If Loc is a top-level entry, return true and don't modify it.1979static bool1980MoveUpTranslationUnitIncludeHierarchy(std::pair<FileID, unsigned> &Loc,1981const SourceManager &SM) {1982std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);1983if (UpperLoc.first.isInvalid() ||1984!SM.isInTheSameTranslationUnitImpl(UpperLoc, Loc))1985return true; // We reached the top.19861987Loc = UpperLoc;1988return false;1989}19901991/// Return the cache entry for comparing the given file IDs1992/// for isBeforeInTranslationUnit.1993InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,1994FileID RFID) const {1995// This is a magic number for limiting the cache size. It was experimentally1996// derived from a small Objective-C project (where the cache filled1997// out to ~250 items). We can make it larger if necessary.1998// FIXME: this is almost certainly full these days. Use an LRU cache?1999enum { MagicCacheSize = 300 };2000IsBeforeInTUCacheKey Key(LFID, RFID);20012002// If the cache size isn't too large, do a lookup and if necessary default2003// construct an entry. We can then return it to the caller for direct2004// use. When they update the value, the cache will get automatically2005// updated as well.2006if (IBTUCache.size() < MagicCacheSize)2007return IBTUCache.try_emplace(Key, LFID, RFID).first->second;20082009// Otherwise, do a lookup that will not construct a new value.2010InBeforeInTUCache::iterator I = IBTUCache.find(Key);2011if (I != IBTUCache.end())2012return I->second;20132014// Fall back to the overflow value.2015IBTUCacheOverflow.setQueryFIDs(LFID, RFID);2016return IBTUCacheOverflow;2017}20182019/// Determines the order of 2 source locations in the translation unit.2020///2021/// \returns true if LHS source location comes before RHS, false otherwise.2022bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,2023SourceLocation RHS) const {2024assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");2025if (LHS == RHS)2026return false;20272028std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);2029std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);20302031// getDecomposedLoc may have failed to return a valid FileID because, e.g. it2032// is a serialized one referring to a file that was removed after we loaded2033// the PCH.2034if (LOffs.first.isInvalid() || ROffs.first.isInvalid())2035return LOffs.first.isInvalid() && !ROffs.first.isInvalid();20362037std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);2038if (InSameTU.first)2039return InSameTU.second;2040// TODO: This should be unreachable, but some clients are calling this2041// function before making sure LHS and RHS are in the same TU.2042return LOffs.first < ROffs.first;2043}20442045std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(2046std::pair<FileID, unsigned> &LOffs,2047std::pair<FileID, unsigned> &ROffs) const {2048// If the source locations are not in the same TU, return early.2049if (!isInTheSameTranslationUnitImpl(LOffs, ROffs))2050return std::make_pair(false, false);20512052// If the source locations are in the same file, just compare offsets.2053if (LOffs.first == ROffs.first)2054return std::make_pair(true, LOffs.second < ROffs.second);20552056// If we are comparing a source location with multiple locations in the same2057// file, we get a big win by caching the result.2058InBeforeInTUCacheEntry &IsBeforeInTUCache =2059getInBeforeInTUCache(LOffs.first, ROffs.first);20602061// If we are comparing a source location with multiple locations in the same2062// file, we get a big win by caching the result.2063if (IsBeforeInTUCache.isCacheValid())2064return std::make_pair(2065true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));20662067// Okay, we missed in the cache, we'll compute the answer and populate it.2068// We need to find the common ancestor. The only way of doing this is to2069// build the complete include chain for one and then walking up the chain2070// of the other looking for a match.20712072// A location within a FileID on the path up from LOffs to the main file.2073struct Entry {2074std::pair<FileID, unsigned> DecomposedLoc; // FileID redundant, but clearer.2075FileID ChildFID; // Used for breaking ties. Invalid for the initial loc.2076};2077llvm::SmallDenseMap<FileID, Entry, 16> LChain;20782079FileID LChild;2080do {2081LChain.try_emplace(LOffs.first, Entry{LOffs, LChild});2082// We catch the case where LOffs is in a file included by ROffs and2083// quit early. The other way round unfortunately remains suboptimal.2084if (LOffs.first == ROffs.first)2085break;2086LChild = LOffs.first;2087} while (!MoveUpTranslationUnitIncludeHierarchy(LOffs, *this));20882089FileID RChild;2090do {2091auto LIt = LChain.find(ROffs.first);2092if (LIt != LChain.end()) {2093// Compare the locations within the common file and cache them.2094LOffs = LIt->second.DecomposedLoc;2095LChild = LIt->second.ChildFID;2096// The relative order of LChild and RChild is a tiebreaker when2097// - locs expand to the same location (occurs in macro arg expansion)2098// - one loc is a parent of the other (we consider the parent as "first")2099// For the parent entry to be first, its invalid child file ID must2100// compare smaller to the valid child file ID of the other entry.2101// However loaded FileIDs are <0, so we perform *unsigned* comparison!2102// This changes the relative order of local vs loaded FileIDs, but it2103// doesn't matter as these are never mixed in macro expansion.2104unsigned LChildID = LChild.ID;2105unsigned RChildID = RChild.ID;2106assert(((LOffs.second != ROffs.second) ||2107(LChildID == 0 || RChildID == 0) ||2108isInSameSLocAddrSpace(getComposedLoc(LChild, 0),2109getComposedLoc(RChild, 0), nullptr)) &&2110"Mixed local/loaded FileIDs with same include location?");2111IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second,2112LChildID < RChildID);2113return std::make_pair(2114true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));2115}2116RChild = ROffs.first;2117} while (!MoveUpTranslationUnitIncludeHierarchy(ROffs, *this));21182119// If we found no match, the location is either in a built-ins buffer or2120// associated with global inline asm. PR5662 and PR22576 are examples.21212122StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier();2123StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier();21242125bool LIsBuiltins = LB == "<built-in>";2126bool RIsBuiltins = RB == "<built-in>";2127// Sort built-in before non-built-in.2128if (LIsBuiltins || RIsBuiltins) {2129if (LIsBuiltins != RIsBuiltins)2130return std::make_pair(true, LIsBuiltins);2131// Both are in built-in buffers, but from different files. We just claim2132// that lower IDs come first.2133return std::make_pair(true, LOffs.first < ROffs.first);2134}21352136bool LIsAsm = LB == "<inline asm>";2137bool RIsAsm = RB == "<inline asm>";2138// Sort assembler after built-ins, but before the rest.2139if (LIsAsm || RIsAsm) {2140if (LIsAsm != RIsAsm)2141return std::make_pair(true, RIsAsm);2142assert(LOffs.first == ROffs.first);2143return std::make_pair(true, false);2144}21452146bool LIsScratch = LB == "<scratch space>";2147bool RIsScratch = RB == "<scratch space>";2148// Sort scratch after inline asm, but before the rest.2149if (LIsScratch || RIsScratch) {2150if (LIsScratch != RIsScratch)2151return std::make_pair(true, LIsScratch);2152return std::make_pair(true, LOffs.second < ROffs.second);2153}21542155llvm_unreachable("Unsortable locations found");2156}21572158void SourceManager::PrintStats() const {2159llvm::errs() << "\n*** Source Manager Stats:\n";2160llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()2161<< " mem buffers mapped.\n";2162llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntries allocated ("2163<< llvm::capacity_in_bytes(LocalSLocEntryTable)2164<< " bytes of capacity), " << NextLocalOffset2165<< "B of SLoc address space used.\n";2166llvm::errs() << LoadedSLocEntryTable.size()2167<< " loaded SLocEntries allocated ("2168<< llvm::capacity_in_bytes(LoadedSLocEntryTable)2169<< " bytes of capacity), "2170<< MaxLoadedOffset - CurrentLoadedOffset2171<< "B of SLoc address space used.\n";21722173unsigned NumLineNumsComputed = 0;2174unsigned NumFileBytesMapped = 0;2175for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){2176NumLineNumsComputed += bool(I->second->SourceLineCache);2177NumFileBytesMapped += I->second->getSizeBytesMapped();2178}2179unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();21802181llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "2182<< NumLineNumsComputed << " files with line #'s computed, "2183<< NumMacroArgsComputed << " files with macro args computed.\n";2184llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "2185<< NumBinaryProbes << " binary.\n";2186}21872188LLVM_DUMP_METHOD void SourceManager::dump() const {2189llvm::raw_ostream &out = llvm::errs();21902191auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,2192std::optional<SourceLocation::UIntTy> NextStart) {2193out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")2194<< " <SourceLocation " << Entry.getOffset() << ":";2195if (NextStart)2196out << *NextStart << ">\n";2197else2198out << "???\?>\n";2199if (Entry.isFile()) {2200auto &FI = Entry.getFile();2201if (FI.NumCreatedFIDs)2202out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)2203<< ">\n";2204if (FI.getIncludeLoc().isValid())2205out << " included from " << FI.getIncludeLoc().getOffset() << "\n";2206auto &CC = FI.getContentCache();2207out << " for " << (CC.OrigEntry ? CC.OrigEntry->getName() : "<none>")2208<< "\n";2209if (CC.BufferOverridden)2210out << " contents overridden\n";2211if (CC.ContentsEntry != CC.OrigEntry) {2212out << " contents from "2213<< (CC.ContentsEntry ? CC.ContentsEntry->getName() : "<none>")2214<< "\n";2215}2216} else {2217auto &EI = Entry.getExpansion();2218out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";2219out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")2220<< " range <" << EI.getExpansionLocStart().getOffset() << ":"2221<< EI.getExpansionLocEnd().getOffset() << ">\n";2222}2223};22242225// Dump local SLocEntries.2226for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {2227DumpSLocEntry(ID, LocalSLocEntryTable[ID],2228ID == NumIDs - 1 ? NextLocalOffset2229: LocalSLocEntryTable[ID + 1].getOffset());2230}2231// Dump loaded SLocEntries.2232std::optional<SourceLocation::UIntTy> NextStart;2233for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {2234int ID = -(int)Index - 2;2235if (SLocEntryLoaded[Index]) {2236DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);2237NextStart = LoadedSLocEntryTable[Index].getOffset();2238} else {2239NextStart = std::nullopt;2240}2241}2242}22432244void SourceManager::noteSLocAddressSpaceUsage(2245DiagnosticsEngine &Diag, std::optional<unsigned> MaxNotes) const {2246struct Info {2247// A location where this file was entered.2248SourceLocation Loc;2249// Number of times this FileEntry was entered.2250unsigned Inclusions = 0;2251// Size usage from the file itself.2252uint64_t DirectSize = 0;2253// Total size usage from the file and its macro expansions.2254uint64_t TotalSize = 0;2255};2256using UsageMap = llvm::MapVector<const FileEntry*, Info>;22572258UsageMap Usage;2259uint64_t CountedSize = 0;22602261auto AddUsageForFileID = [&](FileID ID) {2262// The +1 here is because getFileIDSize doesn't include the extra byte for2263// the one-past-the-end location.2264unsigned Size = getFileIDSize(ID) + 1;22652266// Find the file that used this address space, either directly or by2267// macro expansion.2268SourceLocation FileStart = getFileLoc(getComposedLoc(ID, 0));2269FileID FileLocID = getFileID(FileStart);2270const FileEntry *Entry = getFileEntryForID(FileLocID);22712272Info &EntryInfo = Usage[Entry];2273if (EntryInfo.Loc.isInvalid())2274EntryInfo.Loc = FileStart;2275if (ID == FileLocID) {2276++EntryInfo.Inclusions;2277EntryInfo.DirectSize += Size;2278}2279EntryInfo.TotalSize += Size;2280CountedSize += Size;2281};22822283// Loaded SLocEntries have indexes counting downwards from -2.2284for (size_t Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {2285AddUsageForFileID(FileID::get(-2 - Index));2286}2287// Local SLocEntries have indexes counting upwards from 0.2288for (size_t Index = 0; Index != LocalSLocEntryTable.size(); ++Index) {2289AddUsageForFileID(FileID::get(Index));2290}22912292// Sort the usage by size from largest to smallest. Break ties by raw source2293// location.2294auto SortedUsage = Usage.takeVector();2295auto Cmp = [](const UsageMap::value_type &A, const UsageMap::value_type &B) {2296return A.second.TotalSize > B.second.TotalSize ||2297(A.second.TotalSize == B.second.TotalSize &&2298A.second.Loc < B.second.Loc);2299};2300auto SortedEnd = SortedUsage.end();2301if (MaxNotes && SortedUsage.size() > *MaxNotes) {2302SortedEnd = SortedUsage.begin() + *MaxNotes;2303std::nth_element(SortedUsage.begin(), SortedEnd, SortedUsage.end(), Cmp);2304}2305std::sort(SortedUsage.begin(), SortedEnd, Cmp);23062307// Produce note on sloc address space usage total.2308uint64_t LocalUsage = NextLocalOffset;2309uint64_t LoadedUsage = MaxLoadedOffset - CurrentLoadedOffset;2310int UsagePercent = static_cast<int>(100.0 * double(LocalUsage + LoadedUsage) /2311MaxLoadedOffset);2312Diag.Report(SourceLocation(), diag::note_total_sloc_usage)2313<< LocalUsage << LoadedUsage << (LocalUsage + LoadedUsage) << UsagePercent;23142315// Produce notes on sloc address space usage for each file with a high usage.2316uint64_t ReportedSize = 0;2317for (auto &[Entry, FileInfo] :2318llvm::make_range(SortedUsage.begin(), SortedEnd)) {2319Diag.Report(FileInfo.Loc, diag::note_file_sloc_usage)2320<< FileInfo.Inclusions << FileInfo.DirectSize2321<< (FileInfo.TotalSize - FileInfo.DirectSize);2322ReportedSize += FileInfo.TotalSize;2323}23242325// Describe any remaining usage not reported in the per-file usage.2326if (ReportedSize != CountedSize) {2327Diag.Report(SourceLocation(), diag::note_file_misc_sloc_usage)2328<< (SortedUsage.end() - SortedEnd) << CountedSize - ReportedSize;2329}2330}23312332ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;23332334/// Return the amount of memory used by memory buffers, breaking down2335/// by heap-backed versus mmap'ed memory.2336SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {2337size_t malloc_bytes = 0;2338size_t mmap_bytes = 0;23392340for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)2341if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())2342switch (MemBufferInfos[i]->getMemoryBufferKind()) {2343case llvm::MemoryBuffer::MemoryBuffer_MMap:2344mmap_bytes += sized_mapped;2345break;2346case llvm::MemoryBuffer::MemoryBuffer_Malloc:2347malloc_bytes += sized_mapped;2348break;2349}23502351return MemoryBufferSizes(malloc_bytes, mmap_bytes);2352}23532354size_t SourceManager::getDataStructureSizes() const {2355size_t size = llvm::capacity_in_bytes(MemBufferInfos) +2356llvm::capacity_in_bytes(LocalSLocEntryTable) +2357llvm::capacity_in_bytes(LoadedSLocEntryTable) +2358llvm::capacity_in_bytes(SLocEntryLoaded) +2359llvm::capacity_in_bytes(FileInfos);23602361if (OverriddenFilesInfo)2362size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);23632364return size;2365}23662367SourceManagerForFile::SourceManagerForFile(StringRef FileName,2368StringRef Content) {2369// This is referenced by `FileMgr` and will be released by `FileMgr` when it2370// is deleted.2371IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(2372new llvm::vfs::InMemoryFileSystem);2373InMemoryFileSystem->addFile(2374FileName, 0,2375llvm::MemoryBuffer::getMemBuffer(Content, FileName,2376/*RequiresNullTerminator=*/false));2377// This is passed to `SM` as reference, so the pointer has to be referenced2378// in `Environment` so that `FileMgr` can out-live this function scope.2379FileMgr =2380std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);2381// This is passed to `SM` as reference, so the pointer has to be referenced2382// by `Environment` due to the same reason above.2383Diagnostics = std::make_unique<DiagnosticsEngine>(2384IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),2385new DiagnosticOptions);2386SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);2387FileEntryRef FE = llvm::cantFail(FileMgr->getFileRef(FileName));2388FileID ID =2389SourceMgr->createFileID(FE, SourceLocation(), clang::SrcMgr::C_User);2390assert(ID.isValid());2391SourceMgr->setMainFileID(ID);2392}239323942395