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