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