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