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