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