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