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/Support/Compiler.h" 19 #include "llvm/Support/MemoryBuffer.h" 20 #include "llvm/Support/raw_ostream.h" 21 #include "llvm/System/Path.h" 22 #include <algorithm> 23 #include <string> 24 #include <cstring> 25 26 using namespace clang; 27 using namespace SrcMgr; 28 using llvm::MemoryBuffer; 29 30 //===----------------------------------------------------------------------===// 31 // SourceManager Helper Classes 32 //===----------------------------------------------------------------------===// 33 34 ContentCache::~ContentCache() { 35 delete Buffer.getPointer(); 36 } 37 38 /// getSizeBytesMapped - Returns the number of bytes actually mapped for 39 /// this ContentCache. This can be 0 if the MemBuffer was not actually 40 /// instantiated. 41 unsigned ContentCache::getSizeBytesMapped() const { 42 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0; 43 } 44 45 /// getSize - Returns the size of the content encapsulated by this ContentCache. 46 /// This can be the size of the source file or the size of an arbitrary 47 /// scratch buffer. If the ContentCache encapsulates a source file, that 48 /// file is not lazily brought in from disk to satisfy this query. 49 unsigned ContentCache::getSize() const { 50 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize() 51 : (unsigned) Entry->getSize(); 52 } 53 54 void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B) { 55 assert(B != Buffer.getPointer()); 56 57 delete Buffer.getPointer(); 58 Buffer.setPointer(B); 59 Buffer.setInt(false); 60 } 61 62 const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag, 63 bool *Invalid) const { 64 if (Invalid) 65 *Invalid = false; 66 67 // Lazily create the Buffer for ContentCaches that wrap files. 68 if (!Buffer.getPointer() && Entry) { 69 std::string ErrorStr; 70 struct stat FileInfo; 71 Buffer.setPointer(MemoryBuffer::getFile(Entry->getName(), &ErrorStr, 72 Entry->getSize(), &FileInfo)); 73 Buffer.setInt(false); 74 75 // If we were unable to open the file, then we are in an inconsistent 76 // situation where the content cache referenced a file which no longer 77 // exists. Most likely, we were using a stat cache with an invalid entry but 78 // the file could also have been removed during processing. Since we can't 79 // really deal with this situation, just create an empty buffer. 80 // 81 // FIXME: This is definitely not ideal, but our immediate clients can't 82 // currently handle returning a null entry here. Ideally we should detect 83 // that we are in an inconsistent situation and error out as quickly as 84 // possible. 85 if (!Buffer.getPointer()) { 86 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n"); 87 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(Entry->getSize(), 88 "<invalid>")); 89 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart()); 90 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i) 91 Ptr[i] = FillStr[i % FillStr.size()]; 92 93 if (Diag.isDiagnosticInFlight()) 94 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file, 95 Entry->getName(), ErrorStr); 96 else 97 Diag.Report(diag::err_cannot_open_file) 98 << Entry->getName() << ErrorStr; 99 100 Buffer.setInt(true); 101 102 // FIXME: This conditionalization is horrible, but we see spurious failures 103 // in the test suite due to this warning and no one has had time to hunt it 104 // down. So for now, we just don't emit this diagnostic on Win32, and hope 105 // nothing bad happens. 106 // 107 // PR6812. 108 #if !defined(LLVM_ON_WIN32) 109 } else if (FileInfo.st_size != Entry->getSize() || 110 FileInfo.st_mtime != Entry->getModificationTime()) { 111 // Check that the file's size and modification time are the same 112 // as in the file entry (which may have come from a stat cache). 113 if (Diag.isDiagnosticInFlight()) 114 Diag.SetDelayedDiagnostic(diag::err_file_modified, 115 Entry->getName()); 116 else 117 Diag.Report(diag::err_file_modified) << Entry->getName(); 118 119 Buffer.setInt(true); 120 #endif 121 } 122 } 123 124 if (Invalid) 125 *Invalid = Buffer.getInt(); 126 127 return Buffer.getPointer(); 128 } 129 130 unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) { 131 // Look up the filename in the string table, returning the pre-existing value 132 // if it exists. 133 llvm::StringMapEntry<unsigned> &Entry = 134 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U); 135 if (Entry.getValue() != ~0U) 136 return Entry.getValue(); 137 138 // Otherwise, assign this the next available ID. 139 Entry.setValue(FilenamesByID.size()); 140 FilenamesByID.push_back(&Entry); 141 return FilenamesByID.size()-1; 142 } 143 144 /// AddLineNote - Add a line note to the line table that indicates that there 145 /// is a #line at the specified FID/Offset location which changes the presumed 146 /// location to LineNo/FilenameID. 147 void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset, 148 unsigned LineNo, int FilenameID) { 149 std::vector<LineEntry> &Entries = LineEntries[FID]; 150 151 assert((Entries.empty() || Entries.back().FileOffset < Offset) && 152 "Adding line entries out of order!"); 153 154 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User; 155 unsigned IncludeOffset = 0; 156 157 if (!Entries.empty()) { 158 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember 159 // that we are still in "foo.h". 160 if (FilenameID == -1) 161 FilenameID = Entries.back().FilenameID; 162 163 // If we are after a line marker that switched us to system header mode, or 164 // that set #include information, preserve it. 165 Kind = Entries.back().FileKind; 166 IncludeOffset = Entries.back().IncludeOffset; 167 } 168 169 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind, 170 IncludeOffset)); 171 } 172 173 /// AddLineNote This is the same as the previous version of AddLineNote, but is 174 /// used for GNU line markers. If EntryExit is 0, then this doesn't change the 175 /// presumed #include stack. If it is 1, this is a file entry, if it is 2 then 176 /// this is a file exit. FileKind specifies whether this is a system header or 177 /// extern C system header. 178 void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset, 179 unsigned LineNo, int FilenameID, 180 unsigned EntryExit, 181 SrcMgr::CharacteristicKind FileKind) { 182 assert(FilenameID != -1 && "Unspecified filename should use other accessor"); 183 184 std::vector<LineEntry> &Entries = LineEntries[FID]; 185 186 assert((Entries.empty() || Entries.back().FileOffset < Offset) && 187 "Adding line entries out of order!"); 188 189 unsigned IncludeOffset = 0; 190 if (EntryExit == 0) { // No #include stack change. 191 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset; 192 } else if (EntryExit == 1) { 193 IncludeOffset = Offset-1; 194 } else if (EntryExit == 2) { 195 assert(!Entries.empty() && Entries.back().IncludeOffset && 196 "PPDirectives should have caught case when popping empty include stack"); 197 198 // Get the include loc of the last entries' include loc as our include loc. 199 IncludeOffset = 0; 200 if (const LineEntry *PrevEntry = 201 FindNearestLineEntry(FID, Entries.back().IncludeOffset)) 202 IncludeOffset = PrevEntry->IncludeOffset; 203 } 204 205 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind, 206 IncludeOffset)); 207 } 208 209 210 /// FindNearestLineEntry - Find the line entry nearest to FID that is before 211 /// it. If there is no line entry before Offset in FID, return null. 212 const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID, 213 unsigned Offset) { 214 const std::vector<LineEntry> &Entries = LineEntries[FID]; 215 assert(!Entries.empty() && "No #line entries for this FID after all!"); 216 217 // It is very common for the query to be after the last #line, check this 218 // first. 219 if (Entries.back().FileOffset <= Offset) 220 return &Entries.back(); 221 222 // Do a binary search to find the maximal element that is still before Offset. 223 std::vector<LineEntry>::const_iterator I = 224 std::upper_bound(Entries.begin(), Entries.end(), Offset); 225 if (I == Entries.begin()) return 0; 226 return &*--I; 227 } 228 229 /// \brief Add a new line entry that has already been encoded into 230 /// the internal representation of the line table. 231 void LineTableInfo::AddEntry(unsigned FID, 232 const std::vector<LineEntry> &Entries) { 233 LineEntries[FID] = Entries; 234 } 235 236 /// getLineTableFilenameID - Return the uniqued ID for the specified filename. 237 /// 238 unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) { 239 if (LineTable == 0) 240 LineTable = new LineTableInfo(); 241 return LineTable->getLineTableFilenameID(Ptr, Len); 242 } 243 244 245 /// AddLineNote - Add a line note to the line table for the FileID and offset 246 /// specified by Loc. If FilenameID is -1, it is considered to be 247 /// unspecified. 248 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, 249 int FilenameID) { 250 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc); 251 252 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile(); 253 254 // Remember that this file has #line directives now if it doesn't already. 255 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives(); 256 257 if (LineTable == 0) 258 LineTable = new LineTableInfo(); 259 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID); 260 } 261 262 /// AddLineNote - Add a GNU line marker to the line table. 263 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, 264 int FilenameID, bool IsFileEntry, 265 bool IsFileExit, bool IsSystemHeader, 266 bool IsExternCHeader) { 267 // If there is no filename and no flags, this is treated just like a #line, 268 // which does not change the flags of the previous line marker. 269 if (FilenameID == -1) { 270 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader && 271 "Can't set flags without setting the filename!"); 272 return AddLineNote(Loc, LineNo, FilenameID); 273 } 274 275 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc); 276 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile(); 277 278 // Remember that this file has #line directives now if it doesn't already. 279 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives(); 280 281 if (LineTable == 0) 282 LineTable = new LineTableInfo(); 283 284 SrcMgr::CharacteristicKind FileKind; 285 if (IsExternCHeader) 286 FileKind = SrcMgr::C_ExternCSystem; 287 else if (IsSystemHeader) 288 FileKind = SrcMgr::C_System; 289 else 290 FileKind = SrcMgr::C_User; 291 292 unsigned EntryExit = 0; 293 if (IsFileEntry) 294 EntryExit = 1; 295 else if (IsFileExit) 296 EntryExit = 2; 297 298 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID, 299 EntryExit, FileKind); 300 } 301 302 LineTableInfo &SourceManager::getLineTable() { 303 if (LineTable == 0) 304 LineTable = new LineTableInfo(); 305 return *LineTable; 306 } 307 308 //===----------------------------------------------------------------------===// 309 // Private 'Create' methods. 310 //===----------------------------------------------------------------------===// 311 312 SourceManager::~SourceManager() { 313 delete LineTable; 314 315 // Delete FileEntry objects corresponding to content caches. Since the actual 316 // content cache objects are bump pointer allocated, we just have to run the 317 // dtors, but we call the deallocate method for completeness. 318 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) { 319 MemBufferInfos[i]->~ContentCache(); 320 ContentCacheAlloc.Deallocate(MemBufferInfos[i]); 321 } 322 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator 323 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) { 324 I->second->~ContentCache(); 325 ContentCacheAlloc.Deallocate(I->second); 326 } 327 } 328 329 void SourceManager::clearIDTables() { 330 MainFileID = FileID(); 331 SLocEntryTable.clear(); 332 LastLineNoFileIDQuery = FileID(); 333 LastLineNoContentCache = 0; 334 LastFileIDLookup = FileID(); 335 336 if (LineTable) 337 LineTable->clear(); 338 339 // Use up FileID #0 as an invalid instantiation. 340 NextOffset = 0; 341 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1); 342 } 343 344 /// getOrCreateContentCache - Create or return a cached ContentCache for the 345 /// specified file. 346 const ContentCache * 347 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) { 348 assert(FileEnt && "Didn't specify a file entry to use?"); 349 350 // Do we already have information about this file? 351 ContentCache *&Entry = FileInfos[FileEnt]; 352 if (Entry) return Entry; 353 354 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned 355 // so that FileInfo can use the low 3 bits of the pointer for its own 356 // nefarious purposes. 357 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment; 358 EntryAlign = std::max(8U, EntryAlign); 359 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign); 360 new (Entry) ContentCache(FileEnt); 361 return Entry; 362 } 363 364 365 /// createMemBufferContentCache - Create a new ContentCache for the specified 366 /// memory buffer. This does no caching. 367 const ContentCache* 368 SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) { 369 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure 370 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of 371 // the pointer for its own nefarious purposes. 372 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment; 373 EntryAlign = std::max(8U, EntryAlign); 374 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign); 375 new (Entry) ContentCache(); 376 MemBufferInfos.push_back(Entry); 377 Entry->setBuffer(Buffer); 378 return Entry; 379 } 380 381 void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source, 382 unsigned NumSLocEntries, 383 unsigned NextOffset) { 384 ExternalSLocEntries = Source; 385 this->NextOffset = NextOffset; 386 SLocEntryLoaded.resize(NumSLocEntries + 1); 387 SLocEntryLoaded[0] = true; 388 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries); 389 } 390 391 void SourceManager::ClearPreallocatedSLocEntries() { 392 unsigned I = 0; 393 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I) 394 if (!SLocEntryLoaded[I]) 395 break; 396 397 // We've already loaded all preallocated source location entries. 398 if (I == SLocEntryLoaded.size()) 399 return; 400 401 // Remove everything from location I onward. 402 SLocEntryTable.resize(I); 403 SLocEntryLoaded.clear(); 404 ExternalSLocEntries = 0; 405 } 406 407 408 //===----------------------------------------------------------------------===// 409 // Methods to create new FileID's and instantiations. 410 //===----------------------------------------------------------------------===// 411 412 /// createFileID - Create a new fileID for the specified ContentCache and 413 /// include position. This works regardless of whether the ContentCache 414 /// corresponds to a file or some other input source. 415 FileID SourceManager::createFileID(const ContentCache *File, 416 SourceLocation IncludePos, 417 SrcMgr::CharacteristicKind FileCharacter, 418 unsigned PreallocatedID, 419 unsigned Offset) { 420 if (PreallocatedID) { 421 // If we're filling in a preallocated ID, just load in the file 422 // entry and return. 423 assert(PreallocatedID < SLocEntryLoaded.size() && 424 "Preallocate ID out-of-range"); 425 assert(!SLocEntryLoaded[PreallocatedID] && 426 "Source location entry already loaded"); 427 assert(Offset && "Preallocate source location cannot have zero offset"); 428 SLocEntryTable[PreallocatedID] 429 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter)); 430 SLocEntryLoaded[PreallocatedID] = true; 431 FileID FID = FileID::get(PreallocatedID); 432 return FID; 433 } 434 435 SLocEntryTable.push_back(SLocEntry::get(NextOffset, 436 FileInfo::get(IncludePos, File, 437 FileCharacter))); 438 unsigned FileSize = File->getSize(); 439 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!"); 440 NextOffset += FileSize+1; 441 442 // Set LastFileIDLookup to the newly created file. The next getFileID call is 443 // almost guaranteed to be from that file. 444 FileID FID = FileID::get(SLocEntryTable.size()-1); 445 return LastFileIDLookup = FID; 446 } 447 448 /// createInstantiationLoc - Return a new SourceLocation that encodes the fact 449 /// that a token from SpellingLoc should actually be referenced from 450 /// InstantiationLoc. 451 SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc, 452 SourceLocation ILocStart, 453 SourceLocation ILocEnd, 454 unsigned TokLength, 455 unsigned PreallocatedID, 456 unsigned Offset) { 457 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc); 458 if (PreallocatedID) { 459 // If we're filling in a preallocated ID, just load in the 460 // instantiation entry and return. 461 assert(PreallocatedID < SLocEntryLoaded.size() && 462 "Preallocate ID out-of-range"); 463 assert(!SLocEntryLoaded[PreallocatedID] && 464 "Source location entry already loaded"); 465 assert(Offset && "Preallocate source location cannot have zero offset"); 466 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II); 467 SLocEntryLoaded[PreallocatedID] = true; 468 return SourceLocation::getMacroLoc(Offset); 469 } 470 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II)); 471 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!"); 472 NextOffset += TokLength+1; 473 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1)); 474 } 475 476 const llvm::MemoryBuffer * 477 SourceManager::getMemoryBufferForFile(const FileEntry *File, 478 bool *Invalid) { 479 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File); 480 assert(IR && "getOrCreateContentCache() cannot return NULL"); 481 return IR->getBuffer(Diag, Invalid); 482 } 483 484 bool SourceManager::overrideFileContents(const FileEntry *SourceFile, 485 const llvm::MemoryBuffer *Buffer) { 486 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile); 487 if (IR == 0) 488 return true; 489 490 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer); 491 return false; 492 } 493 494 llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const { 495 bool MyInvalid = false; 496 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid); 497 if (Invalid) 498 *Invalid = MyInvalid; 499 500 if (MyInvalid) 501 return ""; 502 503 return Buf->getBuffer(); 504 } 505 506 //===----------------------------------------------------------------------===// 507 // SourceLocation manipulation methods. 508 //===----------------------------------------------------------------------===// 509 510 /// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot 511 /// method that is used for all SourceManager queries that start with a 512 /// SourceLocation object. It is responsible for finding the entry in 513 /// SLocEntryTable which contains the specified location. 514 /// 515 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const { 516 assert(SLocOffset && "Invalid FileID"); 517 518 // After the first and second level caches, I see two common sorts of 519 // behavior: 1) a lot of searched FileID's are "near" the cached file location 520 // or are "near" the cached instantiation location. 2) others are just 521 // completely random and may be a very long way away. 522 // 523 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly 524 // then we fall back to a less cache efficient, but more scalable, binary 525 // search to find the location. 526 527 // See if this is near the file point - worst case we start scanning from the 528 // most newly created FileID. 529 std::vector<SrcMgr::SLocEntry>::const_iterator I; 530 531 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) { 532 // Neither loc prunes our search. 533 I = SLocEntryTable.end(); 534 } else { 535 // Perhaps it is near the file point. 536 I = SLocEntryTable.begin()+LastFileIDLookup.ID; 537 } 538 539 // Find the FileID that contains this. "I" is an iterator that points to a 540 // FileID whose offset is known to be larger than SLocOffset. 541 unsigned NumProbes = 0; 542 while (1) { 543 --I; 544 if (ExternalSLocEntries) 545 getSLocEntry(FileID::get(I - SLocEntryTable.begin())); 546 if (I->getOffset() <= SLocOffset) { 547 #if 0 548 printf("lin %d -> %d [%s] %d %d\n", SLocOffset, 549 I-SLocEntryTable.begin(), 550 I->isInstantiation() ? "inst" : "file", 551 LastFileIDLookup.ID, int(SLocEntryTable.end()-I)); 552 #endif 553 FileID Res = FileID::get(I-SLocEntryTable.begin()); 554 555 // If this isn't an instantiation, remember it. We have good locality 556 // across FileID lookups. 557 if (!I->isInstantiation()) 558 LastFileIDLookup = Res; 559 NumLinearScans += NumProbes+1; 560 return Res; 561 } 562 if (++NumProbes == 8) 563 break; 564 } 565 566 // Convert "I" back into an index. We know that it is an entry whose index is 567 // larger than the offset we are looking for. 568 unsigned GreaterIndex = I-SLocEntryTable.begin(); 569 // LessIndex - This is the lower bound of the range that we're searching. 570 // We know that the offset corresponding to the FileID is is less than 571 // SLocOffset. 572 unsigned LessIndex = 0; 573 NumProbes = 0; 574 while (1) { 575 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex; 576 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset(); 577 578 ++NumProbes; 579 580 // If the offset of the midpoint is too large, chop the high side of the 581 // range to the midpoint. 582 if (MidOffset > SLocOffset) { 583 GreaterIndex = MiddleIndex; 584 continue; 585 } 586 587 // If the middle index contains the value, succeed and return. 588 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) { 589 #if 0 590 printf("bin %d -> %d [%s] %d %d\n", SLocOffset, 591 I-SLocEntryTable.begin(), 592 I->isInstantiation() ? "inst" : "file", 593 LastFileIDLookup.ID, int(SLocEntryTable.end()-I)); 594 #endif 595 FileID Res = FileID::get(MiddleIndex); 596 597 // If this isn't an instantiation, remember it. We have good locality 598 // across FileID lookups. 599 if (!I->isInstantiation()) 600 LastFileIDLookup = Res; 601 NumBinaryProbes += NumProbes; 602 return Res; 603 } 604 605 // Otherwise, move the low-side up to the middle index. 606 LessIndex = MiddleIndex; 607 } 608 } 609 610 SourceLocation SourceManager:: 611 getInstantiationLocSlowCase(SourceLocation Loc) const { 612 do { 613 // Note: If Loc indicates an offset into a token that came from a macro 614 // expansion (e.g. the 5th character of the token) we do not want to add 615 // this offset when going to the instantiation location. The instatiation 616 // location is the macro invocation, which the offset has nothing to do 617 // with. This is unlike when we get the spelling loc, because the offset 618 // directly correspond to the token whose spelling we're inspecting. 619 Loc = getSLocEntry(getFileID(Loc)).getInstantiation() 620 .getInstantiationLocStart(); 621 } while (!Loc.isFileID()); 622 623 return Loc; 624 } 625 626 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const { 627 do { 628 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc); 629 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc(); 630 Loc = Loc.getFileLocWithOffset(LocInfo.second); 631 } while (!Loc.isFileID()); 632 return Loc; 633 } 634 635 636 std::pair<FileID, unsigned> 637 SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E, 638 unsigned Offset) const { 639 // If this is an instantiation record, walk through all the instantiation 640 // points. 641 FileID FID; 642 SourceLocation Loc; 643 do { 644 Loc = E->getInstantiation().getInstantiationLocStart(); 645 646 FID = getFileID(Loc); 647 E = &getSLocEntry(FID); 648 Offset += Loc.getOffset()-E->getOffset(); 649 } while (!Loc.isFileID()); 650 651 return std::make_pair(FID, Offset); 652 } 653 654 std::pair<FileID, unsigned> 655 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E, 656 unsigned Offset) const { 657 // If this is an instantiation record, walk through all the instantiation 658 // points. 659 FileID FID; 660 SourceLocation Loc; 661 do { 662 Loc = E->getInstantiation().getSpellingLoc(); 663 664 FID = getFileID(Loc); 665 E = &getSLocEntry(FID); 666 Offset += Loc.getOffset()-E->getOffset(); 667 } while (!Loc.isFileID()); 668 669 return std::make_pair(FID, Offset); 670 } 671 672 /// getImmediateSpellingLoc - Given a SourceLocation object, return the 673 /// spelling location referenced by the ID. This is the first level down 674 /// towards the place where the characters that make up the lexed token can be 675 /// found. This should not generally be used by clients. 676 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{ 677 if (Loc.isFileID()) return Loc; 678 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc); 679 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc(); 680 return Loc.getFileLocWithOffset(LocInfo.second); 681 } 682 683 684 /// getImmediateInstantiationRange - Loc is required to be an instantiation 685 /// location. Return the start/end of the instantiation information. 686 std::pair<SourceLocation,SourceLocation> 687 SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const { 688 assert(Loc.isMacroID() && "Not an instantiation loc!"); 689 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation(); 690 return II.getInstantiationLocRange(); 691 } 692 693 /// getInstantiationRange - Given a SourceLocation object, return the 694 /// range of tokens covered by the instantiation in the ultimate file. 695 std::pair<SourceLocation,SourceLocation> 696 SourceManager::getInstantiationRange(SourceLocation Loc) const { 697 if (Loc.isFileID()) return std::make_pair(Loc, Loc); 698 699 std::pair<SourceLocation,SourceLocation> Res = 700 getImmediateInstantiationRange(Loc); 701 702 // Fully resolve the start and end locations to their ultimate instantiation 703 // points. 704 while (!Res.first.isFileID()) 705 Res.first = getImmediateInstantiationRange(Res.first).first; 706 while (!Res.second.isFileID()) 707 Res.second = getImmediateInstantiationRange(Res.second).second; 708 return Res; 709 } 710 711 712 713 //===----------------------------------------------------------------------===// 714 // Queries about the code at a SourceLocation. 715 //===----------------------------------------------------------------------===// 716 717 /// getCharacterData - Return a pointer to the start of the specified location 718 /// in the appropriate MemoryBuffer. 719 const char *SourceManager::getCharacterData(SourceLocation SL, 720 bool *Invalid) const { 721 // Note that this is a hot function in the getSpelling() path, which is 722 // heavily used by -E mode. 723 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL); 724 725 // Note that calling 'getBuffer()' may lazily page in a source file. 726 bool CharDataInvalid = false; 727 const llvm::MemoryBuffer *Buffer 728 = getSLocEntry(LocInfo.first).getFile().getContentCache()->getBuffer(Diag, 729 &CharDataInvalid); 730 if (Invalid) 731 *Invalid = CharDataInvalid; 732 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second); 733 } 734 735 736 /// getColumnNumber - Return the column # for the specified file position. 737 /// this is significantly cheaper to compute than the line number. 738 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos, 739 bool *Invalid) const { 740 bool MyInvalid = false; 741 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart(); 742 if (Invalid) 743 *Invalid = MyInvalid; 744 745 if (MyInvalid) 746 return 1; 747 748 unsigned LineStart = FilePos; 749 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r') 750 --LineStart; 751 return FilePos-LineStart+1; 752 } 753 754 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc, 755 bool *Invalid) const { 756 if (Loc.isInvalid()) return 0; 757 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); 758 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid); 759 } 760 761 unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc, 762 bool *Invalid) const { 763 if (Loc.isInvalid()) return 0; 764 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc); 765 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid); 766 } 767 768 static DISABLE_INLINE void ComputeLineNumbers(Diagnostic &Diag, 769 ContentCache* FI, 770 llvm::BumpPtrAllocator &Alloc, 771 bool &Invalid); 772 static void ComputeLineNumbers(Diagnostic &Diag, ContentCache* FI, 773 llvm::BumpPtrAllocator &Alloc, bool &Invalid) { 774 // Note that calling 'getBuffer()' may lazily page in the file. 775 const MemoryBuffer *Buffer = FI->getBuffer(Diag, &Invalid); 776 if (Invalid) 777 return; 778 779 // Find the file offsets of all of the *physical* source lines. This does 780 // not look at trigraphs, escaped newlines, or anything else tricky. 781 std::vector<unsigned> LineOffsets; 782 783 // Line #1 starts at char 0. 784 LineOffsets.push_back(0); 785 786 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart(); 787 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd(); 788 unsigned Offs = 0; 789 while (1) { 790 // Skip over the contents of the line. 791 // TODO: Vectorize this? This is very performance sensitive for programs 792 // with lots of diagnostics and in -E mode. 793 const unsigned char *NextBuf = (const unsigned char *)Buf; 794 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0') 795 ++NextBuf; 796 Offs += NextBuf-Buf; 797 Buf = NextBuf; 798 799 if (Buf[0] == '\n' || Buf[0] == '\r') { 800 // If this is \n\r or \r\n, skip both characters. 801 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) 802 ++Offs, ++Buf; 803 ++Offs, ++Buf; 804 LineOffsets.push_back(Offs); 805 } else { 806 // Otherwise, this is a null. If end of file, exit. 807 if (Buf == End) break; 808 // Otherwise, skip the null. 809 ++Offs, ++Buf; 810 } 811 } 812 813 // Copy the offsets into the FileInfo structure. 814 FI->NumLines = LineOffsets.size(); 815 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size()); 816 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache); 817 } 818 819 /// getLineNumber - Given a SourceLocation, return the spelling line number 820 /// for the position indicated. This requires building and caching a table of 821 /// line offsets for the MemoryBuffer, so this is not cheap: use only when 822 /// about to emit a diagnostic. 823 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, 824 bool *Invalid) const { 825 ContentCache *Content; 826 if (LastLineNoFileIDQuery == FID) 827 Content = LastLineNoContentCache; 828 else 829 Content = const_cast<ContentCache*>(getSLocEntry(FID) 830 .getFile().getContentCache()); 831 832 // If this is the first use of line information for this buffer, compute the 833 /// SourceLineCache for it on demand. 834 if (Content->SourceLineCache == 0) { 835 bool MyInvalid = false; 836 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid); 837 if (Invalid) 838 *Invalid = MyInvalid; 839 if (MyInvalid) 840 return 1; 841 } else if (Invalid) 842 *Invalid = false; 843 844 // Okay, we know we have a line number table. Do a binary search to find the 845 // line number that this character position lands on. 846 unsigned *SourceLineCache = Content->SourceLineCache; 847 unsigned *SourceLineCacheStart = SourceLineCache; 848 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines; 849 850 unsigned QueriedFilePos = FilePos+1; 851 852 // FIXME: I would like to be convinced that this code is worth being as 853 // complicated as it is, binary search isn't that slow. 854 // 855 // If it is worth being optimized, then in my opinion it could be more 856 // performant, simpler, and more obviously correct by just "galloping" outward 857 // from the queried file position. In fact, this could be incorporated into a 858 // generic algorithm such as lower_bound_with_hint. 859 // 860 // If someone gives me a test case where this matters, and I will do it! - DWD 861 862 // If the previous query was to the same file, we know both the file pos from 863 // that query and the line number returned. This allows us to narrow the 864 // search space from the entire file to something near the match. 865 if (LastLineNoFileIDQuery == FID) { 866 if (QueriedFilePos >= LastLineNoFilePos) { 867 // FIXME: Potential overflow? 868 SourceLineCache = SourceLineCache+LastLineNoResult-1; 869 870 // The query is likely to be nearby the previous one. Here we check to 871 // see if it is within 5, 10 or 20 lines. It can be far away in cases 872 // where big comment blocks and vertical whitespace eat up lines but 873 // contribute no tokens. 874 if (SourceLineCache+5 < SourceLineCacheEnd) { 875 if (SourceLineCache[5] > QueriedFilePos) 876 SourceLineCacheEnd = SourceLineCache+5; 877 else if (SourceLineCache+10 < SourceLineCacheEnd) { 878 if (SourceLineCache[10] > QueriedFilePos) 879 SourceLineCacheEnd = SourceLineCache+10; 880 else if (SourceLineCache+20 < SourceLineCacheEnd) { 881 if (SourceLineCache[20] > QueriedFilePos) 882 SourceLineCacheEnd = SourceLineCache+20; 883 } 884 } 885 } 886 } else { 887 if (LastLineNoResult < Content->NumLines) 888 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1; 889 } 890 } 891 892 // If the spread is large, do a "radix" test as our initial guess, based on 893 // the assumption that lines average to approximately the same length. 894 // NOTE: This is currently disabled, as it does not appear to be profitable in 895 // initial measurements. 896 if (0 && SourceLineCacheEnd-SourceLineCache > 20) { 897 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1]; 898 899 // Take a stab at guessing where it is. 900 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen; 901 902 // Check for -10 and +10 lines. 903 unsigned LowerBound = std::max(int(ApproxPos-10), 0); 904 unsigned UpperBound = std::min(ApproxPos+10, FileLen); 905 906 // If the computed lower bound is less than the query location, move it in. 907 if (SourceLineCache < SourceLineCacheStart+LowerBound && 908 SourceLineCacheStart[LowerBound] < QueriedFilePos) 909 SourceLineCache = SourceLineCacheStart+LowerBound; 910 911 // If the computed upper bound is greater than the query location, move it. 912 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound && 913 SourceLineCacheStart[UpperBound] >= QueriedFilePos) 914 SourceLineCacheEnd = SourceLineCacheStart+UpperBound; 915 } 916 917 unsigned *Pos 918 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos); 919 unsigned LineNo = Pos-SourceLineCacheStart; 920 921 LastLineNoFileIDQuery = FID; 922 LastLineNoContentCache = Content; 923 LastLineNoFilePos = QueriedFilePos; 924 LastLineNoResult = LineNo; 925 return LineNo; 926 } 927 928 unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc, 929 bool *Invalid) const { 930 if (Loc.isInvalid()) return 0; 931 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc); 932 return getLineNumber(LocInfo.first, LocInfo.second); 933 } 934 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc, 935 bool *Invalid) const { 936 if (Loc.isInvalid()) return 0; 937 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); 938 return getLineNumber(LocInfo.first, LocInfo.second); 939 } 940 941 /// getFileCharacteristic - return the file characteristic of the specified 942 /// source location, indicating whether this is a normal file, a system 943 /// header, or an "implicit extern C" system header. 944 /// 945 /// This state can be modified with flags on GNU linemarker directives like: 946 /// # 4 "foo.h" 3 947 /// which changes all source locations in the current file after that to be 948 /// considered to be from a system header. 949 SrcMgr::CharacteristicKind 950 SourceManager::getFileCharacteristic(SourceLocation Loc) const { 951 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!"); 952 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc); 953 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile(); 954 955 // If there are no #line directives in this file, just return the whole-file 956 // state. 957 if (!FI.hasLineDirectives()) 958 return FI.getFileCharacteristic(); 959 960 assert(LineTable && "Can't have linetable entries without a LineTable!"); 961 // See if there is a #line directive before the location. 962 const LineEntry *Entry = 963 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second); 964 965 // If this is before the first line marker, use the file characteristic. 966 if (!Entry) 967 return FI.getFileCharacteristic(); 968 969 return Entry->FileKind; 970 } 971 972 /// Return the filename or buffer identifier of the buffer the location is in. 973 /// Note that this name does not respect #line directives. Use getPresumedLoc 974 /// for normal clients. 975 const char *SourceManager::getBufferName(SourceLocation Loc, 976 bool *Invalid) const { 977 if (Loc.isInvalid()) return "<invalid loc>"; 978 979 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier(); 980 } 981 982 983 /// getPresumedLoc - This method returns the "presumed" location of a 984 /// SourceLocation specifies. A "presumed location" can be modified by #line 985 /// or GNU line marker directives. This provides a view on the data that a 986 /// user should see in diagnostics, for example. 987 /// 988 /// Note that a presumed location is always given as the instantiation point 989 /// of an instantiation location, not at the spelling location. 990 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const { 991 if (Loc.isInvalid()) return PresumedLoc(); 992 993 // Presumed locations are always for instantiation points. 994 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc); 995 996 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile(); 997 const SrcMgr::ContentCache *C = FI.getContentCache(); 998 999 // To get the source name, first consult the FileEntry (if one exists) 1000 // before the MemBuffer as this will avoid unnecessarily paging in the 1001 // MemBuffer. 1002 const char *Filename = 1003 C->Entry ? C->Entry->getName() : C->getBuffer(Diag)->getBufferIdentifier(); 1004 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second); 1005 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second); 1006 SourceLocation IncludeLoc = FI.getIncludeLoc(); 1007 1008 // If we have #line directives in this file, update and overwrite the physical 1009 // location info if appropriate. 1010 if (FI.hasLineDirectives()) { 1011 assert(LineTable && "Can't have linetable entries without a LineTable!"); 1012 // See if there is a #line directive before this. If so, get it. 1013 if (const LineEntry *Entry = 1014 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) { 1015 // If the LineEntry indicates a filename, use it. 1016 if (Entry->FilenameID != -1) 1017 Filename = LineTable->getFilename(Entry->FilenameID); 1018 1019 // Use the line number specified by the LineEntry. This line number may 1020 // be multiple lines down from the line entry. Add the difference in 1021 // physical line numbers from the query point and the line marker to the 1022 // total. 1023 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset); 1024 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1); 1025 1026 // Note that column numbers are not molested by line markers. 1027 1028 // Handle virtual #include manipulation. 1029 if (Entry->IncludeOffset) { 1030 IncludeLoc = getLocForStartOfFile(LocInfo.first); 1031 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset); 1032 } 1033 } 1034 } 1035 1036 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc); 1037 } 1038 1039 //===----------------------------------------------------------------------===// 1040 // Other miscellaneous methods. 1041 //===----------------------------------------------------------------------===// 1042 1043 /// \brief Get the source location for the given file:line:col triplet. 1044 /// 1045 /// If the source file is included multiple times, the source location will 1046 /// be based upon the first inclusion. 1047 SourceLocation SourceManager::getLocation(const FileEntry *SourceFile, 1048 unsigned Line, unsigned Col) const { 1049 assert(SourceFile && "Null source file!"); 1050 assert(Line && Col && "Line and column should start from 1!"); 1051 1052 fileinfo_iterator FI = FileInfos.find(SourceFile); 1053 if (FI == FileInfos.end()) 1054 return SourceLocation(); 1055 ContentCache *Content = FI->second; 1056 1057 // If this is the first use of line information for this buffer, compute the 1058 /// SourceLineCache for it on demand. 1059 if (Content->SourceLineCache == 0) { 1060 bool MyInvalid = false; 1061 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid); 1062 if (MyInvalid) 1063 return SourceLocation(); 1064 } 1065 1066 // Find the first file ID that corresponds to the given file. 1067 FileID FirstFID; 1068 1069 // First, check the main file ID, since it is common to look for a 1070 // location in the main file. 1071 if (!MainFileID.isInvalid()) { 1072 const SLocEntry &MainSLoc = getSLocEntry(MainFileID); 1073 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content) 1074 FirstFID = MainFileID; 1075 } 1076 1077 if (FirstFID.isInvalid()) { 1078 // The location we're looking for isn't in the main file; look 1079 // through all of the source locations. 1080 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) { 1081 const SLocEntry &SLoc = getSLocEntry(I); 1082 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) { 1083 FirstFID = FileID::get(I); 1084 break; 1085 } 1086 } 1087 } 1088 1089 if (FirstFID.isInvalid()) 1090 return SourceLocation(); 1091 1092 if (Line > Content->NumLines) { 1093 unsigned Size = Content->getBuffer(Diag)->getBufferSize(); 1094 if (Size > 0) 1095 --Size; 1096 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size); 1097 } 1098 1099 unsigned FilePos = Content->SourceLineCache[Line - 1]; 1100 const char *Buf = Content->getBuffer(Diag)->getBufferStart() + FilePos; 1101 unsigned BufLength = Content->getBuffer(Diag)->getBufferEnd() - Buf; 1102 unsigned i = 0; 1103 1104 // Check that the given column is valid. 1105 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r') 1106 ++i; 1107 if (i < Col-1) 1108 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i); 1109 1110 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1); 1111 } 1112 1113 /// \brief Determines the order of 2 source locations in the translation unit. 1114 /// 1115 /// \returns true if LHS source location comes before RHS, false otherwise. 1116 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS, 1117 SourceLocation RHS) const { 1118 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!"); 1119 if (LHS == RHS) 1120 return false; 1121 1122 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS); 1123 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS); 1124 1125 // If the source locations are in the same file, just compare offsets. 1126 if (LOffs.first == ROffs.first) 1127 return LOffs.second < ROffs.second; 1128 1129 // If we are comparing a source location with multiple locations in the same 1130 // file, we get a big win by caching the result. 1131 1132 if (LastLFIDForBeforeTUCheck == LOffs.first && 1133 LastRFIDForBeforeTUCheck == ROffs.first) 1134 return LastResForBeforeTUCheck; 1135 1136 LastLFIDForBeforeTUCheck = LOffs.first; 1137 LastRFIDForBeforeTUCheck = ROffs.first; 1138 1139 // "Traverse" the include/instantiation stacks of both locations and try to 1140 // find a common "ancestor". 1141 // 1142 // First we traverse the stack of the right location and check each level 1143 // against the level of the left location, while collecting all levels in a 1144 // "stack map". 1145 1146 std::map<FileID, unsigned> ROffsMap; 1147 ROffsMap[ROffs.first] = ROffs.second; 1148 1149 while (1) { 1150 SourceLocation UpperLoc; 1151 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first); 1152 if (Entry.isInstantiation()) 1153 UpperLoc = Entry.getInstantiation().getInstantiationLocStart(); 1154 else 1155 UpperLoc = Entry.getFile().getIncludeLoc(); 1156 1157 if (UpperLoc.isInvalid()) 1158 break; // We reached the top. 1159 1160 ROffs = getDecomposedLoc(UpperLoc); 1161 1162 if (LOffs.first == ROffs.first) 1163 return LastResForBeforeTUCheck = LOffs.second < ROffs.second; 1164 1165 ROffsMap[ROffs.first] = ROffs.second; 1166 } 1167 1168 // We didn't find a common ancestor. Now traverse the stack of the left 1169 // location, checking against the stack map of the right location. 1170 1171 while (1) { 1172 SourceLocation UpperLoc; 1173 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first); 1174 if (Entry.isInstantiation()) 1175 UpperLoc = Entry.getInstantiation().getInstantiationLocStart(); 1176 else 1177 UpperLoc = Entry.getFile().getIncludeLoc(); 1178 1179 if (UpperLoc.isInvalid()) 1180 break; // We reached the top. 1181 1182 LOffs = getDecomposedLoc(UpperLoc); 1183 1184 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first); 1185 if (I != ROffsMap.end()) 1186 return LastResForBeforeTUCheck = LOffs.second < I->second; 1187 } 1188 1189 // There is no common ancestor, most probably because one location is in the 1190 // predefines buffer. 1191 // 1192 // FIXME: We should rearrange the external interface so this simply never 1193 // happens; it can't conceptually happen. Also see PR5662. 1194 1195 // If exactly one location is a memory buffer, assume it preceeds the other. 1196 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry; 1197 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry; 1198 if (LIsMB != RIsMB) 1199 return LastResForBeforeTUCheck = LIsMB; 1200 1201 // Otherwise, just assume FileIDs were created in order. 1202 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first); 1203 } 1204 1205 /// PrintStats - Print statistics to stderr. 1206 /// 1207 void SourceManager::PrintStats() const { 1208 llvm::errs() << "\n*** Source Manager Stats:\n"; 1209 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size() 1210 << " mem buffers mapped.\n"; 1211 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, " 1212 << NextOffset << "B of Sloc address space used.\n"; 1213 1214 unsigned NumLineNumsComputed = 0; 1215 unsigned NumFileBytesMapped = 0; 1216 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){ 1217 NumLineNumsComputed += I->second->SourceLineCache != 0; 1218 NumFileBytesMapped += I->second->getSizeBytesMapped(); 1219 } 1220 1221 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, " 1222 << NumLineNumsComputed << " files with line #'s computed.\n"; 1223 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, " 1224 << NumBinaryProbes << " binary.\n"; 1225 } 1226 1227 ExternalSLocEntrySource::~ExternalSLocEntrySource() { } 1228