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