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