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/SourceManagerInternals.h" 16 #include "clang/Basic/Diagnostic.h" 17 #include "clang/Basic/FileManager.h" 18 #include "llvm/ADT/StringSwitch.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/Support/Compiler.h" 22 #include "llvm/Support/MemoryBuffer.h" 23 #include "llvm/Support/raw_ostream.h" 24 #include "llvm/Support/Path.h" 25 #include "llvm/Support/Capacity.h" 26 #include <algorithm> 27 #include <string> 28 #include <cstring> 29 #include <sys/stat.h> 30 31 using namespace clang; 32 using namespace SrcMgr; 33 using llvm::MemoryBuffer; 34 35 //===----------------------------------------------------------------------===// 36 // SourceManager Helper Classes 37 //===----------------------------------------------------------------------===// 38 39 ContentCache::~ContentCache() { 40 if (shouldFreeBuffer()) 41 delete Buffer.getPointer(); 42 } 43 44 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this 45 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded. 46 unsigned ContentCache::getSizeBytesMapped() const { 47 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0; 48 } 49 50 /// Returns the kind of memory used to back the memory buffer for 51 /// this content cache. This is used for performance analysis. 52 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const { 53 assert(Buffer.getPointer()); 54 55 // Should be unreachable, but keep for sanity. 56 if (!Buffer.getPointer()) 57 return llvm::MemoryBuffer::MemoryBuffer_Malloc; 58 59 const llvm::MemoryBuffer *buf = Buffer.getPointer(); 60 return buf->getBufferKind(); 61 } 62 63 /// getSize - Returns the size of the content encapsulated by this ContentCache. 64 /// This can be the size of the source file or the size of an arbitrary 65 /// scratch buffer. If the ContentCache encapsulates a source file, that 66 /// file is not lazily brought in from disk to satisfy this query. 67 unsigned ContentCache::getSize() const { 68 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize() 69 : (unsigned) ContentsEntry->getSize(); 70 } 71 72 void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B, 73 bool DoNotFree) { 74 if (B == Buffer.getPointer()) { 75 assert(0 && "Replacing with the same buffer"); 76 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0); 77 return; 78 } 79 80 if (shouldFreeBuffer()) 81 delete Buffer.getPointer(); 82 Buffer.setPointer(B); 83 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0); 84 } 85 86 const llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag, 87 const SourceManager &SM, 88 SourceLocation Loc, 89 bool *Invalid) const { 90 // Lazily create the Buffer for ContentCaches that wrap files. If we already 91 // computed it, just return what we have. 92 if (Buffer.getPointer() || ContentsEntry == 0) { 93 if (Invalid) 94 *Invalid = isBufferInvalid(); 95 96 return Buffer.getPointer(); 97 } 98 99 std::string ErrorStr; 100 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr)); 101 102 // If we were unable to open the file, then we are in an inconsistent 103 // situation where the content cache referenced a file which no longer 104 // exists. Most likely, we were using a stat cache with an invalid entry but 105 // the file could also have been removed during processing. Since we can't 106 // really deal with this situation, just create an empty buffer. 107 // 108 // FIXME: This is definitely not ideal, but our immediate clients can't 109 // currently handle returning a null entry here. Ideally we should detect 110 // that we are in an inconsistent situation and error out as quickly as 111 // possible. 112 if (!Buffer.getPointer()) { 113 const StringRef FillStr("<<<MISSING SOURCE FILE>>>\n"); 114 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(), 115 "<invalid>")); 116 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart()); 117 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i) 118 Ptr[i] = FillStr[i % FillStr.size()]; 119 120 if (Diag.isDiagnosticInFlight()) 121 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file, 122 ContentsEntry->getName(), ErrorStr); 123 else 124 Diag.Report(Loc, diag::err_cannot_open_file) 125 << ContentsEntry->getName() << ErrorStr; 126 127 Buffer.setInt(Buffer.getInt() | InvalidFlag); 128 129 if (Invalid) *Invalid = true; 130 return Buffer.getPointer(); 131 } 132 133 // Check that the file's size is the same as in the file entry (which may 134 // have come from a stat cache). 135 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) { 136 if (Diag.isDiagnosticInFlight()) 137 Diag.SetDelayedDiagnostic(diag::err_file_modified, 138 ContentsEntry->getName()); 139 else 140 Diag.Report(Loc, diag::err_file_modified) 141 << ContentsEntry->getName(); 142 143 Buffer.setInt(Buffer.getInt() | InvalidFlag); 144 if (Invalid) *Invalid = true; 145 return Buffer.getPointer(); 146 } 147 148 // If the buffer is valid, check to see if it has a UTF Byte Order Mark 149 // (BOM). We only support UTF-8 with and without a BOM right now. See 150 // http://en.wikipedia.org/wiki/Byte_order_mark for more information. 151 StringRef BufStr = Buffer.getPointer()->getBuffer(); 152 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr) 153 .StartsWith("\xFE\xFF", "UTF-16 (BE)") 154 .StartsWith("\xFF\xFE", "UTF-16 (LE)") 155 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)") 156 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)") 157 .StartsWith("\x2B\x2F\x76", "UTF-7") 158 .StartsWith("\xF7\x64\x4C", "UTF-1") 159 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC") 160 .StartsWith("\x0E\xFE\xFF", "SDSU") 161 .StartsWith("\xFB\xEE\x28", "BOCU-1") 162 .StartsWith("\x84\x31\x95\x33", "GB-18030") 163 .Default(0); 164 165 if (InvalidBOM) { 166 Diag.Report(Loc, diag::err_unsupported_bom) 167 << InvalidBOM << ContentsEntry->getName(); 168 Buffer.setInt(Buffer.getInt() | InvalidFlag); 169 } 170 171 if (Invalid) 172 *Invalid = isBufferInvalid(); 173 174 return Buffer.getPointer(); 175 } 176 177 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) { 178 // Look up the filename in the string table, returning the pre-existing value 179 // if it exists. 180 llvm::StringMapEntry<unsigned> &Entry = 181 FilenameIDs.GetOrCreateValue(Name, ~0U); 182 if (Entry.getValue() != ~0U) 183 return Entry.getValue(); 184 185 // Otherwise, assign this the next available ID. 186 Entry.setValue(FilenamesByID.size()); 187 FilenamesByID.push_back(&Entry); 188 return FilenamesByID.size()-1; 189 } 190 191 /// AddLineNote - Add a line note to the line table that indicates that there 192 /// is a #line at the specified FID/Offset location which changes the presumed 193 /// location to LineNo/FilenameID. 194 void LineTableInfo::AddLineNote(int FID, unsigned Offset, 195 unsigned LineNo, int FilenameID) { 196 std::vector<LineEntry> &Entries = LineEntries[FID]; 197 198 assert((Entries.empty() || Entries.back().FileOffset < Offset) && 199 "Adding line entries out of order!"); 200 201 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User; 202 unsigned IncludeOffset = 0; 203 204 if (!Entries.empty()) { 205 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember 206 // that we are still in "foo.h". 207 if (FilenameID == -1) 208 FilenameID = Entries.back().FilenameID; 209 210 // If we are after a line marker that switched us to system header mode, or 211 // that set #include information, preserve it. 212 Kind = Entries.back().FileKind; 213 IncludeOffset = Entries.back().IncludeOffset; 214 } 215 216 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind, 217 IncludeOffset)); 218 } 219 220 /// AddLineNote This is the same as the previous version of AddLineNote, but is 221 /// used for GNU line markers. If EntryExit is 0, then this doesn't change the 222 /// presumed #include stack. If it is 1, this is a file entry, if it is 2 then 223 /// this is a file exit. FileKind specifies whether this is a system header or 224 /// extern C system header. 225 void LineTableInfo::AddLineNote(int FID, unsigned Offset, 226 unsigned LineNo, int FilenameID, 227 unsigned EntryExit, 228 SrcMgr::CharacteristicKind FileKind) { 229 assert(FilenameID != -1 && "Unspecified filename should use other accessor"); 230 231 std::vector<LineEntry> &Entries = LineEntries[FID]; 232 233 assert((Entries.empty() || Entries.back().FileOffset < Offset) && 234 "Adding line entries out of order!"); 235 236 unsigned IncludeOffset = 0; 237 if (EntryExit == 0) { // No #include stack change. 238 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset; 239 } else if (EntryExit == 1) { 240 IncludeOffset = Offset-1; 241 } else if (EntryExit == 2) { 242 assert(!Entries.empty() && Entries.back().IncludeOffset && 243 "PPDirectives should have caught case when popping empty include stack"); 244 245 // Get the include loc of the last entries' include loc as our include loc. 246 IncludeOffset = 0; 247 if (const LineEntry *PrevEntry = 248 FindNearestLineEntry(FID, Entries.back().IncludeOffset)) 249 IncludeOffset = PrevEntry->IncludeOffset; 250 } 251 252 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind, 253 IncludeOffset)); 254 } 255 256 257 /// FindNearestLineEntry - Find the line entry nearest to FID that is before 258 /// it. If there is no line entry before Offset in FID, return null. 259 const LineEntry *LineTableInfo::FindNearestLineEntry(int FID, 260 unsigned Offset) { 261 const std::vector<LineEntry> &Entries = LineEntries[FID]; 262 assert(!Entries.empty() && "No #line entries for this FID after all!"); 263 264 // It is very common for the query to be after the last #line, check this 265 // first. 266 if (Entries.back().FileOffset <= Offset) 267 return &Entries.back(); 268 269 // Do a binary search to find the maximal element that is still before Offset. 270 std::vector<LineEntry>::const_iterator I = 271 std::upper_bound(Entries.begin(), Entries.end(), Offset); 272 if (I == Entries.begin()) return 0; 273 return &*--I; 274 } 275 276 /// \brief Add a new line entry that has already been encoded into 277 /// the internal representation of the line table. 278 void LineTableInfo::AddEntry(int FID, 279 const std::vector<LineEntry> &Entries) { 280 LineEntries[FID] = Entries; 281 } 282 283 /// getLineTableFilenameID - Return the uniqued ID for the specified filename. 284 /// 285 unsigned SourceManager::getLineTableFilenameID(StringRef Name) { 286 if (LineTable == 0) 287 LineTable = new LineTableInfo(); 288 return LineTable->getLineTableFilenameID(Name); 289 } 290 291 292 /// AddLineNote - Add a line note to the line table for the FileID and offset 293 /// specified by Loc. If FilenameID is -1, it is considered to be 294 /// unspecified. 295 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, 296 int FilenameID) { 297 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); 298 299 bool Invalid = false; 300 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); 301 if (!Entry.isFile() || Invalid) 302 return; 303 304 const SrcMgr::FileInfo &FileInfo = Entry.getFile(); 305 306 // Remember that this file has #line directives now if it doesn't already. 307 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives(); 308 309 if (LineTable == 0) 310 LineTable = new LineTableInfo(); 311 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID); 312 } 313 314 /// AddLineNote - Add a GNU line marker to the line table. 315 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, 316 int FilenameID, bool IsFileEntry, 317 bool IsFileExit, bool IsSystemHeader, 318 bool IsExternCHeader) { 319 // If there is no filename and no flags, this is treated just like a #line, 320 // which does not change the flags of the previous line marker. 321 if (FilenameID == -1) { 322 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader && 323 "Can't set flags without setting the filename!"); 324 return AddLineNote(Loc, LineNo, FilenameID); 325 } 326 327 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); 328 329 bool Invalid = false; 330 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); 331 if (!Entry.isFile() || Invalid) 332 return; 333 334 const SrcMgr::FileInfo &FileInfo = Entry.getFile(); 335 336 // Remember that this file has #line directives now if it doesn't already. 337 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives(); 338 339 if (LineTable == 0) 340 LineTable = new LineTableInfo(); 341 342 SrcMgr::CharacteristicKind FileKind; 343 if (IsExternCHeader) 344 FileKind = SrcMgr::C_ExternCSystem; 345 else if (IsSystemHeader) 346 FileKind = SrcMgr::C_System; 347 else 348 FileKind = SrcMgr::C_User; 349 350 unsigned EntryExit = 0; 351 if (IsFileEntry) 352 EntryExit = 1; 353 else if (IsFileExit) 354 EntryExit = 2; 355 356 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID, 357 EntryExit, FileKind); 358 } 359 360 LineTableInfo &SourceManager::getLineTable() { 361 if (LineTable == 0) 362 LineTable = new LineTableInfo(); 363 return *LineTable; 364 } 365 366 //===----------------------------------------------------------------------===// 367 // Private 'Create' methods. 368 //===----------------------------------------------------------------------===// 369 370 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr) 371 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true), 372 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0), 373 NumBinaryProbes(0), FakeBufferForRecovery(0) { 374 clearIDTables(); 375 Diag.setSourceManager(this); 376 } 377 378 SourceManager::~SourceManager() { 379 delete LineTable; 380 381 // Delete FileEntry objects corresponding to content caches. Since the actual 382 // content cache objects are bump pointer allocated, we just have to run the 383 // dtors, but we call the deallocate method for completeness. 384 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) { 385 if (MemBufferInfos[i]) { 386 MemBufferInfos[i]->~ContentCache(); 387 ContentCacheAlloc.Deallocate(MemBufferInfos[i]); 388 } 389 } 390 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator 391 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) { 392 if (I->second) { 393 I->second->~ContentCache(); 394 ContentCacheAlloc.Deallocate(I->second); 395 } 396 } 397 398 delete FakeBufferForRecovery; 399 400 for (llvm::DenseMap<FileID, MacroArgsMap *>::iterator 401 I = MacroArgsCacheMap.begin(),E = MacroArgsCacheMap.end(); I!=E; ++I) { 402 delete I->second; 403 } 404 } 405 406 void SourceManager::clearIDTables() { 407 MainFileID = FileID(); 408 LocalSLocEntryTable.clear(); 409 LoadedSLocEntryTable.clear(); 410 SLocEntryLoaded.clear(); 411 LastLineNoFileIDQuery = FileID(); 412 LastLineNoContentCache = 0; 413 LastFileIDLookup = FileID(); 414 415 if (LineTable) 416 LineTable->clear(); 417 418 // Use up FileID #0 as an invalid expansion. 419 NextLocalOffset = 0; 420 CurrentLoadedOffset = MaxLoadedOffset; 421 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1); 422 } 423 424 /// getOrCreateContentCache - Create or return a cached ContentCache for the 425 /// specified file. 426 const ContentCache * 427 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) { 428 assert(FileEnt && "Didn't specify a file entry to use?"); 429 430 // Do we already have information about this file? 431 ContentCache *&Entry = FileInfos[FileEnt]; 432 if (Entry) return Entry; 433 434 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned 435 // so that FileInfo can use the low 3 bits of the pointer for its own 436 // nefarious purposes. 437 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment; 438 EntryAlign = std::max(8U, EntryAlign); 439 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign); 440 441 // If the file contents are overridden with contents from another file, 442 // pass that file to ContentCache. 443 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator 444 overI = OverriddenFiles.find(FileEnt); 445 if (overI == OverriddenFiles.end()) 446 new (Entry) ContentCache(FileEnt); 447 else 448 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt 449 : overI->second, 450 overI->second); 451 452 return Entry; 453 } 454 455 456 /// createMemBufferContentCache - Create a new ContentCache for the specified 457 /// memory buffer. This does no caching. 458 const ContentCache* 459 SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) { 460 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure 461 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of 462 // the pointer for its own nefarious purposes. 463 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment; 464 EntryAlign = std::max(8U, EntryAlign); 465 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign); 466 new (Entry) ContentCache(); 467 MemBufferInfos.push_back(Entry); 468 Entry->setBuffer(Buffer); 469 return Entry; 470 } 471 472 std::pair<int, unsigned> 473 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries, 474 unsigned TotalSize) { 475 assert(ExternalSLocEntries && "Don't have an external sloc source"); 476 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries); 477 SLocEntryLoaded.resize(LoadedSLocEntryTable.size()); 478 CurrentLoadedOffset -= TotalSize; 479 assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations"); 480 int ID = LoadedSLocEntryTable.size(); 481 return std::make_pair(-ID - 1, CurrentLoadedOffset); 482 } 483 484 /// \brief As part of recovering from missing or changed content, produce a 485 /// fake, non-empty buffer. 486 const llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const { 487 if (!FakeBufferForRecovery) 488 FakeBufferForRecovery 489 = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>"); 490 491 return FakeBufferForRecovery; 492 } 493 494 //===----------------------------------------------------------------------===// 495 // Methods to create new FileID's and macro expansions. 496 //===----------------------------------------------------------------------===// 497 498 /// createFileID - Create a new FileID for the specified ContentCache and 499 /// include position. This works regardless of whether the ContentCache 500 /// corresponds to a file or some other input source. 501 FileID SourceManager::createFileID(const ContentCache *File, 502 SourceLocation IncludePos, 503 SrcMgr::CharacteristicKind FileCharacter, 504 int LoadedID, unsigned LoadedOffset) { 505 if (LoadedID < 0) { 506 assert(LoadedID != -1 && "Loading sentinel FileID"); 507 unsigned Index = unsigned(-LoadedID) - 2; 508 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range"); 509 assert(!SLocEntryLoaded[Index] && "FileID already loaded"); 510 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, 511 FileInfo::get(IncludePos, File, FileCharacter)); 512 SLocEntryLoaded[Index] = true; 513 return FileID::get(LoadedID); 514 } 515 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, 516 FileInfo::get(IncludePos, File, 517 FileCharacter))); 518 unsigned FileSize = File->getSize(); 519 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset && 520 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset && 521 "Ran out of source locations!"); 522 // We do a +1 here because we want a SourceLocation that means "the end of the 523 // file", e.g. for the "no newline at the end of the file" diagnostic. 524 NextLocalOffset += FileSize + 1; 525 526 // Set LastFileIDLookup to the newly created file. The next getFileID call is 527 // almost guaranteed to be from that file. 528 FileID FID = FileID::get(LocalSLocEntryTable.size()-1); 529 return LastFileIDLookup = FID; 530 } 531 532 SourceLocation 533 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc, 534 SourceLocation ExpansionLoc, 535 unsigned TokLength) { 536 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc, 537 ExpansionLoc); 538 return createExpansionLocImpl(Info, TokLength); 539 } 540 541 SourceLocation 542 SourceManager::createExpansionLoc(SourceLocation SpellingLoc, 543 SourceLocation ExpansionLocStart, 544 SourceLocation ExpansionLocEnd, 545 unsigned TokLength, 546 int LoadedID, 547 unsigned LoadedOffset) { 548 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart, 549 ExpansionLocEnd); 550 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset); 551 } 552 553 SourceLocation 554 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info, 555 unsigned TokLength, 556 int LoadedID, 557 unsigned LoadedOffset) { 558 if (LoadedID < 0) { 559 assert(LoadedID != -1 && "Loading sentinel FileID"); 560 unsigned Index = unsigned(-LoadedID) - 2; 561 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range"); 562 assert(!SLocEntryLoaded[Index] && "FileID already loaded"); 563 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info); 564 SLocEntryLoaded[Index] = true; 565 return SourceLocation::getMacroLoc(LoadedOffset); 566 } 567 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info)); 568 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset && 569 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset && 570 "Ran out of source locations!"); 571 // See createFileID for that +1. 572 NextLocalOffset += TokLength + 1; 573 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1)); 574 } 575 576 const llvm::MemoryBuffer * 577 SourceManager::getMemoryBufferForFile(const FileEntry *File, 578 bool *Invalid) { 579 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File); 580 assert(IR && "getOrCreateContentCache() cannot return NULL"); 581 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid); 582 } 583 584 void SourceManager::overrideFileContents(const FileEntry *SourceFile, 585 const llvm::MemoryBuffer *Buffer, 586 bool DoNotFree) { 587 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile); 588 assert(IR && "getOrCreateContentCache() cannot return NULL"); 589 590 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree); 591 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true; 592 } 593 594 void SourceManager::overrideFileContents(const FileEntry *SourceFile, 595 const FileEntry *NewFile) { 596 assert(SourceFile->getSize() == NewFile->getSize() && 597 "Different sizes, use the FileManager to create a virtual file with " 598 "the correct size"); 599 assert(FileInfos.count(SourceFile) == 0 && 600 "This function should be called at the initialization stage, before " 601 "any parsing occurs."); 602 OverriddenFiles[SourceFile] = NewFile; 603 } 604 605 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const { 606 bool MyInvalid = false; 607 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid); 608 if (!SLoc.isFile() || MyInvalid) { 609 if (Invalid) 610 *Invalid = true; 611 return "<<<<<INVALID SOURCE LOCATION>>>>>"; 612 } 613 614 const llvm::MemoryBuffer *Buf 615 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(), 616 &MyInvalid); 617 if (Invalid) 618 *Invalid = MyInvalid; 619 620 if (MyInvalid) 621 return "<<<<<INVALID SOURCE LOCATION>>>>>"; 622 623 return Buf->getBuffer(); 624 } 625 626 //===----------------------------------------------------------------------===// 627 // SourceLocation manipulation methods. 628 //===----------------------------------------------------------------------===// 629 630 /// \brief Return the FileID for a SourceLocation. 631 /// 632 /// This is the cache-miss path of getFileID. Not as hot as that function, but 633 /// still very important. It is responsible for finding the entry in the 634 /// SLocEntry tables that contains the specified location. 635 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const { 636 if (!SLocOffset) 637 return FileID::get(0); 638 639 // Now it is time to search for the correct file. See where the SLocOffset 640 // sits in the global view and consult local or loaded buffers for it. 641 if (SLocOffset < NextLocalOffset) 642 return getFileIDLocal(SLocOffset); 643 return getFileIDLoaded(SLocOffset); 644 } 645 646 /// \brief Return the FileID for a SourceLocation with a low offset. 647 /// 648 /// This function knows that the SourceLocation is in a local buffer, not a 649 /// loaded one. 650 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const { 651 assert(SLocOffset < NextLocalOffset && "Bad function choice"); 652 653 // After the first and second level caches, I see two common sorts of 654 // behavior: 1) a lot of searched FileID's are "near" the cached file 655 // location or are "near" the cached expansion location. 2) others are just 656 // completely random and may be a very long way away. 657 // 658 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly 659 // then we fall back to a less cache efficient, but more scalable, binary 660 // search to find the location. 661 662 // See if this is near the file point - worst case we start scanning from the 663 // most newly created FileID. 664 std::vector<SrcMgr::SLocEntry>::const_iterator I; 665 666 if (LastFileIDLookup.ID < 0 || 667 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) { 668 // Neither loc prunes our search. 669 I = LocalSLocEntryTable.end(); 670 } else { 671 // Perhaps it is near the file point. 672 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID; 673 } 674 675 // Find the FileID that contains this. "I" is an iterator that points to a 676 // FileID whose offset is known to be larger than SLocOffset. 677 unsigned NumProbes = 0; 678 while (1) { 679 --I; 680 if (I->getOffset() <= SLocOffset) { 681 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin())); 682 683 // If this isn't an expansion, remember it. We have good locality across 684 // FileID lookups. 685 if (!I->isExpansion()) 686 LastFileIDLookup = Res; 687 NumLinearScans += NumProbes+1; 688 return Res; 689 } 690 if (++NumProbes == 8) 691 break; 692 } 693 694 // Convert "I" back into an index. We know that it is an entry whose index is 695 // larger than the offset we are looking for. 696 unsigned GreaterIndex = I - LocalSLocEntryTable.begin(); 697 // LessIndex - This is the lower bound of the range that we're searching. 698 // We know that the offset corresponding to the FileID is is less than 699 // SLocOffset. 700 unsigned LessIndex = 0; 701 NumProbes = 0; 702 while (1) { 703 bool Invalid = false; 704 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex; 705 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset(); 706 if (Invalid) 707 return FileID::get(0); 708 709 ++NumProbes; 710 711 // If the offset of the midpoint is too large, chop the high side of the 712 // range to the midpoint. 713 if (MidOffset > SLocOffset) { 714 GreaterIndex = MiddleIndex; 715 continue; 716 } 717 718 // If the middle index contains the value, succeed and return. 719 // FIXME: This could be made faster by using a function that's aware of 720 // being in the local area. 721 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) { 722 FileID Res = FileID::get(MiddleIndex); 723 724 // If this isn't a macro expansion, remember it. We have good locality 725 // across FileID lookups. 726 if (!LocalSLocEntryTable[MiddleIndex].isExpansion()) 727 LastFileIDLookup = Res; 728 NumBinaryProbes += NumProbes; 729 return Res; 730 } 731 732 // Otherwise, move the low-side up to the middle index. 733 LessIndex = MiddleIndex; 734 } 735 } 736 737 /// \brief Return the FileID for a SourceLocation with a high offset. 738 /// 739 /// This function knows that the SourceLocation is in a loaded buffer, not a 740 /// local one. 741 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const { 742 // Sanity checking, otherwise a bug may lead to hanging in release build. 743 if (SLocOffset < CurrentLoadedOffset) { 744 assert(0 && "Invalid SLocOffset or bad function choice"); 745 return FileID(); 746 } 747 748 // Essentially the same as the local case, but the loaded array is sorted 749 // in the other direction. 750 751 // First do a linear scan from the last lookup position, if possible. 752 unsigned I; 753 int LastID = LastFileIDLookup.ID; 754 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset) 755 I = 0; 756 else 757 I = (-LastID - 2) + 1; 758 759 unsigned NumProbes; 760 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) { 761 // Make sure the entry is loaded! 762 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I); 763 if (E.getOffset() <= SLocOffset) { 764 FileID Res = FileID::get(-int(I) - 2); 765 766 if (!E.isExpansion()) 767 LastFileIDLookup = Res; 768 NumLinearScans += NumProbes + 1; 769 return Res; 770 } 771 } 772 773 // Linear scan failed. Do the binary search. Note the reverse sorting of the 774 // table: GreaterIndex is the one where the offset is greater, which is 775 // actually a lower index! 776 unsigned GreaterIndex = I; 777 unsigned LessIndex = LoadedSLocEntryTable.size(); 778 NumProbes = 0; 779 while (1) { 780 ++NumProbes; 781 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex; 782 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex); 783 784 ++NumProbes; 785 786 if (E.getOffset() > SLocOffset) { 787 GreaterIndex = MiddleIndex; 788 continue; 789 } 790 791 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) { 792 FileID Res = FileID::get(-int(MiddleIndex) - 2); 793 if (!E.isExpansion()) 794 LastFileIDLookup = Res; 795 NumBinaryProbes += NumProbes; 796 return Res; 797 } 798 799 LessIndex = MiddleIndex; 800 } 801 } 802 803 SourceLocation SourceManager:: 804 getExpansionLocSlowCase(SourceLocation Loc) const { 805 do { 806 // Note: If Loc indicates an offset into a token that came from a macro 807 // expansion (e.g. the 5th character of the token) we do not want to add 808 // this offset when going to the expansion location. The expansion 809 // location is the macro invocation, which the offset has nothing to do 810 // with. This is unlike when we get the spelling loc, because the offset 811 // directly correspond to the token whose spelling we're inspecting. 812 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart(); 813 } while (!Loc.isFileID()); 814 815 return Loc; 816 } 817 818 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const { 819 do { 820 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc); 821 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc(); 822 Loc = Loc.getLocWithOffset(LocInfo.second); 823 } while (!Loc.isFileID()); 824 return Loc; 825 } 826 827 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const { 828 do { 829 if (isMacroArgExpansion(Loc)) 830 Loc = getImmediateSpellingLoc(Loc); 831 else 832 Loc = getImmediateExpansionRange(Loc).first; 833 } while (!Loc.isFileID()); 834 return Loc; 835 } 836 837 838 std::pair<FileID, unsigned> 839 SourceManager::getDecomposedExpansionLocSlowCase( 840 const SrcMgr::SLocEntry *E) const { 841 // If this is an expansion record, walk through all the expansion points. 842 FileID FID; 843 SourceLocation Loc; 844 unsigned Offset; 845 do { 846 Loc = E->getExpansion().getExpansionLocStart(); 847 848 FID = getFileID(Loc); 849 E = &getSLocEntry(FID); 850 Offset = Loc.getOffset()-E->getOffset(); 851 } while (!Loc.isFileID()); 852 853 return std::make_pair(FID, Offset); 854 } 855 856 std::pair<FileID, unsigned> 857 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E, 858 unsigned Offset) const { 859 // If this is an expansion record, walk through all the expansion points. 860 FileID FID; 861 SourceLocation Loc; 862 do { 863 Loc = E->getExpansion().getSpellingLoc(); 864 Loc = Loc.getLocWithOffset(Offset); 865 866 FID = getFileID(Loc); 867 E = &getSLocEntry(FID); 868 Offset = Loc.getOffset()-E->getOffset(); 869 } while (!Loc.isFileID()); 870 871 return std::make_pair(FID, Offset); 872 } 873 874 /// getImmediateSpellingLoc - Given a SourceLocation object, return the 875 /// spelling location referenced by the ID. This is the first level down 876 /// towards the place where the characters that make up the lexed token can be 877 /// found. This should not generally be used by clients. 878 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{ 879 if (Loc.isFileID()) return Loc; 880 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc); 881 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc(); 882 return Loc.getLocWithOffset(LocInfo.second); 883 } 884 885 886 /// getImmediateExpansionRange - Loc is required to be an expansion location. 887 /// Return the start/end of the expansion information. 888 std::pair<SourceLocation,SourceLocation> 889 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const { 890 assert(Loc.isMacroID() && "Not a macro expansion loc!"); 891 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion(); 892 return Expansion.getExpansionLocRange(); 893 } 894 895 /// getExpansionRange - Given a SourceLocation object, return the range of 896 /// tokens covered by the expansion in the ultimate file. 897 std::pair<SourceLocation,SourceLocation> 898 SourceManager::getExpansionRange(SourceLocation Loc) const { 899 if (Loc.isFileID()) return std::make_pair(Loc, Loc); 900 901 std::pair<SourceLocation,SourceLocation> Res = 902 getImmediateExpansionRange(Loc); 903 904 // Fully resolve the start and end locations to their ultimate expansion 905 // points. 906 while (!Res.first.isFileID()) 907 Res.first = getImmediateExpansionRange(Res.first).first; 908 while (!Res.second.isFileID()) 909 Res.second = getImmediateExpansionRange(Res.second).second; 910 return Res; 911 } 912 913 bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const { 914 if (!Loc.isMacroID()) return false; 915 916 FileID FID = getFileID(Loc); 917 const SrcMgr::SLocEntry *E = &getSLocEntry(FID); 918 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion(); 919 return Expansion.isMacroArgExpansion(); 920 } 921 922 923 //===----------------------------------------------------------------------===// 924 // Queries about the code at a SourceLocation. 925 //===----------------------------------------------------------------------===// 926 927 /// getCharacterData - Return a pointer to the start of the specified location 928 /// in the appropriate MemoryBuffer. 929 const char *SourceManager::getCharacterData(SourceLocation SL, 930 bool *Invalid) const { 931 // Note that this is a hot function in the getSpelling() path, which is 932 // heavily used by -E mode. 933 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL); 934 935 // Note that calling 'getBuffer()' may lazily page in a source file. 936 bool CharDataInvalid = false; 937 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid); 938 if (CharDataInvalid || !Entry.isFile()) { 939 if (Invalid) 940 *Invalid = true; 941 942 return "<<<<INVALID BUFFER>>>>"; 943 } 944 const llvm::MemoryBuffer *Buffer 945 = Entry.getFile().getContentCache() 946 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid); 947 if (Invalid) 948 *Invalid = CharDataInvalid; 949 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second); 950 } 951 952 953 /// getColumnNumber - Return the column # for the specified file position. 954 /// this is significantly cheaper to compute than the line number. 955 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos, 956 bool *Invalid) const { 957 bool MyInvalid = false; 958 const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid); 959 if (Invalid) 960 *Invalid = MyInvalid; 961 962 if (MyInvalid) 963 return 1; 964 965 const char *Buf = MemBuf->getBufferStart(); 966 if (Buf + FilePos >= MemBuf->getBufferEnd()) { 967 if (Invalid) 968 *Invalid = MyInvalid; 969 return 1; 970 } 971 972 unsigned LineStart = FilePos; 973 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r') 974 --LineStart; 975 return FilePos-LineStart+1; 976 } 977 978 // isInvalid - Return the result of calling loc.isInvalid(), and 979 // if Invalid is not null, set its value to same. 980 static bool isInvalid(SourceLocation Loc, bool *Invalid) { 981 bool MyInvalid = Loc.isInvalid(); 982 if (Invalid) 983 *Invalid = MyInvalid; 984 return MyInvalid; 985 } 986 987 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc, 988 bool *Invalid) const { 989 if (isInvalid(Loc, Invalid)) return 0; 990 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); 991 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid); 992 } 993 994 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc, 995 bool *Invalid) const { 996 if (isInvalid(Loc, Invalid)) return 0; 997 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); 998 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid); 999 } 1000 1001 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc, 1002 bool *Invalid) const { 1003 if (isInvalid(Loc, Invalid)) return 0; 1004 return getPresumedLoc(Loc).getColumn(); 1005 } 1006 1007 static LLVM_ATTRIBUTE_NOINLINE void 1008 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI, 1009 llvm::BumpPtrAllocator &Alloc, 1010 const SourceManager &SM, bool &Invalid); 1011 static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI, 1012 llvm::BumpPtrAllocator &Alloc, 1013 const SourceManager &SM, bool &Invalid) { 1014 // Note that calling 'getBuffer()' may lazily page in the file. 1015 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), 1016 &Invalid); 1017 if (Invalid) 1018 return; 1019 1020 // Find the file offsets of all of the *physical* source lines. This does 1021 // not look at trigraphs, escaped newlines, or anything else tricky. 1022 SmallVector<unsigned, 256> LineOffsets; 1023 1024 // Line #1 starts at char 0. 1025 LineOffsets.push_back(0); 1026 1027 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart(); 1028 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd(); 1029 unsigned Offs = 0; 1030 while (1) { 1031 // Skip over the contents of the line. 1032 // TODO: Vectorize this? This is very performance sensitive for programs 1033 // with lots of diagnostics and in -E mode. 1034 const unsigned char *NextBuf = (const unsigned char *)Buf; 1035 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0') 1036 ++NextBuf; 1037 Offs += NextBuf-Buf; 1038 Buf = NextBuf; 1039 1040 if (Buf[0] == '\n' || Buf[0] == '\r') { 1041 // If this is \n\r or \r\n, skip both characters. 1042 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) 1043 ++Offs, ++Buf; 1044 ++Offs, ++Buf; 1045 LineOffsets.push_back(Offs); 1046 } else { 1047 // Otherwise, this is a null. If end of file, exit. 1048 if (Buf == End) break; 1049 // Otherwise, skip the null. 1050 ++Offs, ++Buf; 1051 } 1052 } 1053 1054 // Copy the offsets into the FileInfo structure. 1055 FI->NumLines = LineOffsets.size(); 1056 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size()); 1057 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache); 1058 } 1059 1060 /// getLineNumber - Given a SourceLocation, return the spelling line number 1061 /// for the position indicated. This requires building and caching a table of 1062 /// line offsets for the MemoryBuffer, so this is not cheap: use only when 1063 /// about to emit a diagnostic. 1064 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, 1065 bool *Invalid) const { 1066 if (FID.isInvalid()) { 1067 if (Invalid) 1068 *Invalid = true; 1069 return 1; 1070 } 1071 1072 ContentCache *Content; 1073 if (LastLineNoFileIDQuery == FID) 1074 Content = LastLineNoContentCache; 1075 else { 1076 bool MyInvalid = false; 1077 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid); 1078 if (MyInvalid || !Entry.isFile()) { 1079 if (Invalid) 1080 *Invalid = true; 1081 return 1; 1082 } 1083 1084 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache()); 1085 } 1086 1087 // If this is the first use of line information for this buffer, compute the 1088 /// SourceLineCache for it on demand. 1089 if (Content->SourceLineCache == 0) { 1090 bool MyInvalid = false; 1091 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid); 1092 if (Invalid) 1093 *Invalid = MyInvalid; 1094 if (MyInvalid) 1095 return 1; 1096 } else if (Invalid) 1097 *Invalid = false; 1098 1099 // Okay, we know we have a line number table. Do a binary search to find the 1100 // line number that this character position lands on. 1101 unsigned *SourceLineCache = Content->SourceLineCache; 1102 unsigned *SourceLineCacheStart = SourceLineCache; 1103 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines; 1104 1105 unsigned QueriedFilePos = FilePos+1; 1106 1107 // FIXME: I would like to be convinced that this code is worth being as 1108 // complicated as it is, binary search isn't that slow. 1109 // 1110 // If it is worth being optimized, then in my opinion it could be more 1111 // performant, simpler, and more obviously correct by just "galloping" outward 1112 // from the queried file position. In fact, this could be incorporated into a 1113 // generic algorithm such as lower_bound_with_hint. 1114 // 1115 // If someone gives me a test case where this matters, and I will do it! - DWD 1116 1117 // If the previous query was to the same file, we know both the file pos from 1118 // that query and the line number returned. This allows us to narrow the 1119 // search space from the entire file to something near the match. 1120 if (LastLineNoFileIDQuery == FID) { 1121 if (QueriedFilePos >= LastLineNoFilePos) { 1122 // FIXME: Potential overflow? 1123 SourceLineCache = SourceLineCache+LastLineNoResult-1; 1124 1125 // The query is likely to be nearby the previous one. Here we check to 1126 // see if it is within 5, 10 or 20 lines. It can be far away in cases 1127 // where big comment blocks and vertical whitespace eat up lines but 1128 // contribute no tokens. 1129 if (SourceLineCache+5 < SourceLineCacheEnd) { 1130 if (SourceLineCache[5] > QueriedFilePos) 1131 SourceLineCacheEnd = SourceLineCache+5; 1132 else if (SourceLineCache+10 < SourceLineCacheEnd) { 1133 if (SourceLineCache[10] > QueriedFilePos) 1134 SourceLineCacheEnd = SourceLineCache+10; 1135 else if (SourceLineCache+20 < SourceLineCacheEnd) { 1136 if (SourceLineCache[20] > QueriedFilePos) 1137 SourceLineCacheEnd = SourceLineCache+20; 1138 } 1139 } 1140 } 1141 } else { 1142 if (LastLineNoResult < Content->NumLines) 1143 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1; 1144 } 1145 } 1146 1147 // If the spread is large, do a "radix" test as our initial guess, based on 1148 // the assumption that lines average to approximately the same length. 1149 // NOTE: This is currently disabled, as it does not appear to be profitable in 1150 // initial measurements. 1151 if (0 && SourceLineCacheEnd-SourceLineCache > 20) { 1152 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1]; 1153 1154 // Take a stab at guessing where it is. 1155 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen; 1156 1157 // Check for -10 and +10 lines. 1158 unsigned LowerBound = std::max(int(ApproxPos-10), 0); 1159 unsigned UpperBound = std::min(ApproxPos+10, FileLen); 1160 1161 // If the computed lower bound is less than the query location, move it in. 1162 if (SourceLineCache < SourceLineCacheStart+LowerBound && 1163 SourceLineCacheStart[LowerBound] < QueriedFilePos) 1164 SourceLineCache = SourceLineCacheStart+LowerBound; 1165 1166 // If the computed upper bound is greater than the query location, move it. 1167 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound && 1168 SourceLineCacheStart[UpperBound] >= QueriedFilePos) 1169 SourceLineCacheEnd = SourceLineCacheStart+UpperBound; 1170 } 1171 1172 unsigned *Pos 1173 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos); 1174 unsigned LineNo = Pos-SourceLineCacheStart; 1175 1176 LastLineNoFileIDQuery = FID; 1177 LastLineNoContentCache = Content; 1178 LastLineNoFilePos = QueriedFilePos; 1179 LastLineNoResult = LineNo; 1180 return LineNo; 1181 } 1182 1183 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc, 1184 bool *Invalid) const { 1185 if (isInvalid(Loc, Invalid)) return 0; 1186 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); 1187 return getLineNumber(LocInfo.first, LocInfo.second); 1188 } 1189 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc, 1190 bool *Invalid) const { 1191 if (isInvalid(Loc, Invalid)) return 0; 1192 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); 1193 return getLineNumber(LocInfo.first, LocInfo.second); 1194 } 1195 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc, 1196 bool *Invalid) const { 1197 if (isInvalid(Loc, Invalid)) return 0; 1198 return getPresumedLoc(Loc).getLine(); 1199 } 1200 1201 /// getFileCharacteristic - return the file characteristic of the specified 1202 /// source location, indicating whether this is a normal file, a system 1203 /// header, or an "implicit extern C" system header. 1204 /// 1205 /// This state can be modified with flags on GNU linemarker directives like: 1206 /// # 4 "foo.h" 3 1207 /// which changes all source locations in the current file after that to be 1208 /// considered to be from a system header. 1209 SrcMgr::CharacteristicKind 1210 SourceManager::getFileCharacteristic(SourceLocation Loc) const { 1211 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!"); 1212 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); 1213 bool Invalid = false; 1214 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid); 1215 if (Invalid || !SEntry.isFile()) 1216 return C_User; 1217 1218 const SrcMgr::FileInfo &FI = SEntry.getFile(); 1219 1220 // If there are no #line directives in this file, just return the whole-file 1221 // state. 1222 if (!FI.hasLineDirectives()) 1223 return FI.getFileCharacteristic(); 1224 1225 assert(LineTable && "Can't have linetable entries without a LineTable!"); 1226 // See if there is a #line directive before the location. 1227 const LineEntry *Entry = 1228 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second); 1229 1230 // If this is before the first line marker, use the file characteristic. 1231 if (!Entry) 1232 return FI.getFileCharacteristic(); 1233 1234 return Entry->FileKind; 1235 } 1236 1237 /// Return the filename or buffer identifier of the buffer the location is in. 1238 /// Note that this name does not respect #line directives. Use getPresumedLoc 1239 /// for normal clients. 1240 const char *SourceManager::getBufferName(SourceLocation Loc, 1241 bool *Invalid) const { 1242 if (isInvalid(Loc, Invalid)) return "<invalid loc>"; 1243 1244 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier(); 1245 } 1246 1247 1248 /// getPresumedLoc - This method returns the "presumed" location of a 1249 /// SourceLocation specifies. A "presumed location" can be modified by #line 1250 /// or GNU line marker directives. This provides a view on the data that a 1251 /// user should see in diagnostics, for example. 1252 /// 1253 /// Note that a presumed location is always given as the expansion point of an 1254 /// expansion location, not at the spelling location. 1255 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const { 1256 if (Loc.isInvalid()) return PresumedLoc(); 1257 1258 // Presumed locations are always for expansion points. 1259 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); 1260 1261 bool Invalid = false; 1262 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); 1263 if (Invalid || !Entry.isFile()) 1264 return PresumedLoc(); 1265 1266 const SrcMgr::FileInfo &FI = Entry.getFile(); 1267 const SrcMgr::ContentCache *C = FI.getContentCache(); 1268 1269 // To get the source name, first consult the FileEntry (if one exists) 1270 // before the MemBuffer as this will avoid unnecessarily paging in the 1271 // MemBuffer. 1272 const char *Filename; 1273 if (C->OrigEntry) 1274 Filename = C->OrigEntry->getName(); 1275 else 1276 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier(); 1277 1278 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid); 1279 if (Invalid) 1280 return PresumedLoc(); 1281 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid); 1282 if (Invalid) 1283 return PresumedLoc(); 1284 1285 SourceLocation IncludeLoc = FI.getIncludeLoc(); 1286 1287 // If we have #line directives in this file, update and overwrite the physical 1288 // location info if appropriate. 1289 if (FI.hasLineDirectives()) { 1290 assert(LineTable && "Can't have linetable entries without a LineTable!"); 1291 // See if there is a #line directive before this. If so, get it. 1292 if (const LineEntry *Entry = 1293 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) { 1294 // If the LineEntry indicates a filename, use it. 1295 if (Entry->FilenameID != -1) 1296 Filename = LineTable->getFilename(Entry->FilenameID); 1297 1298 // Use the line number specified by the LineEntry. This line number may 1299 // be multiple lines down from the line entry. Add the difference in 1300 // physical line numbers from the query point and the line marker to the 1301 // total. 1302 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset); 1303 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1); 1304 1305 // Note that column numbers are not molested by line markers. 1306 1307 // Handle virtual #include manipulation. 1308 if (Entry->IncludeOffset) { 1309 IncludeLoc = getLocForStartOfFile(LocInfo.first); 1310 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset); 1311 } 1312 } 1313 } 1314 1315 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc); 1316 } 1317 1318 /// \brief The size of the SLocEnty that \arg FID represents. 1319 unsigned SourceManager::getFileIDSize(FileID FID) const { 1320 bool Invalid = false; 1321 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid); 1322 if (Invalid) 1323 return 0; 1324 1325 int ID = FID.ID; 1326 unsigned NextOffset; 1327 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size())) 1328 NextOffset = getNextLocalOffset(); 1329 else if (ID+1 == -1) 1330 NextOffset = MaxLoadedOffset; 1331 else 1332 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset(); 1333 1334 return NextOffset - Entry.getOffset() - 1; 1335 } 1336 1337 //===----------------------------------------------------------------------===// 1338 // Other miscellaneous methods. 1339 //===----------------------------------------------------------------------===// 1340 1341 /// \brief Retrieve the inode for the given file entry, if possible. 1342 /// 1343 /// This routine involves a system call, and therefore should only be used 1344 /// in non-performance-critical code. 1345 static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) { 1346 if (!File) 1347 return llvm::Optional<ino_t>(); 1348 1349 struct stat StatBuf; 1350 if (::stat(File->getName(), &StatBuf)) 1351 return llvm::Optional<ino_t>(); 1352 1353 return StatBuf.st_ino; 1354 } 1355 1356 /// \brief Get the source location for the given file:line:col triplet. 1357 /// 1358 /// If the source file is included multiple times, the source location will 1359 /// be based upon an arbitrary inclusion. 1360 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile, 1361 unsigned Line, 1362 unsigned Col) const { 1363 assert(SourceFile && "Null source file!"); 1364 assert(Line && Col && "Line and column should start from 1!"); 1365 1366 FileID FirstFID = translateFile(SourceFile); 1367 return translateLineCol(FirstFID, Line, Col); 1368 } 1369 1370 /// \brief Get the FileID for the given file. 1371 /// 1372 /// If the source file is included multiple times, the FileID will be the 1373 /// first inclusion. 1374 FileID SourceManager::translateFile(const FileEntry *SourceFile) const { 1375 assert(SourceFile && "Null source file!"); 1376 1377 // Find the first file ID that corresponds to the given file. 1378 FileID FirstFID; 1379 1380 // First, check the main file ID, since it is common to look for a 1381 // location in the main file. 1382 llvm::Optional<ino_t> SourceFileInode; 1383 llvm::Optional<StringRef> SourceFileName; 1384 if (!MainFileID.isInvalid()) { 1385 bool Invalid = false; 1386 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid); 1387 if (Invalid) 1388 return FileID(); 1389 1390 if (MainSLoc.isFile()) { 1391 const ContentCache *MainContentCache 1392 = MainSLoc.getFile().getContentCache(); 1393 if (!MainContentCache) { 1394 // Can't do anything 1395 } else if (MainContentCache->OrigEntry == SourceFile) { 1396 FirstFID = MainFileID; 1397 } else { 1398 // Fall back: check whether we have the same base name and inode 1399 // as the main file. 1400 const FileEntry *MainFile = MainContentCache->OrigEntry; 1401 SourceFileName = llvm::sys::path::filename(SourceFile->getName()); 1402 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) { 1403 SourceFileInode = getActualFileInode(SourceFile); 1404 if (SourceFileInode) { 1405 if (llvm::Optional<ino_t> MainFileInode 1406 = getActualFileInode(MainFile)) { 1407 if (*SourceFileInode == *MainFileInode) { 1408 FirstFID = MainFileID; 1409 SourceFile = MainFile; 1410 } 1411 } 1412 } 1413 } 1414 } 1415 } 1416 } 1417 1418 if (FirstFID.isInvalid()) { 1419 // The location we're looking for isn't in the main file; look 1420 // through all of the local source locations. 1421 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) { 1422 bool Invalid = false; 1423 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid); 1424 if (Invalid) 1425 return FileID(); 1426 1427 if (SLoc.isFile() && 1428 SLoc.getFile().getContentCache() && 1429 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) { 1430 FirstFID = FileID::get(I); 1431 break; 1432 } 1433 } 1434 // If that still didn't help, try the modules. 1435 if (FirstFID.isInvalid()) { 1436 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) { 1437 const SLocEntry &SLoc = getLoadedSLocEntry(I); 1438 if (SLoc.isFile() && 1439 SLoc.getFile().getContentCache() && 1440 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) { 1441 FirstFID = FileID::get(-int(I) - 2); 1442 break; 1443 } 1444 } 1445 } 1446 } 1447 1448 // If we haven't found what we want yet, try again, but this time stat() 1449 // each of the files in case the files have changed since we originally 1450 // parsed the file. 1451 if (FirstFID.isInvalid() && 1452 (SourceFileName || 1453 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) && 1454 (SourceFileInode || 1455 (SourceFileInode = getActualFileInode(SourceFile)))) { 1456 bool Invalid = false; 1457 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) { 1458 FileID IFileID; 1459 IFileID.ID = I; 1460 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid); 1461 if (Invalid) 1462 return FileID(); 1463 1464 if (SLoc.isFile()) { 1465 const ContentCache *FileContentCache 1466 = SLoc.getFile().getContentCache(); 1467 const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0; 1468 if (Entry && 1469 *SourceFileName == llvm::sys::path::filename(Entry->getName())) { 1470 if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) { 1471 if (*SourceFileInode == *EntryInode) { 1472 FirstFID = FileID::get(I); 1473 SourceFile = Entry; 1474 break; 1475 } 1476 } 1477 } 1478 } 1479 } 1480 } 1481 1482 return FirstFID; 1483 } 1484 1485 /// \brief Get the source location in \arg FID for the given line:col. 1486 /// Returns null location if \arg FID is not a file SLocEntry. 1487 SourceLocation SourceManager::translateLineCol(FileID FID, 1488 unsigned Line, 1489 unsigned Col) const { 1490 if (FID.isInvalid()) 1491 return SourceLocation(); 1492 1493 bool Invalid = false; 1494 const SLocEntry &Entry = getSLocEntry(FID, &Invalid); 1495 if (Invalid) 1496 return SourceLocation(); 1497 1498 if (!Entry.isFile()) 1499 return SourceLocation(); 1500 1501 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset()); 1502 1503 if (Line == 1 && Col == 1) 1504 return FileLoc; 1505 1506 ContentCache *Content 1507 = const_cast<ContentCache *>(Entry.getFile().getContentCache()); 1508 if (!Content) 1509 return SourceLocation(); 1510 1511 // If this is the first use of line information for this buffer, compute the 1512 // SourceLineCache for it on demand. 1513 if (Content->SourceLineCache == 0) { 1514 bool MyInvalid = false; 1515 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid); 1516 if (MyInvalid) 1517 return SourceLocation(); 1518 } 1519 1520 if (Line > Content->NumLines) { 1521 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize(); 1522 if (Size > 0) 1523 --Size; 1524 return FileLoc.getLocWithOffset(Size); 1525 } 1526 1527 unsigned FilePos = Content->SourceLineCache[Line - 1]; 1528 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos; 1529 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf; 1530 if (BufLength == 0) 1531 return FileLoc.getLocWithOffset(FilePos); 1532 1533 unsigned i = 0; 1534 1535 // Check that the given column is valid. 1536 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r') 1537 ++i; 1538 if (i < Col-1) 1539 return FileLoc.getLocWithOffset(FilePos + i); 1540 1541 return FileLoc.getLocWithOffset(FilePos + Col - 1); 1542 } 1543 1544 /// \brief Compute a map of macro argument chunks to their expanded source 1545 /// location. Chunks that are not part of a macro argument will map to an 1546 /// invalid source location. e.g. if a file contains one macro argument at 1547 /// offset 100 with length 10, this is how the map will be formed: 1548 /// 0 -> SourceLocation() 1549 /// 100 -> Expanded macro arg location 1550 /// 110 -> SourceLocation() 1551 void SourceManager::computeMacroArgsCache(MacroArgsMap *&CachePtr, 1552 FileID FID) const { 1553 assert(!FID.isInvalid()); 1554 assert(!CachePtr); 1555 1556 CachePtr = new MacroArgsMap(); 1557 MacroArgsMap &MacroArgsCache = *CachePtr; 1558 // Initially no macro argument chunk is present. 1559 MacroArgsCache.insert(std::make_pair(0, SourceLocation())); 1560 1561 int ID = FID.ID; 1562 while (1) { 1563 ++ID; 1564 // Stop if there are no more FileIDs to check. 1565 if (ID > 0) { 1566 if (unsigned(ID) >= local_sloc_entry_size()) 1567 return; 1568 } else if (ID == -1) { 1569 return; 1570 } 1571 1572 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID); 1573 if (Entry.isFile()) { 1574 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc(); 1575 if (IncludeLoc.isInvalid()) 1576 continue; 1577 if (!isInFileID(IncludeLoc, FID)) 1578 return; // No more files/macros that may be "contained" in this file. 1579 1580 // Skip the files/macros of the #include'd file, we only care about macros 1581 // that lexed macro arguments from our file. 1582 if (Entry.getFile().NumCreatedFIDs) 1583 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/; 1584 continue; 1585 } 1586 1587 if (!Entry.getExpansion().isMacroArgExpansion()) 1588 continue; 1589 1590 SourceLocation SpellLoc = 1591 getSpellingLoc(Entry.getExpansion().getSpellingLoc()); 1592 unsigned BeginOffs; 1593 if (!isInFileID(SpellLoc, FID, &BeginOffs)) 1594 return; // No more files/macros that may be "contained" in this file. 1595 unsigned EndOffs = BeginOffs + getFileIDSize(FileID::get(ID)); 1596 1597 // Add a new chunk for this macro argument. A previous macro argument chunk 1598 // may have been lexed again, so e.g. if the map is 1599 // 0 -> SourceLocation() 1600 // 100 -> Expanded loc #1 1601 // 110 -> SourceLocation() 1602 // and we found a new macro FileID that lexed from offet 105 with length 3, 1603 // the new map will be: 1604 // 0 -> SourceLocation() 1605 // 100 -> Expanded loc #1 1606 // 105 -> Expanded loc #2 1607 // 108 -> Expanded loc #1 1608 // 110 -> SourceLocation() 1609 // 1610 // Since re-lexed macro chunks will always be the same size or less of 1611 // previous chunks, we only need to find where the ending of the new macro 1612 // chunk is mapped to and update the map with new begin/end mappings. 1613 1614 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs); 1615 --I; 1616 SourceLocation EndOffsMappedLoc = I->second; 1617 MacroArgsCache[BeginOffs] = SourceLocation::getMacroLoc(Entry.getOffset()); 1618 MacroArgsCache[EndOffs] = EndOffsMappedLoc; 1619 } 1620 } 1621 1622 /// \brief If \arg Loc points inside a function macro argument, the returned 1623 /// location will be the macro location in which the argument was expanded. 1624 /// If a macro argument is used multiple times, the expanded location will 1625 /// be at the first expansion of the argument. 1626 /// e.g. 1627 /// MY_MACRO(foo); 1628 /// ^ 1629 /// Passing a file location pointing at 'foo', will yield a macro location 1630 /// where 'foo' was expanded into. 1631 SourceLocation 1632 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const { 1633 if (Loc.isInvalid() || !Loc.isFileID()) 1634 return Loc; 1635 1636 FileID FID; 1637 unsigned Offset; 1638 llvm::tie(FID, Offset) = getDecomposedLoc(Loc); 1639 if (FID.isInvalid()) 1640 return Loc; 1641 1642 MacroArgsMap *&MacroArgsCache = MacroArgsCacheMap[FID]; 1643 if (!MacroArgsCache) 1644 computeMacroArgsCache(MacroArgsCache, FID); 1645 1646 assert(!MacroArgsCache->empty()); 1647 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset); 1648 --I; 1649 1650 unsigned MacroArgBeginOffs = I->first; 1651 SourceLocation MacroArgExpandedLoc = I->second; 1652 if (MacroArgExpandedLoc.isValid()) 1653 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs); 1654 1655 return Loc; 1656 } 1657 1658 /// Given a decomposed source location, move it up the include/expansion stack 1659 /// to the parent source location. If this is possible, return the decomposed 1660 /// version of the parent in Loc and return false. If Loc is the top-level 1661 /// entry, return true and don't modify it. 1662 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc, 1663 const SourceManager &SM) { 1664 SourceLocation UpperLoc; 1665 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first); 1666 if (Entry.isExpansion()) 1667 UpperLoc = Entry.getExpansion().getExpansionLocEnd(); 1668 else 1669 UpperLoc = Entry.getFile().getIncludeLoc(); 1670 1671 if (UpperLoc.isInvalid()) 1672 return true; // We reached the top. 1673 1674 Loc = SM.getDecomposedLoc(UpperLoc); 1675 return false; 1676 } 1677 1678 1679 /// \brief Determines the order of 2 source locations in the translation unit. 1680 /// 1681 /// \returns true if LHS source location comes before RHS, false otherwise. 1682 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS, 1683 SourceLocation RHS) const { 1684 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!"); 1685 if (LHS == RHS) 1686 return false; 1687 1688 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS); 1689 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS); 1690 1691 // If the source locations are in the same file, just compare offsets. 1692 if (LOffs.first == ROffs.first) 1693 return LOffs.second < ROffs.second; 1694 1695 // If we are comparing a source location with multiple locations in the same 1696 // file, we get a big win by caching the result. 1697 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first)) 1698 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second); 1699 1700 // Okay, we missed in the cache, start updating the cache for this query. 1701 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first, 1702 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID); 1703 1704 // We need to find the common ancestor. The only way of doing this is to 1705 // build the complete include chain for one and then walking up the chain 1706 // of the other looking for a match. 1707 // We use a map from FileID to Offset to store the chain. Easier than writing 1708 // a custom set hash info that only depends on the first part of a pair. 1709 typedef llvm::DenseMap<FileID, unsigned> LocSet; 1710 LocSet LChain; 1711 do { 1712 LChain.insert(LOffs); 1713 // We catch the case where LOffs is in a file included by ROffs and 1714 // quit early. The other way round unfortunately remains suboptimal. 1715 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this)); 1716 LocSet::iterator I; 1717 while((I = LChain.find(ROffs.first)) == LChain.end()) { 1718 if (MoveUpIncludeHierarchy(ROffs, *this)) 1719 break; // Met at topmost file. 1720 } 1721 if (I != LChain.end()) 1722 LOffs = *I; 1723 1724 // If we exited because we found a nearest common ancestor, compare the 1725 // locations within the common file and cache them. 1726 if (LOffs.first == ROffs.first) { 1727 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second); 1728 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second); 1729 } 1730 1731 // This can happen if a location is in a built-ins buffer. 1732 // But see PR5662. 1733 // Clear the lookup cache, it depends on a common location. 1734 IsBeforeInTUCache.clear(); 1735 bool LIsBuiltins = strcmp("<built-in>", 1736 getBuffer(LOffs.first)->getBufferIdentifier()) == 0; 1737 bool RIsBuiltins = strcmp("<built-in>", 1738 getBuffer(ROffs.first)->getBufferIdentifier()) == 0; 1739 // built-in is before non-built-in 1740 if (LIsBuiltins != RIsBuiltins) 1741 return LIsBuiltins; 1742 assert(LIsBuiltins && RIsBuiltins && 1743 "Non-built-in locations must be rooted in the main file"); 1744 // Both are in built-in buffers, but from different files. We just claim that 1745 // lower IDs come first. 1746 return LOffs.first < ROffs.first; 1747 } 1748 1749 /// PrintStats - Print statistics to stderr. 1750 /// 1751 void SourceManager::PrintStats() const { 1752 llvm::errs() << "\n*** Source Manager Stats:\n"; 1753 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size() 1754 << " mem buffers mapped.\n"; 1755 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated (" 1756 << llvm::capacity_in_bytes(LocalSLocEntryTable) 1757 << " bytes of capacity), " 1758 << NextLocalOffset << "B of Sloc address space used.\n"; 1759 llvm::errs() << LoadedSLocEntryTable.size() 1760 << " loaded SLocEntries allocated, " 1761 << MaxLoadedOffset - CurrentLoadedOffset 1762 << "B of Sloc address space used.\n"; 1763 1764 unsigned NumLineNumsComputed = 0; 1765 unsigned NumFileBytesMapped = 0; 1766 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){ 1767 NumLineNumsComputed += I->second->SourceLineCache != 0; 1768 NumFileBytesMapped += I->second->getSizeBytesMapped(); 1769 } 1770 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size(); 1771 1772 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, " 1773 << NumLineNumsComputed << " files with line #'s computed, " 1774 << NumMacroArgsComputed << " files with macro args computed.\n"; 1775 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, " 1776 << NumBinaryProbes << " binary.\n"; 1777 } 1778 1779 ExternalSLocEntrySource::~ExternalSLocEntrySource() { } 1780 1781 /// Return the amount of memory used by memory buffers, breaking down 1782 /// by heap-backed versus mmap'ed memory. 1783 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const { 1784 size_t malloc_bytes = 0; 1785 size_t mmap_bytes = 0; 1786 1787 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) 1788 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped()) 1789 switch (MemBufferInfos[i]->getMemoryBufferKind()) { 1790 case llvm::MemoryBuffer::MemoryBuffer_MMap: 1791 mmap_bytes += sized_mapped; 1792 break; 1793 case llvm::MemoryBuffer::MemoryBuffer_Malloc: 1794 malloc_bytes += sized_mapped; 1795 break; 1796 } 1797 1798 return MemoryBufferSizes(malloc_bytes, mmap_bytes); 1799 } 1800 1801 size_t SourceManager::getDataStructureSizes() const { 1802 return llvm::capacity_in_bytes(MemBufferInfos) 1803 + llvm::capacity_in_bytes(LocalSLocEntryTable) 1804 + llvm::capacity_in_bytes(LoadedSLocEntryTable) 1805 + llvm::capacity_in_bytes(SLocEntryLoaded) 1806 + llvm::capacity_in_bytes(FileInfos) 1807 + llvm::capacity_in_bytes(OverriddenFiles); 1808 } 1809