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