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