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