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