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