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