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