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