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