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