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