clang  16.0.0git
SourceManager.h
Go to the documentation of this file.
1 //===- SourceManager.h - Track and cache source files -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Defines the SourceManager interface.
11 ///
12 /// There are three different types of locations in a %file: a spelling
13 /// location, an expansion location, and a presumed location.
14 ///
15 /// Given an example of:
16 /// \code
17 /// #define min(x, y) x < y ? x : y
18 /// \endcode
19 ///
20 /// and then later on a use of min:
21 /// \code
22 /// #line 17
23 /// return min(a, b);
24 /// \endcode
25 ///
26 /// The expansion location is the line in the source code where the macro
27 /// was expanded (the return statement), the spelling location is the
28 /// location in the source where the macro was originally defined,
29 /// and the presumed location is where the line directive states that
30 /// the line is 17, or any other line.
31 //
32 //===----------------------------------------------------------------------===//
33 
34 #ifndef LLVM_CLANG_BASIC_SOURCEMANAGER_H
35 #define LLVM_CLANG_BASIC_SOURCEMANAGER_H
36 
37 #include "clang/Basic/Diagnostic.h"
38 #include "clang/Basic/FileEntry.h"
41 #include "llvm/ADT/ArrayRef.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/DenseMap.h"
44 #include "llvm/ADT/DenseSet.h"
45 #include "llvm/ADT/IntrusiveRefCntPtr.h"
46 #include "llvm/ADT/PointerIntPair.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/ADT/StringRef.h"
49 #include "llvm/Support/Allocator.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include <cassert>
53 #include <cstddef>
54 #include <map>
55 #include <memory>
56 #include <string>
57 #include <utility>
58 #include <vector>
59 
60 namespace clang {
61 
62 class ASTReader;
63 class ASTWriter;
64 class FileManager;
65 class LineTableInfo;
66 class SourceManager;
67 
68 /// Public enums and private classes that are part of the
69 /// SourceManager implementation.
70 namespace SrcMgr {
71 
72 /// Indicates whether a file or directory holds normal user code,
73 /// system code, or system code which is implicitly 'extern "C"' in C++ mode.
74 ///
75 /// Entire directories can be tagged with this (this is maintained by
76 /// DirectoryLookup and friends) as can specific FileInfos when a \#pragma
77 /// system_header is seen or in various other cases.
78 ///
85 };
86 
87 /// Determine whether a file / directory characteristic is for system code.
88 inline bool isSystem(CharacteristicKind CK) {
89  return CK != C_User && CK != C_User_ModuleMap;
90 }
91 
92 /// Determine whether a file characteristic is for a module map.
94  return CK == C_User_ModuleMap || CK == C_System_ModuleMap;
95 }
96 
97 /// Mapping of line offsets into a source file. This does not own the storage
98 /// for the line numbers.
100 public:
101  explicit operator bool() const { return Storage; }
102  unsigned size() const {
103  assert(Storage);
104  return Storage[0];
105  }
107  assert(Storage);
108  return ArrayRef<unsigned>(Storage + 1, Storage + 1 + size());
109  }
110  const unsigned *begin() const { return getLines().begin(); }
111  const unsigned *end() const { return getLines().end(); }
112  const unsigned &operator[](int I) const { return getLines()[I]; }
113 
114  static LineOffsetMapping get(llvm::MemoryBufferRef Buffer,
115  llvm::BumpPtrAllocator &Alloc);
116 
117  LineOffsetMapping() = default;
119  llvm::BumpPtrAllocator &Alloc);
120 
121 private:
122  /// First element is the size, followed by elements at off-by-one indexes.
123  unsigned *Storage = nullptr;
124 };
125 
126 /// One instance of this struct is kept for every file loaded or used.
127 ///
128 /// This object owns the MemoryBuffer object.
129 class alignas(8) ContentCache {
130  /// The actual buffer containing the characters from the input
131  /// file.
132  mutable std::unique_ptr<llvm::MemoryBuffer> Buffer;
133 
134 public:
135  /// Reference to the file entry representing this ContentCache.
136  ///
137  /// This reference does not own the FileEntry object.
138  ///
139  /// It is possible for this to be NULL if the ContentCache encapsulates
140  /// an imaginary text buffer.
141  ///
142  /// FIXME: Make non-optional using a virtual file as needed, remove \c
143  /// Filename and use \c OrigEntry.getNameAsRequested() instead.
145 
146  /// References the file which the contents were actually loaded from.
147  ///
148  /// Can be different from 'Entry' if we overridden the contents of one file
149  /// with the contents of another file.
151 
152  /// The filename that is used to access OrigEntry.
153  ///
154  /// FIXME: Remove this once OrigEntry is a FileEntryRef with a stable name.
155  StringRef Filename;
156 
157  /// A bump pointer allocated array of offsets for each source line.
158  ///
159  /// This is lazily computed. The lines are owned by the SourceManager
160  /// BumpPointerAllocator object.
162 
163  /// Indicates whether the buffer itself was provided to override
164  /// the actual file contents.
165  ///
166  /// When true, the original entry may be a virtual file that does not
167  /// exist.
168  unsigned BufferOverridden : 1;
169 
170  /// True if this content cache was initially created for a source file
171  /// considered to be volatile (likely to change between stat and open).
172  unsigned IsFileVolatile : 1;
173 
174  /// True if this file may be transient, that is, if it might not
175  /// exist at some later point in time when this content entry is used,
176  /// after serialization and deserialization.
177  unsigned IsTransient : 1;
178 
179  mutable unsigned IsBufferInvalid : 1;
180 
182  : OrigEntry(std::nullopt), ContentsEntry(nullptr),
185 
187 
188  ContentCache(FileEntryRef Ent, const FileEntry *contentEnt)
189  : OrigEntry(Ent), ContentsEntry(contentEnt), BufferOverridden(false),
191 
192  /// The copy ctor does not allow copies where source object has either
193  /// a non-NULL Buffer or SourceLineCache. Ownership of allocated memory
194  /// is not transferred, so this is a logical error.
198  OrigEntry = RHS.OrigEntry;
200 
201  assert(!RHS.Buffer && !RHS.SourceLineCache &&
202  "Passed ContentCache object cannot own a buffer.");
203  }
204 
205  ContentCache &operator=(const ContentCache &RHS) = delete;
206 
207  /// Returns the memory buffer for the associated content.
208  ///
209  /// \param Diag Object through which diagnostics will be emitted if the
210  /// buffer cannot be retrieved.
211  ///
212  /// \param Loc If specified, is the location that invalid file diagnostics
213  /// will be emitted at.
216  SourceLocation Loc = SourceLocation()) const;
217 
218  /// Returns the size of the content encapsulated by this
219  /// ContentCache.
220  ///
221  /// This can be the size of the source file or the size of an
222  /// arbitrary scratch buffer. If the ContentCache encapsulates a source
223  /// file this size is retrieved from the file's FileEntry.
224  unsigned getSize() const;
225 
226  /// Returns the number of bytes actually mapped for this
227  /// ContentCache.
228  ///
229  /// This can be 0 if the MemBuffer was not actually expanded.
230  unsigned getSizeBytesMapped() const;
231 
232  /// Returns the kind of memory used to back the memory buffer for
233  /// this content cache. This is used for performance analysis.
234  llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const;
235 
236  /// Return the buffer, only if it has been loaded.
238  if (Buffer)
239  return Buffer->getMemBufferRef();
240  return std::nullopt;
241  }
242 
243  /// Return a StringRef to the source buffer data, only if it has already
244  /// been loaded.
246  if (Buffer)
247  return Buffer->getBuffer();
248  return std::nullopt;
249  }
250 
251  /// Set the buffer.
252  void setBuffer(std::unique_ptr<llvm::MemoryBuffer> B) {
253  IsBufferInvalid = false;
254  Buffer = std::move(B);
255  }
256 
257  /// Set the buffer to one that's not owned (or to nullptr).
258  ///
259  /// \pre Buffer cannot already be set.
261  assert(!Buffer && "Expected to be called right after construction");
262  if (B)
263  setBuffer(llvm::MemoryBuffer::getMemBuffer(*B));
264  }
265 
266  // If BufStr has an invalid BOM, returns the BOM name; otherwise, returns
267  // nullptr
268  static const char *getInvalidBOM(StringRef BufStr);
269 };
270 
271 // Assert that the \c ContentCache objects will always be 8-byte aligned so
272 // that we can pack 3 bits of integer into pointers to such objects.
273 static_assert(alignof(ContentCache) >= 8,
274  "ContentCache must be 8-byte aligned.");
275 
276 /// Information about a FileID, basically just the logical file
277 /// that it represents and include stack information.
278 ///
279 /// Each FileInfo has include stack information, indicating where it came
280 /// from. This information encodes the \#include chain that a token was
281 /// expanded from. The main include file has an invalid IncludeLoc.
282 ///
283 /// FileInfo should not grow larger than ExpansionInfo. Doing so will
284 /// cause memory to bloat in compilations with many unloaded macro
285 /// expansions, since the two data structurs are stored in a union in
286 /// SLocEntry. Extra fields should instead go in "ContentCache *", which
287 /// stores file contents and other bits on the side.
288 ///
289 class FileInfo {
290  friend class clang::SourceManager;
291  friend class clang::ASTWriter;
292  friend class clang::ASTReader;
293 
294  /// The location of the \#include that brought in this file.
295  ///
296  /// This is an invalid SLOC for the main file (top of the \#include chain).
297  SourceLocation IncludeLoc;
298 
299  /// Number of FileIDs (files and macros) that were created during
300  /// preprocessing of this \#include, including this SLocEntry.
301  ///
302  /// Zero means the preprocessor didn't provide such info for this SLocEntry.
303  unsigned NumCreatedFIDs : 31;
304 
305  /// Whether this FileInfo has any \#line directives.
306  unsigned HasLineDirectives : 1;
307 
308  /// The content cache and the characteristic of the file.
309  llvm::PointerIntPair<const ContentCache *, 3, CharacteristicKind>
310  ContentAndKind;
311 
312 public:
313  /// Return a FileInfo object.
315  CharacteristicKind FileCharacter, StringRef Filename) {
316  FileInfo X;
317  X.IncludeLoc = IL;
318  X.NumCreatedFIDs = 0;
319  X.HasLineDirectives = false;
320  X.ContentAndKind.setPointer(&Con);
321  X.ContentAndKind.setInt(FileCharacter);
322  Con.Filename = Filename;
323  return X;
324  }
325 
327  return IncludeLoc;
328  }
329 
330  const ContentCache &getContentCache() const {
331  return *ContentAndKind.getPointer();
332  }
333 
334  /// Return whether this is a system header or not.
336  return ContentAndKind.getInt();
337  }
338 
339  /// Return true if this FileID has \#line directives in it.
340  bool hasLineDirectives() const { return HasLineDirectives; }
341 
342  /// Set the flag that indicates that this FileID has
343  /// line table entries associated with it.
344  void setHasLineDirectives() { HasLineDirectives = true; }
345 
346  /// Returns the name of the file that was used when the file was loaded from
347  /// the underlying file system.
348  StringRef getName() const { return getContentCache().Filename; }
349 };
350 
351 /// Each ExpansionInfo encodes the expansion location - where
352 /// the token was ultimately expanded, and the SpellingLoc - where the actual
353 /// character data for the token came from.
355  // Really these are all SourceLocations.
356 
357  /// Where the spelling for the token can be found.
358  SourceLocation SpellingLoc;
359 
360  /// In a macro expansion, ExpansionLocStart and ExpansionLocEnd
361  /// indicate the start and end of the expansion. In object-like macros,
362  /// they will be the same. In a function-like macro expansion, the start
363  /// will be the identifier and the end will be the ')'. Finally, in
364  /// macro-argument instantiations, the end will be 'SourceLocation()', an
365  /// invalid location.
366  SourceLocation ExpansionLocStart, ExpansionLocEnd;
367 
368  /// Whether the expansion range is a token range.
369  bool ExpansionIsTokenRange;
370 
371 public:
373  return SpellingLoc.isInvalid() ? getExpansionLocStart() : SpellingLoc;
374  }
375 
377  return ExpansionLocStart;
378  }
379 
381  return ExpansionLocEnd.isInvalid() ? getExpansionLocStart()
382  : ExpansionLocEnd;
383  }
384 
385  bool isExpansionTokenRange() const { return ExpansionIsTokenRange; }
386 
388  return CharSourceRange(
391  }
392 
393  bool isMacroArgExpansion() const {
394  // Note that this needs to return false for default constructed objects.
395  return getExpansionLocStart().isValid() && ExpansionLocEnd.isInvalid();
396  }
397 
398  bool isMacroBodyExpansion() const {
399  return getExpansionLocStart().isValid() && ExpansionLocEnd.isValid();
400  }
401 
403  return getExpansionLocStart().isValid() &&
405  }
406 
407  /// Return a ExpansionInfo for an expansion.
408  ///
409  /// Start and End specify the expansion range (where the macro is
410  /// expanded), and SpellingLoc specifies the spelling location (where
411  /// the characters from the token come from). All three can refer to
412  /// normal File SLocs or expansion locations.
415  bool ExpansionIsTokenRange = true) {
417  X.SpellingLoc = SpellingLoc;
418  X.ExpansionLocStart = Start;
419  X.ExpansionLocEnd = End;
420  X.ExpansionIsTokenRange = ExpansionIsTokenRange;
421  return X;
422  }
423 
424  /// Return a special ExpansionInfo for the expansion of
425  /// a macro argument into a function-like macro's body.
426  ///
427  /// ExpansionLoc specifies the expansion location (where the macro is
428  /// expanded). This doesn't need to be a range because a macro is always
429  /// expanded at a macro parameter reference, and macro parameters are
430  /// always exactly one token. SpellingLoc specifies the spelling location
431  /// (where the characters from the token come from). ExpansionLoc and
432  /// SpellingLoc can both refer to normal File SLocs or expansion locations.
433  ///
434  /// Given the code:
435  /// \code
436  /// #define F(x) f(x)
437  /// F(42);
438  /// \endcode
439  ///
440  /// When expanding '\c F(42)', the '\c x' would call this with an
441  /// SpellingLoc pointing at '\c 42' and an ExpansionLoc pointing at its
442  /// location in the definition of '\c F'.
444  SourceLocation ExpansionLoc) {
445  // We store an intentionally invalid source location for the end of the
446  // expansion range to mark that this is a macro argument location rather
447  // than a normal one.
448  return create(SpellingLoc, ExpansionLoc, SourceLocation());
449  }
450 
451  /// Return a special ExpansionInfo representing a token that ends
452  /// prematurely. This is used to model a '>>' token that has been split
453  /// into '>' tokens and similar cases. Unlike for the other forms of
454  /// expansion, the expansion range in this case is a character range, not
455  /// a token range.
457  SourceLocation Start,
459  return create(SpellingLoc, Start, End, false);
460  }
461 };
462 
463 // Assert that the \c FileInfo objects are no bigger than \c ExpansionInfo
464 // objects. This controls the size of \c SLocEntry, of which we have one for
465 // each macro expansion. The number of (unloaded) macro expansions can be
466 // very large. Any other fields needed in FileInfo should go in ContentCache.
467 static_assert(sizeof(FileInfo) <= sizeof(ExpansionInfo),
468  "FileInfo must be no larger than ExpansionInfo.");
469 
470 /// This is a discriminated union of FileInfo and ExpansionInfo.
471 ///
472 /// SourceManager keeps an array of these objects, and they are uniquely
473 /// identified by the FileID datatype.
474 class SLocEntry {
475  static constexpr int OffsetBits = 8 * sizeof(SourceLocation::UIntTy) - 1;
476  SourceLocation::UIntTy Offset : OffsetBits;
477  SourceLocation::UIntTy IsExpansion : 1;
478  union {
481  };
482 
483 public:
484  SLocEntry() : Offset(), IsExpansion(), File() {}
485 
486  SourceLocation::UIntTy getOffset() const { return Offset; }
487 
488  bool isExpansion() const { return IsExpansion; }
489  bool isFile() const { return !isExpansion(); }
490 
491  const FileInfo &getFile() const {
492  assert(isFile() && "Not a file SLocEntry!");
493  return File;
494  }
495 
496  const ExpansionInfo &getExpansion() const {
497  assert(isExpansion() && "Not a macro expansion SLocEntry!");
498  return Expansion;
499  }
500 
501  static SLocEntry get(SourceLocation::UIntTy Offset, const FileInfo &FI) {
502  assert(!(Offset & (1ULL << OffsetBits)) && "Offset is too large");
503  SLocEntry E;
504  E.Offset = Offset;
505  E.IsExpansion = false;
506  E.File = FI;
507  return E;
508  }
509 
511  const ExpansionInfo &Expansion) {
512  assert(!(Offset & (1ULL << OffsetBits)) && "Offset is too large");
513  SLocEntry E;
514  E.Offset = Offset;
515  E.IsExpansion = true;
517  return E;
518  }
519 };
520 
521 } // namespace SrcMgr
522 
523 /// External source of source location entries.
525 public:
526  virtual ~ExternalSLocEntrySource();
527 
528  /// Read the source location entry with index ID, which will always be
529  /// less than -1.
530  ///
531  /// \returns true if an error occurred that prevented the source-location
532  /// entry from being loaded.
533  virtual bool ReadSLocEntry(int ID) = 0;
534 
535  /// Retrieve the module import location and name for the given ID, if
536  /// in fact it was loaded from a module (rather than, say, a precompiled
537  /// header).
538  virtual std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) = 0;
539 };
540 
541 /// Holds the cache used by isBeforeInTranslationUnit.
542 ///
543 /// The cache structure is complex enough to be worth breaking out of
544 /// SourceManager.
546  /// The FileID's of the cached query.
547  ///
548  /// If these match up with a subsequent query, the result can be reused.
549  FileID LQueryFID, RQueryFID;
550 
551  /// The relative order of FileIDs that the CommonFID *immediately* includes.
552  ///
553  /// This is used to compare macro expansion locations.
554  bool LChildBeforeRChild;
555 
556  /// The file found in common between the two \#include traces, i.e.,
557  /// the nearest common ancestor of the \#include tree.
558  FileID CommonFID;
559 
560  /// The offset of the previous query in CommonFID.
561  ///
562  /// Usually, this represents the location of the \#include for QueryFID, but
563  /// if LQueryFID is a parent of RQueryFID (or vice versa) then these can be a
564  /// random token in the parent.
565  unsigned LCommonOffset, RCommonOffset;
566 
567 public:
568  InBeforeInTUCacheEntry() = default;
569  InBeforeInTUCacheEntry(FileID L, FileID R) : LQueryFID(L), RQueryFID(R) {
570  assert(L != R);
571  }
572 
573  /// Return true if the currently cached values match up with
574  /// the specified LHS/RHS query.
575  ///
576  /// If not, we can't use the cache.
577  bool isCacheValid() const {
578  return CommonFID.isValid();
579  }
580 
581  /// If the cache is valid, compute the result given the
582  /// specified offsets in the LHS/RHS FileID's.
583  bool getCachedResult(unsigned LOffset, unsigned ROffset) const {
584  // If one of the query files is the common file, use the offset. Otherwise,
585  // use the #include loc in the common file.
586  if (LQueryFID != CommonFID) LOffset = LCommonOffset;
587  if (RQueryFID != CommonFID) ROffset = RCommonOffset;
588 
589  // It is common for multiple macro expansions to be "included" from the same
590  // location (expansion location), in which case use the order of the FileIDs
591  // to determine which came first. This will also take care the case where
592  // one of the locations points at the inclusion/expansion point of the other
593  // in which case its FileID will come before the other.
594  if (LOffset == ROffset)
595  return LChildBeforeRChild;
596 
597  return LOffset < ROffset;
598  }
599 
600  /// Set up a new query.
601  /// If it matches the old query, we can keep the cached answer.
602  void setQueryFIDs(FileID LHS, FileID RHS) {
603  assert(LHS != RHS);
604  if (LQueryFID != LHS || RQueryFID != RHS) {
605  LQueryFID = LHS;
606  RQueryFID = RHS;
607  CommonFID = FileID();
608  }
609  }
610 
611  void setCommonLoc(FileID commonFID, unsigned lCommonOffset,
612  unsigned rCommonOffset, bool LParentBeforeRParent) {
613  CommonFID = commonFID;
614  LCommonOffset = lCommonOffset;
615  RCommonOffset = rCommonOffset;
616  LChildBeforeRChild = LParentBeforeRParent;
617  }
618 };
619 
620 /// The stack used when building modules on demand, which is used
621 /// to provide a link between the source managers of the different compiler
622 /// instances.
624 
625 /// This class handles loading and caching of source files into memory.
626 ///
627 /// This object owns the MemoryBuffer objects for all of the loaded
628 /// files and assigns unique FileID's for each unique \#include chain.
629 ///
630 /// The SourceManager can be queried for information about SourceLocation
631 /// objects, turning them into either spelling or expansion locations. Spelling
632 /// locations represent where the bytes corresponding to a token came from and
633 /// expansion locations represent where the location is in the user's view. In
634 /// the case of a macro expansion, for example, the spelling location indicates
635 /// where the expanded token came from and the expansion location specifies
636 /// where it was expanded.
637 class SourceManager : public RefCountedBase<SourceManager> {
638  /// DiagnosticsEngine object.
639  DiagnosticsEngine &Diag;
640 
641  FileManager &FileMgr;
642 
643  mutable llvm::BumpPtrAllocator ContentCacheAlloc;
644 
645  /// Memoized information about all of the files tracked by this
646  /// SourceManager.
647  ///
648  /// This map allows us to merge ContentCache entries based
649  /// on their FileEntry*. All ContentCache objects will thus have unique,
650  /// non-null, FileEntry pointers.
651  llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*> FileInfos;
652 
653  /// True if the ContentCache for files that are overridden by other
654  /// files, should report the original file name. Defaults to true.
655  bool OverridenFilesKeepOriginalName = true;
656 
657  /// True if non-system source files should be treated as volatile
658  /// (likely to change while trying to use them). Defaults to false.
659  bool UserFilesAreVolatile;
660 
661  /// True if all files read during this compilation should be treated
662  /// as transient (may not be present in later compilations using a module
663  /// file created from this compilation). Defaults to false.
664  bool FilesAreTransient = false;
665 
666  struct OverriddenFilesInfoTy {
667  /// Files that have been overridden with the contents from another
668  /// file.
669  llvm::DenseMap<const FileEntry *, FileEntryRef> OverriddenFiles;
670 
671  /// Files that were overridden with a memory buffer.
672  llvm::DenseSet<const FileEntry *> OverriddenFilesWithBuffer;
673  };
674 
675  /// Lazily create the object keeping overridden files info, since
676  /// it is uncommonly used.
677  std::unique_ptr<OverriddenFilesInfoTy> OverriddenFilesInfo;
678 
679  OverriddenFilesInfoTy &getOverriddenFilesInfo() {
680  if (!OverriddenFilesInfo)
681  OverriddenFilesInfo.reset(new OverriddenFilesInfoTy);
682  return *OverriddenFilesInfo;
683  }
684 
685  /// Information about various memory buffers that we have read in.
686  ///
687  /// All FileEntry* within the stored ContentCache objects are NULL,
688  /// as they do not refer to a file.
689  std::vector<SrcMgr::ContentCache*> MemBufferInfos;
690 
691  /// The table of SLocEntries that are local to this module.
692  ///
693  /// Positive FileIDs are indexes into this table. Entry 0 indicates an invalid
694  /// expansion.
695  SmallVector<SrcMgr::SLocEntry, 0> LocalSLocEntryTable;
696 
697  /// The table of SLocEntries that are loaded from other modules.
698  ///
699  /// Negative FileIDs are indexes into this table. To get from ID to an index,
700  /// use (-ID - 2).
701  SmallVector<SrcMgr::SLocEntry, 0> LoadedSLocEntryTable;
702 
703  /// The starting offset of the next local SLocEntry.
704  ///
705  /// This is LocalSLocEntryTable.back().Offset + the size of that entry.
706  SourceLocation::UIntTy NextLocalOffset;
707 
708  /// The starting offset of the latest batch of loaded SLocEntries.
709  ///
710  /// This is LoadedSLocEntryTable.back().Offset, except that that entry might
711  /// not have been loaded, so that value would be unknown.
712  SourceLocation::UIntTy CurrentLoadedOffset;
713 
714  /// The highest possible offset is 2^31-1 (2^63-1 for 64-bit source
715  /// locations), so CurrentLoadedOffset starts at 2^31 (2^63 resp.).
716  static const SourceLocation::UIntTy MaxLoadedOffset =
717  1ULL << (8 * sizeof(SourceLocation::UIntTy) - 1);
718 
719  /// A bitmap that indicates whether the entries of LoadedSLocEntryTable
720  /// have already been loaded from the external source.
721  ///
722  /// Same indexing as LoadedSLocEntryTable.
723  llvm::BitVector SLocEntryLoaded;
724 
725  /// An external source for source location entries.
726  ExternalSLocEntrySource *ExternalSLocEntries = nullptr;
727 
728  /// A one-entry cache to speed up getFileID.
729  ///
730  /// LastFileIDLookup records the last FileID looked up or created, because it
731  /// is very common to look up many tokens from the same file.
732  mutable FileID LastFileIDLookup;
733 
734  /// Holds information for \#line directives.
735  ///
736  /// This is referenced by indices from SLocEntryTable.
737  std::unique_ptr<LineTableInfo> LineTable;
738 
739  /// These ivars serve as a cache used in the getLineNumber
740  /// method which is used to speedup getLineNumber calls to nearby locations.
741  mutable FileID LastLineNoFileIDQuery;
742  mutable const SrcMgr::ContentCache *LastLineNoContentCache;
743  mutable unsigned LastLineNoFilePos;
744  mutable unsigned LastLineNoResult;
745 
746  /// The file ID for the main source file of the translation unit.
747  FileID MainFileID;
748 
749  /// The file ID for the precompiled preamble there is one.
750  FileID PreambleFileID;
751 
752  // Statistics for -print-stats.
753  mutable unsigned NumLinearScans = 0;
754  mutable unsigned NumBinaryProbes = 0;
755 
756  /// Associates a FileID with its "included/expanded in" decomposed
757  /// location.
758  ///
759  /// Used to cache results from and speed-up \c getDecomposedIncludedLoc
760  /// function.
761  mutable llvm::DenseMap<FileID, std::pair<FileID, unsigned>> IncludedLocMap;
762 
763  /// The key value into the IsBeforeInTUCache table.
764  using IsBeforeInTUCacheKey = std::pair<FileID, FileID>;
765 
766  /// The IsBeforeInTranslationUnitCache is a mapping from FileID pairs
767  /// to cache results.
768  using InBeforeInTUCache =
769  llvm::DenseMap<IsBeforeInTUCacheKey, InBeforeInTUCacheEntry>;
770 
771  /// Cache results for the isBeforeInTranslationUnit method.
772  mutable InBeforeInTUCache IBTUCache;
773  mutable InBeforeInTUCacheEntry IBTUCacheOverflow;
774 
775  /// Return the cache entry for comparing the given file IDs
776  /// for isBeforeInTranslationUnit.
777  InBeforeInTUCacheEntry &getInBeforeInTUCache(FileID LFID, FileID RFID) const;
778 
779  // Cache for the "fake" buffer used for error-recovery purposes.
780  mutable std::unique_ptr<llvm::MemoryBuffer> FakeBufferForRecovery;
781 
782  mutable std::unique_ptr<SrcMgr::ContentCache> FakeContentCacheForRecovery;
783 
784  mutable std::unique_ptr<SrcMgr::SLocEntry> FakeSLocEntryForRecovery;
785 
786  /// Lazily computed map of macro argument chunks to their expanded
787  /// source location.
788  using MacroArgsMap = std::map<unsigned, SourceLocation>;
789 
790  mutable llvm::DenseMap<FileID, std::unique_ptr<MacroArgsMap>>
791  MacroArgsCacheMap;
792 
793  /// The stack of modules being built, which is used to detect
794  /// cycles in the module dependency graph as modules are being built, as
795  /// well as to describe why we're rebuilding a particular module.
796  ///
797  /// There is no way to set this value from the command line. If we ever need
798  /// to do so (e.g., if on-demand module construction moves out-of-process),
799  /// we can add a cc1-level option to do so.
800  SmallVector<std::pair<std::string, FullSourceLoc>, 2> StoredModuleBuildStack;
801 
802 public:
804  bool UserFilesAreVolatile = false);
805  explicit SourceManager(const SourceManager &) = delete;
806  SourceManager &operator=(const SourceManager &) = delete;
807  ~SourceManager();
808 
809  void clearIDTables();
810 
811  /// Initialize this source manager suitably to replay the compilation
812  /// described by \p Old. Requires that \p Old outlive \p *this.
813  void initializeForReplay(const SourceManager &Old);
814 
815  DiagnosticsEngine &getDiagnostics() const { return Diag; }
816 
817  FileManager &getFileManager() const { return FileMgr; }
818 
819  /// Set true if the SourceManager should report the original file name
820  /// for contents of files that were overridden by other files. Defaults to
821  /// true.
823  OverridenFilesKeepOriginalName = value;
824  }
825 
826  /// True if non-system source files should be treated as volatile
827  /// (likely to change while trying to use them).
828  bool userFilesAreVolatile() const { return UserFilesAreVolatile; }
829 
830  /// Retrieve the module build stack.
832  return StoredModuleBuildStack;
833  }
834 
835  /// Set the module build stack.
837  StoredModuleBuildStack.clear();
838  StoredModuleBuildStack.append(stack.begin(), stack.end());
839  }
840 
841  /// Push an entry to the module build stack.
842  void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc) {
843  StoredModuleBuildStack.push_back(std::make_pair(moduleName.str(),importLoc));
844  }
845 
846  //===--------------------------------------------------------------------===//
847  // MainFileID creation and querying methods.
848  //===--------------------------------------------------------------------===//
849 
850  /// Returns the FileID of the main source file.
851  FileID getMainFileID() const { return MainFileID; }
852 
853  /// Set the file ID for the main source file.
854  void setMainFileID(FileID FID) {
855  MainFileID = FID;
856  }
857 
858  /// Returns true when the given FileEntry corresponds to the main file.
859  ///
860  /// The main file should be set prior to calling this function.
861  bool isMainFile(const FileEntry &SourceFile);
862 
863  /// Set the file ID for the precompiled preamble.
864  void setPreambleFileID(FileID Preamble) {
865  assert(PreambleFileID.isInvalid() && "PreambleFileID already set!");
866  PreambleFileID = Preamble;
867  }
868 
869  /// Get the file ID for the precompiled preamble if there is one.
870  FileID getPreambleFileID() const { return PreambleFileID; }
871 
872  //===--------------------------------------------------------------------===//
873  // Methods to create new FileID's and macro expansions.
874  //===--------------------------------------------------------------------===//
875 
876  /// Create a new FileID that represents the specified file
877  /// being \#included from the specified IncludePosition.
878  ///
879  /// This translates NULL into standard input.
880  FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos,
881  SrcMgr::CharacteristicKind FileCharacter,
882  int LoadedID = 0,
883  SourceLocation::UIntTy LoadedOffset = 0);
884 
885  FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos,
886  SrcMgr::CharacteristicKind FileCharacter,
887  int LoadedID = 0,
888  SourceLocation::UIntTy LoadedOffset = 0);
889 
890  /// Create a new FileID that represents the specified memory buffer.
891  ///
892  /// This does no caching of the buffer and takes ownership of the
893  /// MemoryBuffer, so only pass a MemoryBuffer to this once.
894  FileID createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
896  int LoadedID = 0, SourceLocation::UIntTy LoadedOffset = 0,
897  SourceLocation IncludeLoc = SourceLocation());
898 
899  /// Create a new FileID that represents the specified memory buffer.
900  ///
901  /// This does not take ownership of the MemoryBuffer. The memory buffer must
902  /// outlive the SourceManager.
903  FileID createFileID(const llvm::MemoryBufferRef &Buffer,
905  int LoadedID = 0, SourceLocation::UIntTy LoadedOffset = 0,
906  SourceLocation IncludeLoc = SourceLocation());
907 
908  /// Get the FileID for \p SourceFile if it exists. Otherwise, create a
909  /// new FileID for the \p SourceFile.
910  FileID getOrCreateFileID(const FileEntry *SourceFile,
911  SrcMgr::CharacteristicKind FileCharacter);
912 
913  /// Creates an expansion SLocEntry for the substitution of an argument into a
914  /// function-like macro's body. Returns the start of the expansion.
915  ///
916  /// The macro argument was written at \p SpellingLoc with length \p Length.
917  /// \p ExpansionLoc is the parameter name in the (expanded) macro body.
919  SourceLocation ExpansionLoc,
920  unsigned Length);
921 
922  /// Creates an expansion SLocEntry for a macro use. Returns its start.
923  ///
924  /// The macro body begins at \p SpellingLoc with length \p Length.
925  /// The macro use spans [ExpansionLocStart, ExpansionLocEnd].
927  SourceLocation ExpansionLocStart,
928  SourceLocation ExpansionLocEnd,
929  unsigned Length,
930  bool ExpansionIsTokenRange = true,
931  int LoadedID = 0,
932  SourceLocation::UIntTy LoadedOffset = 0);
933 
934  /// Return a new SourceLocation that encodes that the token starting
935  /// at \p TokenStart ends prematurely at \p TokenEnd.
937  SourceLocation TokenStart,
938  SourceLocation TokenEnd);
939 
940  /// Retrieve the memory buffer associated with the given file.
941  ///
942  /// Returns std::nullopt if the buffer is not valid.
945 
946  /// Retrieve the memory buffer associated with the given file.
947  ///
948  /// Returns a fake buffer if there isn't a real one.
949  llvm::MemoryBufferRef getMemoryBufferForFileOrFake(const FileEntry *File) {
950  if (auto B = getMemoryBufferForFileOrNone(File))
951  return *B;
952  return getFakeBufferForRecovery();
953  }
954 
955  /// Override the contents of the given source file by providing an
956  /// already-allocated buffer.
957  ///
958  /// \param SourceFile the source file whose contents will be overridden.
959  ///
960  /// \param Buffer the memory buffer whose contents will be used as the
961  /// data in the given source file.
962  void overrideFileContents(const FileEntry *SourceFile,
963  const llvm::MemoryBufferRef &Buffer) {
964  overrideFileContents(SourceFile, llvm::MemoryBuffer::getMemBuffer(Buffer));
965  }
966 
967  /// Override the contents of the given source file by providing an
968  /// already-allocated buffer.
969  ///
970  /// \param SourceFile the source file whose contents will be overridden.
971  ///
972  /// \param Buffer the memory buffer whose contents will be used as the
973  /// data in the given source file.
974  void overrideFileContents(const FileEntry *SourceFile,
975  std::unique_ptr<llvm::MemoryBuffer> Buffer);
977  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
978  overrideFileContents(&SourceFile.getFileEntry(), std::move(Buffer));
979  }
980 
981  /// Override the given source file with another one.
982  ///
983  /// \param SourceFile the source file which will be overridden.
984  ///
985  /// \param NewFile the file whose contents will be used as the
986  /// data instead of the contents of the given source file.
987  void overrideFileContents(const FileEntry *SourceFile, FileEntryRef NewFile);
988 
989  /// Returns true if the file contents have been overridden.
990  bool isFileOverridden(const FileEntry *File) const {
991  if (OverriddenFilesInfo) {
992  if (OverriddenFilesInfo->OverriddenFilesWithBuffer.count(File))
993  return true;
994  if (OverriddenFilesInfo->OverriddenFiles.find(File) !=
995  OverriddenFilesInfo->OverriddenFiles.end())
996  return true;
997  }
998  return false;
999  }
1000 
1001  /// Bypass the overridden contents of a file. This creates a new FileEntry
1002  /// and initializes the content cache for it. Returns std::nullopt if there
1003  /// is no such file in the filesystem.
1004  ///
1005  /// This should be called before parsing has begun.
1007 
1008  /// Specify that a file is transient.
1009  void setFileIsTransient(const FileEntry *SourceFile);
1010 
1011  /// Specify that all files that are read during this compilation are
1012  /// transient.
1013  void setAllFilesAreTransient(bool Transient) {
1014  FilesAreTransient = Transient;
1015  }
1016 
1017  //===--------------------------------------------------------------------===//
1018  // FileID manipulation methods.
1019  //===--------------------------------------------------------------------===//
1020 
1021  /// Return the buffer for the specified FileID.
1022  ///
1023  /// If there is an error opening this buffer the first time, return
1024  /// std::nullopt.
1027  if (auto *Entry = getSLocEntryForFile(FID))
1028  return Entry->getFile().getContentCache().getBufferOrNone(
1029  Diag, getFileManager(), Loc);
1030  return std::nullopt;
1031  }
1032 
1033  /// Return the buffer for the specified FileID.
1034  ///
1035  /// If there is an error opening this buffer the first time, this
1036  /// manufactures a temporary buffer and returns it.
1037  llvm::MemoryBufferRef
1039  if (auto B = getBufferOrNone(FID, Loc))
1040  return *B;
1041  return getFakeBufferForRecovery();
1042  }
1043 
1044  /// Returns the FileEntry record for the provided FileID.
1045  const FileEntry *getFileEntryForID(FileID FID) const {
1046  if (auto *Entry = getSLocEntryForFile(FID))
1047  return Entry->getFile().getContentCache().OrigEntry;
1048  return nullptr;
1049  }
1050 
1051  /// Returns the FileEntryRef for the provided FileID.
1053  if (auto *Entry = getSLocEntryForFile(FID))
1054  return Entry->getFile().getContentCache().OrigEntry;
1055  return std::nullopt;
1056  }
1057 
1058  /// Returns the filename for the provided FileID, unless it's a built-in
1059  /// buffer that's not represented by a filename.
1060  ///
1061  /// Returns std::nullopt for non-files and built-in files.
1063 
1064  /// Returns the FileEntry record for the provided SLocEntry.
1066  {
1067  return sloc.getFile().getContentCache().OrigEntry;
1068  }
1069 
1070  /// Return a StringRef to the source buffer data for the
1071  /// specified FileID.
1072  ///
1073  /// \param FID The file ID whose contents will be returned.
1074  /// \param Invalid If non-NULL, will be set true if an error occurred.
1075  StringRef getBufferData(FileID FID, bool *Invalid = nullptr) const;
1076 
1077  /// Return a StringRef to the source buffer data for the
1078  /// specified FileID, returning None if invalid.
1079  ///
1080  /// \param FID The file ID whose contents will be returned.
1082 
1083  /// Return a StringRef to the source buffer data for the
1084  /// specified FileID, returning None if it's not yet loaded.
1085  ///
1086  /// \param FID The file ID whose contents will be returned.
1088 
1089  /// Get the number of FileIDs (files and macros) that were created
1090  /// during preprocessing of \p FID, including it.
1091  unsigned getNumCreatedFIDsForFileID(FileID FID) const {
1092  if (auto *Entry = getSLocEntryForFile(FID))
1093  return Entry->getFile().NumCreatedFIDs;
1094  return 0;
1095  }
1096 
1097  /// Set the number of FileIDs (files and macros) that were created
1098  /// during preprocessing of \p FID, including it.
1099  void setNumCreatedFIDsForFileID(FileID FID, unsigned NumFIDs,
1100  bool Force = false) const {
1101  auto *Entry = getSLocEntryForFile(FID);
1102  if (!Entry)
1103  return;
1104  assert((Force || Entry->getFile().NumCreatedFIDs == 0) && "Already set!");
1105  const_cast<SrcMgr::FileInfo &>(Entry->getFile()).NumCreatedFIDs = NumFIDs;
1106  }
1107 
1108  //===--------------------------------------------------------------------===//
1109  // SourceLocation manipulation methods.
1110  //===--------------------------------------------------------------------===//
1111 
1112  /// Return the FileID for a SourceLocation.
1113  ///
1114  /// This is a very hot method that is used for all SourceManager queries
1115  /// that start with a SourceLocation object. It is responsible for finding
1116  /// the entry in SLocEntryTable which contains the specified location.
1117  ///
1118  FileID getFileID(SourceLocation SpellingLoc) const {
1119  return getFileID(SpellingLoc.getOffset());
1120  }
1121 
1122  /// Return the filename of the file containing a SourceLocation.
1123  StringRef getFilename(SourceLocation SpellingLoc) const;
1124 
1125  /// Return the source location corresponding to the first byte of
1126  /// the specified file.
1128  if (auto *Entry = getSLocEntryForFile(FID))
1129  return SourceLocation::getFileLoc(Entry->getOffset());
1130  return SourceLocation();
1131  }
1132 
1133  /// Return the source location corresponding to the last byte of the
1134  /// specified file.
1136  if (auto *Entry = getSLocEntryForFile(FID))
1137  return SourceLocation::getFileLoc(Entry->getOffset() +
1138  getFileIDSize(FID));
1139  return SourceLocation();
1140  }
1141 
1142  /// Returns the include location if \p FID is a \#include'd file
1143  /// otherwise it returns an invalid location.
1145  if (auto *Entry = getSLocEntryForFile(FID))
1146  return Entry->getFile().getIncludeLoc();
1147  return SourceLocation();
1148  }
1149 
1150  // Returns the import location if the given source location is
1151  // located within a module, or an invalid location if the source location
1152  // is within the current translation unit.
1153  std::pair<SourceLocation, StringRef>
1155  FileID FID = getFileID(Loc);
1156 
1157  // Positive file IDs are in the current translation unit, and -1 is a
1158  // placeholder.
1159  if (FID.ID >= -1)
1160  return std::make_pair(SourceLocation(), "");
1161 
1162  return ExternalSLocEntries->getModuleImportLoc(FID.ID);
1163  }
1164 
1165  /// Given a SourceLocation object \p Loc, return the expansion
1166  /// location referenced by the ID.
1168  // Handle the non-mapped case inline, defer to out of line code to handle
1169  // expansions.
1170  if (Loc.isFileID()) return Loc;
1171  return getExpansionLocSlowCase(Loc);
1172  }
1173 
1174  /// Given \p Loc, if it is a macro location return the expansion
1175  /// location or the spelling location, depending on if it comes from a
1176  /// macro argument or not.
1178  if (Loc.isFileID()) return Loc;
1179  return getFileLocSlowCase(Loc);
1180  }
1181 
1182  /// Return the start/end of the expansion information for an
1183  /// expansion location.
1184  ///
1185  /// \pre \p Loc is required to be an expansion location.
1187 
1188  /// Given a SourceLocation object, return the range of
1189  /// tokens covered by the expansion in the ultimate file.
1191 
1192  /// Given a SourceRange object, return the range of
1193  /// tokens or characters covered by the expansion in the ultimate file.
1195  SourceLocation Begin = getExpansionRange(Range.getBegin()).getBegin();
1196  CharSourceRange End = getExpansionRange(Range.getEnd());
1197  return CharSourceRange(SourceRange(Begin, End.getEnd()),
1198  End.isTokenRange());
1199  }
1200 
1201  /// Given a CharSourceRange object, return the range of
1202  /// tokens or characters covered by the expansion in the ultimate file.
1204  CharSourceRange Expansion = getExpansionRange(Range.getAsRange());
1205  if (Expansion.getEnd() == Range.getEnd())
1206  Expansion.setTokenRange(Range.isTokenRange());
1207  return Expansion;
1208  }
1209 
1210  /// Given a SourceLocation object, return the spelling
1211  /// location referenced by the ID.
1212  ///
1213  /// This is the place where the characters that make up the lexed token
1214  /// can be found.
1216  // Handle the non-mapped case inline, defer to out of line code to handle
1217  // expansions.
1218  if (Loc.isFileID()) return Loc;
1219  return getSpellingLocSlowCase(Loc);
1220  }
1221 
1222  /// Given a SourceLocation object, return the spelling location
1223  /// referenced by the ID.
1224  ///
1225  /// This is the first level down towards the place where the characters
1226  /// that make up the lexed token can be found. This should not generally
1227  /// be used by clients.
1229 
1230  /// Form a SourceLocation from a FileID and Offset pair.
1232  auto *Entry = getSLocEntryOrNull(FID);
1233  if (!Entry)
1234  return SourceLocation();
1235 
1236  SourceLocation::UIntTy GlobalOffset = Entry->getOffset() + Offset;
1237  return Entry->isFile() ? SourceLocation::getFileLoc(GlobalOffset)
1238  : SourceLocation::getMacroLoc(GlobalOffset);
1239  }
1240 
1241  /// Decompose the specified location into a raw FileID + Offset pair.
1242  ///
1243  /// The first element is the FileID, the second is the offset from the
1244  /// start of the buffer of the location.
1245  std::pair<FileID, unsigned> getDecomposedLoc(SourceLocation Loc) const {
1246  FileID FID = getFileID(Loc);
1247  auto *Entry = getSLocEntryOrNull(FID);
1248  if (!Entry)
1249  return std::make_pair(FileID(), 0);
1250  return std::make_pair(FID, Loc.getOffset() - Entry->getOffset());
1251  }
1252 
1253  /// Decompose the specified location into a raw FileID + Offset pair.
1254  ///
1255  /// If the location is an expansion record, walk through it until we find
1256  /// the final location expanded.
1257  std::pair<FileID, unsigned>
1259  FileID FID = getFileID(Loc);
1260  auto *E = getSLocEntryOrNull(FID);
1261  if (!E)
1262  return std::make_pair(FileID(), 0);
1263 
1264  unsigned Offset = Loc.getOffset()-E->getOffset();
1265  if (Loc.isFileID())
1266  return std::make_pair(FID, Offset);
1267 
1268  return getDecomposedExpansionLocSlowCase(E);
1269  }
1270 
1271  /// Decompose the specified location into a raw FileID + Offset pair.
1272  ///
1273  /// If the location is an expansion record, walk through it until we find
1274  /// its spelling record.
1275  std::pair<FileID, unsigned>
1277  FileID FID = getFileID(Loc);
1278  auto *E = getSLocEntryOrNull(FID);
1279  if (!E)
1280  return std::make_pair(FileID(), 0);
1281 
1282  unsigned Offset = Loc.getOffset()-E->getOffset();
1283  if (Loc.isFileID())
1284  return std::make_pair(FID, Offset);
1285  return getDecomposedSpellingLocSlowCase(E, Offset);
1286  }
1287 
1288  /// Returns the "included/expanded in" decomposed location of the given
1289  /// FileID.
1290  std::pair<FileID, unsigned> getDecomposedIncludedLoc(FileID FID) const;
1291 
1292  /// Returns the offset from the start of the file that the
1293  /// specified SourceLocation represents.
1294  ///
1295  /// This is not very meaningful for a macro ID.
1296  unsigned getFileOffset(SourceLocation SpellingLoc) const {
1297  return getDecomposedLoc(SpellingLoc).second;
1298  }
1299 
1300  /// Tests whether the given source location represents a macro
1301  /// argument's expansion into the function-like macro definition.
1302  ///
1303  /// \param StartLoc If non-null and function returns true, it is set to the
1304  /// start location of the macro argument expansion.
1305  ///
1306  /// Such source locations only appear inside of the expansion
1307  /// locations representing where a particular function-like macro was
1308  /// expanded.
1310  SourceLocation *StartLoc = nullptr) const;
1311 
1312  /// Tests whether the given source location represents the expansion of
1313  /// a macro body.
1314  ///
1315  /// This is equivalent to testing whether the location is part of a macro
1316  /// expansion but not the expansion of an argument to a function-like macro.
1317  bool isMacroBodyExpansion(SourceLocation Loc) const;
1318 
1319  /// Returns true if the given MacroID location points at the beginning
1320  /// of the immediate macro expansion.
1321  ///
1322  /// \param MacroBegin If non-null and function returns true, it is set to the
1323  /// begin location of the immediate macro expansion.
1325  SourceLocation *MacroBegin = nullptr) const;
1326 
1327  /// Returns true if the given MacroID location points at the character
1328  /// end of the immediate macro expansion.
1329  ///
1330  /// \param MacroEnd If non-null and function returns true, it is set to the
1331  /// character end location of the immediate macro expansion.
1332  bool
1334  SourceLocation *MacroEnd = nullptr) const;
1335 
1336  /// Returns true if \p Loc is inside the [\p Start, +\p Length)
1337  /// chunk of the source location address space.
1338  ///
1339  /// If it's true and \p RelativeOffset is non-null, it will be set to the
1340  /// relative offset of \p Loc inside the chunk.
1341  bool
1342  isInSLocAddrSpace(SourceLocation Loc, SourceLocation Start, unsigned Length,
1343  SourceLocation::UIntTy *RelativeOffset = nullptr) const {
1344  assert(((Start.getOffset() < NextLocalOffset &&
1345  Start.getOffset()+Length <= NextLocalOffset) ||
1346  (Start.getOffset() >= CurrentLoadedOffset &&
1347  Start.getOffset()+Length < MaxLoadedOffset)) &&
1348  "Chunk is not valid SLoc address space");
1349  SourceLocation::UIntTy LocOffs = Loc.getOffset();
1350  SourceLocation::UIntTy BeginOffs = Start.getOffset();
1351  SourceLocation::UIntTy EndOffs = BeginOffs + Length;
1352  if (LocOffs >= BeginOffs && LocOffs < EndOffs) {
1353  if (RelativeOffset)
1354  *RelativeOffset = LocOffs - BeginOffs;
1355  return true;
1356  }
1357 
1358  return false;
1359  }
1360 
1361  /// Return true if both \p LHS and \p RHS are in the local source
1362  /// location address space or the loaded one.
1363  ///
1364  /// If it's true and \p RelativeOffset is non-null, it will be set to the
1365  /// offset of \p RHS relative to \p LHS.
1367  SourceLocation::IntTy *RelativeOffset) const {
1368  SourceLocation::UIntTy LHSOffs = LHS.getOffset(), RHSOffs = RHS.getOffset();
1369  bool LHSLoaded = LHSOffs >= CurrentLoadedOffset;
1370  bool RHSLoaded = RHSOffs >= CurrentLoadedOffset;
1371 
1372  if (LHSLoaded == RHSLoaded) {
1373  if (RelativeOffset)
1374  *RelativeOffset = RHSOffs - LHSOffs;
1375  return true;
1376  }
1377 
1378  return false;
1379  }
1380 
1381  //===--------------------------------------------------------------------===//
1382  // Queries about the code at a SourceLocation.
1383  //===--------------------------------------------------------------------===//
1384 
1385  /// Return a pointer to the start of the specified location
1386  /// in the appropriate spelling MemoryBuffer.
1387  ///
1388  /// \param Invalid If non-NULL, will be set \c true if an error occurs.
1389  const char *getCharacterData(SourceLocation SL,
1390  bool *Invalid = nullptr) const;
1391 
1392  /// Return the column # for the specified file position.
1393  ///
1394  /// This is significantly cheaper to compute than the line number. This
1395  /// returns zero if the column number isn't known. This may only be called
1396  /// on a file sloc, so you must choose a spelling or expansion location
1397  /// before calling this method.
1398  unsigned getColumnNumber(FileID FID, unsigned FilePos,
1399  bool *Invalid = nullptr) const;
1401  bool *Invalid = nullptr) const;
1403  bool *Invalid = nullptr) const;
1405  bool *Invalid = nullptr) const;
1406 
1407  /// Given a SourceLocation, return the spelling line number
1408  /// for the position indicated.
1409  ///
1410  /// This requires building and caching a table of line offsets for the
1411  /// MemoryBuffer, so this is not cheap: use only when about to emit a
1412  /// diagnostic.
1413  unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid = nullptr) const;
1414  unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
1415  unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
1416  unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
1417 
1418  /// Return the filename or buffer identifier of the buffer the
1419  /// location is in.
1420  ///
1421  /// Note that this name does not respect \#line directives. Use
1422  /// getPresumedLoc for normal clients.
1423  StringRef getBufferName(SourceLocation Loc, bool *Invalid = nullptr) const;
1424 
1425  /// Return the file characteristic of the specified source
1426  /// location, indicating whether this is a normal file, a system
1427  /// header, or an "implicit extern C" system header.
1428  ///
1429  /// This state can be modified with flags on GNU linemarker directives like:
1430  /// \code
1431  /// # 4 "foo.h" 3
1432  /// \endcode
1433  /// which changes all source locations in the current file after that to be
1434  /// considered to be from a system header.
1436 
1437  /// Returns the "presumed" location of a SourceLocation specifies.
1438  ///
1439  /// A "presumed location" can be modified by \#line or GNU line marker
1440  /// directives. This provides a view on the data that a user should see
1441  /// in diagnostics, for example.
1442  ///
1443  /// Note that a presumed location is always given as the expansion point of
1444  /// an expansion location, not at the spelling location.
1445  ///
1446  /// \returns The presumed location of the specified SourceLocation. If the
1447  /// presumed location cannot be calculated (e.g., because \p Loc is invalid
1448  /// or the file containing \p Loc has changed on disk), returns an invalid
1449  /// presumed location.
1451  bool UseLineDirectives = true) const;
1452 
1453  /// Returns whether the PresumedLoc for a given SourceLocation is
1454  /// in the main file.
1455  ///
1456  /// This computes the "presumed" location for a SourceLocation, then checks
1457  /// whether it came from a file other than the main file. This is different
1458  /// from isWrittenInMainFile() because it takes line marker directives into
1459  /// account.
1460  bool isInMainFile(SourceLocation Loc) const;
1461 
1462  /// Returns true if the spelling locations for both SourceLocations
1463  /// are part of the same file buffer.
1464  ///
1465  /// This check ignores line marker directives.
1467  return getFileID(Loc1) == getFileID(Loc2);
1468  }
1469 
1470  /// Returns true if the spelling location for the given location
1471  /// is in the main file buffer.
1472  ///
1473  /// This check ignores line marker directives.
1475  return getFileID(Loc) == getMainFileID();
1476  }
1477 
1478  /// Returns whether \p Loc is located in a <built-in> file.
1480  PresumedLoc Presumed = getPresumedLoc(Loc);
1481  if (Presumed.isInvalid())
1482  return false;
1483  StringRef Filename(Presumed.getFilename());
1484  return Filename.equals("<built-in>");
1485  }
1486 
1487  /// Returns whether \p Loc is located in a <command line> file.
1489  PresumedLoc Presumed = getPresumedLoc(Loc);
1490  if (Presumed.isInvalid())
1491  return false;
1492  StringRef Filename(Presumed.getFilename());
1493  return Filename.equals("<command line>");
1494  }
1495 
1496  /// Returns whether \p Loc is located in a <scratch space> file.
1498  PresumedLoc Presumed = getPresumedLoc(Loc);
1499  if (Presumed.isInvalid())
1500  return false;
1501  StringRef Filename(Presumed.getFilename());
1502  return Filename.equals("<scratch space>");
1503  }
1504 
1505  /// Returns if a SourceLocation is in a system header.
1507  if (Loc.isInvalid())
1508  return false;
1509  return isSystem(getFileCharacteristic(Loc));
1510  }
1511 
1512  /// Returns if a SourceLocation is in an "extern C" system header.
1515  }
1516 
1517  /// Returns whether \p Loc is expanded from a macro in a system header.
1519  if (!loc.isMacroID())
1520  return false;
1521 
1522  // This happens when the macro is the result of a paste, in that case
1523  // its spelling is the scratch memory, so we take the parent context.
1524  // There can be several level of token pasting.
1526  do {
1527  loc = getImmediateMacroCallerLoc(loc);
1528  } while (isWrittenInScratchSpace(getSpellingLoc(loc)));
1529  return isInSystemMacro(loc);
1530  }
1531 
1532  return isInSystemHeader(getSpellingLoc(loc));
1533  }
1534 
1535  /// The size of the SLocEntry that \p FID represents.
1536  unsigned getFileIDSize(FileID FID) const;
1537 
1538  /// Given a specific FileID, returns true if \p Loc is inside that
1539  /// FileID chunk and sets relative offset (offset of \p Loc from beginning
1540  /// of FileID) to \p relativeOffset.
1542  unsigned *RelativeOffset = nullptr) const {
1543  SourceLocation::UIntTy Offs = Loc.getOffset();
1544  if (isOffsetInFileID(FID, Offs)) {
1545  if (RelativeOffset)
1546  *RelativeOffset = Offs - getSLocEntry(FID).getOffset();
1547  return true;
1548  }
1549 
1550  return false;
1551  }
1552 
1553  //===--------------------------------------------------------------------===//
1554  // Line Table Manipulation Routines
1555  //===--------------------------------------------------------------------===//
1556 
1557  /// Return the uniqued ID for the specified filename.
1558  unsigned getLineTableFilenameID(StringRef Str);
1559 
1560  /// Add a line note to the line table for the FileID and offset
1561  /// specified by Loc.
1562  ///
1563  /// If FilenameID is -1, it is considered to be unspecified.
1564  void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID,
1565  bool IsFileEntry, bool IsFileExit,
1566  SrcMgr::CharacteristicKind FileKind);
1567 
1568  /// Determine if the source manager has a line table.
1569  bool hasLineTable() const { return LineTable != nullptr; }
1570 
1571  /// Retrieve the stored line table.
1573 
1574  //===--------------------------------------------------------------------===//
1575  // Queries for performance analysis.
1576  //===--------------------------------------------------------------------===//
1577 
1578  /// Return the total amount of physical memory allocated by the
1579  /// ContentCache allocator.
1580  size_t getContentCacheSize() const {
1581  return ContentCacheAlloc.getTotalMemory();
1582  }
1583 
1585  const size_t malloc_bytes;
1586  const size_t mmap_bytes;
1587 
1590  };
1591 
1592  /// Return the amount of memory used by memory buffers, breaking down
1593  /// by heap-backed versus mmap'ed memory.
1594  MemoryBufferSizes getMemoryBufferSizes() const;
1595 
1596  /// Return the amount of memory used for various side tables and
1597  /// data structures in the SourceManager.
1598  size_t getDataStructureSizes() const;
1599 
1600  //===--------------------------------------------------------------------===//
1601  // Other miscellaneous methods.
1602  //===--------------------------------------------------------------------===//
1603 
1604  /// Get the source location for the given file:line:col triplet.
1605  ///
1606  /// If the source file is included multiple times, the source location will
1607  /// be based upon the first inclusion.
1608  SourceLocation translateFileLineCol(const FileEntry *SourceFile,
1609  unsigned Line, unsigned Col) const;
1610 
1611  /// Get the FileID for the given file.
1612  ///
1613  /// If the source file is included multiple times, the FileID will be the
1614  /// first inclusion.
1615  FileID translateFile(const FileEntry *SourceFile) const;
1616  FileID translateFile(FileEntryRef SourceFile) const {
1617  return translateFile(&SourceFile.getFileEntry());
1618  }
1619 
1620  /// Get the source location in \p FID for the given line:col.
1621  /// Returns null location if \p FID is not a file SLocEntry.
1623  unsigned Line, unsigned Col) const;
1624 
1625  /// If \p Loc points inside a function macro argument, the returned
1626  /// location will be the macro location in which the argument was expanded.
1627  /// If a macro argument is used multiple times, the expanded location will
1628  /// be at the first expansion of the argument.
1629  /// e.g.
1630  /// MY_MACRO(foo);
1631  /// ^
1632  /// Passing a file location pointing at 'foo', will yield a macro location
1633  /// where 'foo' was expanded into.
1635 
1636  /// Determines the order of 2 source locations in the translation unit.
1637  ///
1638  /// \returns true if LHS source location comes before RHS, false otherwise.
1640 
1641  /// Determines whether the two decomposed source location is in the
1642  /// same translation unit. As a byproduct, it also calculates the order
1643  /// of the source locations in case they are in the same TU.
1644  ///
1645  /// \returns Pair of bools the first component is true if the two locations
1646  /// are in the same TU. The second bool is true if the first is true
1647  /// and \p LOffs is before \p ROffs.
1648  std::pair<bool, bool>
1649  isInTheSameTranslationUnit(std::pair<FileID, unsigned> &LOffs,
1650  std::pair<FileID, unsigned> &ROffs) const;
1651 
1652  /// Determines the order of 2 source locations in the "source location
1653  /// address space".
1655  return isBeforeInSLocAddrSpace(LHS, RHS.getOffset());
1656  }
1657 
1658  /// Determines the order of a source location and a source location
1659  /// offset in the "source location address space".
1660  ///
1661  /// Note that we always consider source locations loaded from
1663  SourceLocation::UIntTy RHS) const {
1664  SourceLocation::UIntTy LHSOffset = LHS.getOffset();
1665  bool LHSLoaded = LHSOffset >= CurrentLoadedOffset;
1666  bool RHSLoaded = RHS >= CurrentLoadedOffset;
1667  if (LHSLoaded == RHSLoaded)
1668  return LHSOffset < RHS;
1669 
1670  return LHSLoaded;
1671  }
1672 
1673  /// Return true if the Point is within Start and End.
1675  SourceLocation End) const {
1676  return Location == Start || Location == End ||
1677  (isBeforeInTranslationUnit(Start, Location) &&
1678  isBeforeInTranslationUnit(Location, End));
1679  }
1680 
1681  // Iterators over FileInfos.
1682  using fileinfo_iterator =
1683  llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::const_iterator;
1684 
1685  fileinfo_iterator fileinfo_begin() const { return FileInfos.begin(); }
1686  fileinfo_iterator fileinfo_end() const { return FileInfos.end(); }
1687  bool hasFileInfo(const FileEntry *File) const {
1688  return FileInfos.find(File) != FileInfos.end();
1689  }
1690 
1691  /// Print statistics to stderr.
1692  void PrintStats() const;
1693 
1694  void dump() const;
1695 
1696  // Produce notes describing the current source location address space usage.
1698  Optional<unsigned> MaxNotes = 32) const;
1699 
1700  /// Get the number of local SLocEntries we have.
1701  unsigned local_sloc_entry_size() const { return LocalSLocEntryTable.size(); }
1702 
1703  /// Get a local SLocEntry. This is exposed for indexing.
1704  const SrcMgr::SLocEntry &getLocalSLocEntry(unsigned Index) const {
1705  assert(Index < LocalSLocEntryTable.size() && "Invalid index");
1706  return LocalSLocEntryTable[Index];
1707  }
1708 
1709  /// Get the number of loaded SLocEntries we have.
1710  unsigned loaded_sloc_entry_size() const { return LoadedSLocEntryTable.size();}
1711 
1712  /// Get a loaded SLocEntry. This is exposed for indexing.
1713  const SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index,
1714  bool *Invalid = nullptr) const {
1715  assert(Index < LoadedSLocEntryTable.size() && "Invalid index");
1716  if (SLocEntryLoaded[Index])
1717  return LoadedSLocEntryTable[Index];
1718  return loadSLocEntry(Index, Invalid);
1719  }
1720 
1722  bool *Invalid = nullptr) const {
1723  if (FID.ID == 0 || FID.ID == -1) {
1724  if (Invalid) *Invalid = true;
1725  return LocalSLocEntryTable[0];
1726  }
1727  return getSLocEntryByID(FID.ID, Invalid);
1728  }
1729 
1730  SourceLocation::UIntTy getNextLocalOffset() const { return NextLocalOffset; }
1731 
1733  assert(LoadedSLocEntryTable.empty() &&
1734  "Invalidating existing loaded entries");
1735  ExternalSLocEntries = Source;
1736  }
1737 
1738  /// Allocate a number of loaded SLocEntries, which will be actually
1739  /// loaded on demand from the external source.
1740  ///
1741  /// NumSLocEntries will be allocated, which occupy a total of TotalSize space
1742  /// in the global source view. The lowest ID and the base offset of the
1743  /// entries will be returned.
1744  std::pair<int, SourceLocation::UIntTy>
1745  AllocateLoadedSLocEntries(unsigned NumSLocEntries,
1746  SourceLocation::UIntTy TotalSize);
1747 
1748  /// Returns true if \p Loc came from a PCH/Module.
1750  return isLoadedOffset(Loc.getOffset());
1751  }
1752 
1753  /// Returns true if \p Loc did not come from a PCH/Module.
1755  return isLocalOffset(Loc.getOffset());
1756  }
1757 
1758  /// Returns true if \p FID came from a PCH/Module.
1759  bool isLoadedFileID(FileID FID) const {
1760  assert(FID.ID != -1 && "Using FileID sentinel value");
1761  return FID.ID < 0;
1762  }
1763 
1764  /// Returns true if \p FID did not come from a PCH/Module.
1765  bool isLocalFileID(FileID FID) const {
1766  return !isLoadedFileID(FID);
1767  }
1768 
1769  /// Gets the location of the immediate macro caller, one level up the stack
1770  /// toward the initial macro typed into the source.
1772  if (!Loc.isMacroID()) return Loc;
1773 
1774  // When we have the location of (part of) an expanded parameter, its
1775  // spelling location points to the argument as expanded in the macro call,
1776  // and therefore is used to locate the macro caller.
1777  if (isMacroArgExpansion(Loc))
1778  return getImmediateSpellingLoc(Loc);
1779 
1780  // Otherwise, the caller of the macro is located where this macro is
1781  // expanded (while the spelling is part of the macro definition).
1782  return getImmediateExpansionRange(Loc).getBegin();
1783  }
1784 
1785  /// \return Location of the top-level macro caller.
1787 
1788 private:
1789  friend class ASTReader;
1790  friend class ASTWriter;
1791 
1792  llvm::MemoryBufferRef getFakeBufferForRecovery() const;
1793  SrcMgr::ContentCache &getFakeContentCacheForRecovery() const;
1794 
1795  const SrcMgr::SLocEntry &loadSLocEntry(unsigned Index, bool *Invalid) const;
1796 
1797  const SrcMgr::SLocEntry *getSLocEntryOrNull(FileID FID) const {
1798  bool Invalid = false;
1799  const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1800  return Invalid ? nullptr : &Entry;
1801  }
1802 
1803  const SrcMgr::SLocEntry *getSLocEntryForFile(FileID FID) const {
1804  if (auto *Entry = getSLocEntryOrNull(FID))
1805  if (Entry->isFile())
1806  return Entry;
1807  return nullptr;
1808  }
1809 
1810  /// Get the entry with the given unwrapped FileID.
1811  /// Invalid will not be modified for Local IDs.
1812  const SrcMgr::SLocEntry &getSLocEntryByID(int ID,
1813  bool *Invalid = nullptr) const {
1814  assert(ID != -1 && "Using FileID sentinel value");
1815  if (ID < 0)
1816  return getLoadedSLocEntryByID(ID, Invalid);
1817  return getLocalSLocEntry(static_cast<unsigned>(ID));
1818  }
1819 
1820  const SrcMgr::SLocEntry &
1821  getLoadedSLocEntryByID(int ID, bool *Invalid = nullptr) const {
1822  return getLoadedSLocEntry(static_cast<unsigned>(-ID - 2), Invalid);
1823  }
1824 
1825  FileID getFileID(SourceLocation::UIntTy SLocOffset) const {
1826  // If our one-entry cache covers this offset, just return it.
1827  if (isOffsetInFileID(LastFileIDLookup, SLocOffset))
1828  return LastFileIDLookup;
1829 
1830  return getFileIDSlow(SLocOffset);
1831  }
1832 
1833  bool isLocalOffset(SourceLocation::UIntTy SLocOffset) const {
1834  return SLocOffset < CurrentLoadedOffset;
1835  }
1836 
1837  bool isLoadedOffset(SourceLocation::UIntTy SLocOffset) const {
1838  return SLocOffset >= CurrentLoadedOffset;
1839  }
1840 
1841  /// Implements the common elements of storing an expansion info struct into
1842  /// the SLocEntry table and producing a source location that refers to it.
1843  SourceLocation
1844  createExpansionLocImpl(const SrcMgr::ExpansionInfo &Expansion,
1845  unsigned Length, int LoadedID = 0,
1846  SourceLocation::UIntTy LoadedOffset = 0);
1847 
1848  /// Return true if the specified FileID contains the
1849  /// specified SourceLocation offset. This is a very hot method.
1850  inline bool isOffsetInFileID(FileID FID,
1851  SourceLocation::UIntTy SLocOffset) const {
1852  const SrcMgr::SLocEntry &Entry = getSLocEntry(FID);
1853  // If the entry is after the offset, it can't contain it.
1854  if (SLocOffset < Entry.getOffset()) return false;
1855 
1856  // If this is the very last entry then it does.
1857  if (FID.ID == -2)
1858  return true;
1859 
1860  // If it is the last local entry, then it does if the location is local.
1861  if (FID.ID+1 == static_cast<int>(LocalSLocEntryTable.size()))
1862  return SLocOffset < NextLocalOffset;
1863 
1864  // Otherwise, the entry after it has to not include it. This works for both
1865  // local and loaded entries.
1866  return SLocOffset < getSLocEntryByID(FID.ID+1).getOffset();
1867  }
1868 
1869  /// Returns the previous in-order FileID or an invalid FileID if there
1870  /// is no previous one.
1871  FileID getPreviousFileID(FileID FID) const;
1872 
1873  /// Returns the next in-order FileID or an invalid FileID if there is
1874  /// no next one.
1875  FileID getNextFileID(FileID FID) const;
1876 
1877  /// Create a new fileID for the specified ContentCache and
1878  /// include position.
1879  ///
1880  /// This works regardless of whether the ContentCache corresponds to a
1881  /// file or some other input source.
1882  FileID createFileIDImpl(SrcMgr::ContentCache &File, StringRef Filename,
1883  SourceLocation IncludePos,
1884  SrcMgr::CharacteristicKind DirCharacter, int LoadedID,
1885  SourceLocation::UIntTy LoadedOffset);
1886 
1887  SrcMgr::ContentCache &getOrCreateContentCache(FileEntryRef SourceFile,
1888  bool isSystemFile = false);
1889 
1890  /// Create a new ContentCache for the specified memory buffer.
1891  SrcMgr::ContentCache &
1892  createMemBufferContentCache(std::unique_ptr<llvm::MemoryBuffer> Buf);
1893 
1894  FileID getFileIDSlow(SourceLocation::UIntTy SLocOffset) const;
1895  FileID getFileIDLocal(SourceLocation::UIntTy SLocOffset) const;
1896  FileID getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const;
1897 
1898  SourceLocation getExpansionLocSlowCase(SourceLocation Loc) const;
1899  SourceLocation getSpellingLocSlowCase(SourceLocation Loc) const;
1900  SourceLocation getFileLocSlowCase(SourceLocation Loc) const;
1901 
1902  std::pair<FileID, unsigned>
1903  getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry *E) const;
1904  std::pair<FileID, unsigned>
1905  getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
1906  unsigned Offset) const;
1907  void computeMacroArgsCache(MacroArgsMap &MacroArgsCache, FileID FID) const;
1908  void associateFileChunkWithMacroArgExp(MacroArgsMap &MacroArgsCache,
1909  FileID FID,
1910  SourceLocation SpellLoc,
1911  SourceLocation ExpansionLoc,
1912  unsigned ExpansionLength) const;
1913 };
1914 
1915 /// Comparison function object.
1916 template<typename T>
1918 
1919 /// Compare two source locations.
1920 template<>
1922  SourceManager &SM;
1923 
1924 public:
1926 
1928  return SM.isBeforeInTranslationUnit(LHS, RHS);
1929  }
1930 };
1931 
1932 /// Compare two non-overlapping source ranges.
1933 template<>
1935  SourceManager &SM;
1936 
1937 public:
1939 
1940  bool operator()(SourceRange LHS, SourceRange RHS) const {
1941  return SM.isBeforeInTranslationUnit(LHS.getBegin(), RHS.getBegin());
1942  }
1943 };
1944 
1945 /// SourceManager and necessary dependencies (e.g. VFS, FileManager) for a
1946 /// single in-memorty file.
1948 public:
1949  /// Creates SourceManager and necessary dependencies (e.g. VFS, FileManager).
1950  /// The main file in the SourceManager will be \p FileName with \p Content.
1951  SourceManagerForFile(StringRef FileName, StringRef Content);
1952 
1954  assert(SourceMgr);
1955  return *SourceMgr;
1956  }
1957 
1958 private:
1959  // The order of these fields are important - they should be in the same order
1960  // as they are created in `createSourceManagerForFile` so that they can be
1961  // deleted in the reverse order as they are created.
1962  std::unique_ptr<FileManager> FileMgr;
1963  std::unique_ptr<DiagnosticsEngine> Diagnostics;
1964  std::unique_ptr<SourceManager> SourceMgr;
1965 };
1966 
1967 } // namespace clang
1968 
1969 #endif // LLVM_CLANG_BASIC_SOURCEMANAGER_H
clang::SourceManager::overrideFileContents
void overrideFileContents(FileEntryRef SourceFile, std::unique_ptr< llvm::MemoryBuffer > Buffer)
Definition: SourceManager.h:976
clang::SourceManager::fileinfo_begin
fileinfo_iterator fileinfo_begin() const
Definition: SourceManager.h:1685
clang::SourceManager::isInTheSameTranslationUnit
std::pair< bool, bool > isInTheSameTranslationUnit(std::pair< FileID, unsigned > &LOffs, std::pair< FileID, unsigned > &ROffs) const
Determines whether the two decomposed source location is in the same translation unit.
Definition: SourceManager.cpp:2080
clang::SourceManager::isMacroBodyExpansion
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body.
Definition: SourceManager.cpp:1075
clang::SourceManager::~SourceManager
~SourceManager()
Definition: SourceManager.cpp:318
clang::SrcMgr::ExpansionInfo::getExpansionLocRange
CharSourceRange getExpansionLocRange() const
Definition: SourceManager.h:387
clang::SrcMgr::ContentCache::ContentsEntry
const FileEntry * ContentsEntry
References the file which the contents were actually loaded from.
Definition: SourceManager.h:150
clang::SrcMgr::ContentCache::getInvalidBOM
static const char * getInvalidBOM(StringRef BufStr)
Definition: SourceManager.cpp:79
clang::SourceManager::getExpansionRange
CharSourceRange getExpansionRange(SourceRange Range) const
Given a SourceRange object, return the range of tokens or characters covered by the expansion in the ...
Definition: SourceManager.h:1194
clang::SourceManager::isMainFile
bool isMainFile(const FileEntry &SourceFile)
Returns true when the given FileEntry corresponds to the main file.
Definition: SourceManager.cpp:355
clang::SourceManager::SourceManager
SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr, bool UserFilesAreVolatile=false)
Definition: SourceManager.cpp:311
clang::SrcMgr::ContentCache::ContentCache
ContentCache(const ContentCache &RHS)
The copy ctor does not allow copies where source object has either a non-NULL Buffer or SourceLineCac...
Definition: SourceManager.h:195
clang::SrcMgr::ContentCache::IsBufferInvalid
unsigned IsBufferInvalid
Definition: SourceManager.h:179
clang::SourceManager::getFilename
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
Definition: SourceManager.cpp:1021
clang::SourceManager::getFileCharacteristic
SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const
Return the file characteristic of the specified source location, indicating whether this is a normal ...
Definition: SourceManager.cpp:1477
clang::BeforeThanCompare< SourceRange >::BeforeThanCompare
BeforeThanCompare(SourceManager &SM)
Definition: SourceManager.h:1938
clang::SourceManager::getOrCreateFileID
FileID getOrCreateFileID(const FileEntry *SourceFile, SrcMgr::CharacteristicKind FileCharacter)
Get the FileID for SourceFile if it exists.
Definition: SourceManager.cpp:590
clang::SourceManager::getLocalSLocEntry
const SrcMgr::SLocEntry & getLocalSLocEntry(unsigned Index) const
Get a local SLocEntry. This is exposed for indexing.
Definition: SourceManager.h:1704
clang::FileEntryRef
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:62
clang::SrcMgr::ContentCache::getMemoryBufferKind
llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const
Returns the kind of memory used to back the memory buffer for this content cache.
Definition: SourceManager.cpp:62
clang::SourceManager::getPreambleFileID
FileID getPreambleFileID() const
Get the file ID for the precompiled preamble if there is one.
Definition: SourceManager.h:870
clang::SourceManager::createMacroArgExpansionLoc
SourceLocation createMacroArgExpansionLoc(SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned Length)
Creates an expansion SLocEntry for the substitution of an argument into a function-like macro's body.
Definition: SourceManager.cpp:635
clang::SourceManager::isInExternCSystemHeader
bool isInExternCSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in an "extern C" system header.
Definition: SourceManager.h:1513
clang::SourceManager::getModuleImportLoc
std::pair< SourceLocation, StringRef > getModuleImportLoc(SourceLocation Loc) const
Definition: SourceManager.h:1154
clang::CharSourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:283
clang::FullSourceLoc
A SourceLocation and its associated SourceManager.
Definition: SourceLocation.h:368
clang::SrcMgr::SLocEntry::getOffset
SourceLocation::UIntTy getOffset() const
Definition: SourceManager.h:486
clang::SourceManager::isInFileID
bool isInFileID(SourceLocation Loc, FileID FID, unsigned *RelativeOffset=nullptr) const
Given a specific FileID, returns true if Loc is inside that FileID chunk and sets relative offset (of...
Definition: SourceManager.h:1541
clang::DeclaratorContext::File
@ File
clang::SrcMgr::ContentCache::operator=
ContentCache & operator=(const ContentCache &RHS)=delete
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
Diag
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Definition: LiteralSupport.cpp:79
clang::SourceManager::getImmediateSpellingLoc
SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
Definition: SourceManager.cpp:1013
clang::SrcMgr::ExpansionInfo::isMacroBodyExpansion
bool isMacroBodyExpansion() const
Definition: SourceManager.h:398
clang::SourceManager::isInMainFile
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
Definition: SourceManager.cpp:1599
clang::BeforeThanCompare< SourceLocation >::operator()
bool operator()(SourceLocation LHS, SourceLocation RHS) const
Definition: SourceManager.h:1927
clang::SrcMgr::ExpansionInfo::isMacroArgExpansion
bool isMacroArgExpansion() const
Definition: SourceManager.h:393
clang::SourceManager::getFileOffset
unsigned getFileOffset(SourceLocation SpellingLoc) const
Returns the offset from the start of the file that the specified SourceLocation represents.
Definition: SourceManager.h:1296
llvm::SmallVector
Definition: LLVM.h:38
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::SrcMgr::ContentCache::setBuffer
void setBuffer(std::unique_ptr< llvm::MemoryBuffer > B)
Set the buffer.
Definition: SourceManager.h:252
clang::SourceManager::setExternalSLocEntrySource
void setExternalSLocEntrySource(ExternalSLocEntrySource *Source)
Definition: SourceManager.h:1732
clang::SrcMgr::LineOffsetMapping::get
static LineOffsetMapping get(llvm::MemoryBufferRef Buffer, llvm::BumpPtrAllocator &Alloc)
Definition: SourceManager.cpp:1274
clang::SourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:219
clang::SourceManager::noteSLocAddressSpaceUsage
void noteSLocAddressSpaceUsage(DiagnosticsEngine &Diag, Optional< unsigned > MaxNotes=32) const
Definition: SourceManager.cpp:2238
clang::SourceManager::getMacroArgExpandedLocation
SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const
If Loc points inside a function macro argument, the returned location will be the macro location in w...
Definition: SourceManager.cpp:1919
clang::SourceManager::fileinfo_iterator
llvm::DenseMap< const FileEntry *, SrcMgr::ContentCache * >::const_iterator fileinfo_iterator
Definition: SourceManager.h:1683
clang::SrcMgr::ContentCache::IsFileVolatile
unsigned IsFileVolatile
True if this content cache was initially created for a source file considered to be volatile (likely ...
Definition: SourceManager.h:172
clang::SrcMgr::ExpansionInfo::isFunctionMacroExpansion
bool isFunctionMacroExpansion() const
Definition: SourceManager.h:402
clang::SourceManager::getNextLocalOffset
SourceLocation::UIntTy getNextLocalOffset() const
Definition: SourceManager.h:1730
clang::SourceManager::getDecomposedSpellingLoc
std::pair< FileID, unsigned > getDecomposedSpellingLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Definition: SourceManager.h:1276
clang::SourceManager::getBufferOrNone
llvm::Optional< llvm::MemoryBufferRef > getBufferOrNone(FileID FID, SourceLocation Loc=SourceLocation()) const
Return the buffer for the specified FileID.
Definition: SourceManager.h:1026
Filename
StringRef Filename
Definition: Format.cpp:2715
clang::SourceManager::operator=
SourceManager & operator=(const SourceManager &)=delete
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::SourceManager::setOverridenFilesKeepOriginalName
void setOverridenFilesKeepOriginalName(bool value)
Set true if the SourceManager should report the original file name for contents of files that were ov...
Definition: SourceManager.h:822
clang::InBeforeInTUCacheEntry::setQueryFIDs
void setQueryFIDs(FileID LHS, FileID RHS)
Set up a new query.
Definition: SourceManager.h:602
clang::SourceManager::getImmediateExpansionRange
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
Definition: SourceManager.cpp:1030
clang::SourceManager::getExpansionColumnNumber
unsigned getExpansionColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Definition: SourceManager.cpp:1247
clang::SourceManager::isWrittenInBuiltinFile
bool isWrittenInBuiltinFile(SourceLocation Loc) const
Returns whether Loc is located in a <built-in> file.
Definition: SourceManager.h:1479
clang::SrcMgr::LineOffsetMapping::end
const unsigned * end() const
Definition: SourceManager.h:111
clang::SourceManager::getExpansionRange
CharSourceRange getExpansionRange(SourceLocation Loc) const
Given a SourceLocation object, return the range of tokens covered by the expansion in the ultimate fi...
Definition: SourceManager.cpp:1044
clang::SourceManager::getFileLoc
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
Definition: SourceManager.h:1177
llvm::Optional< llvm::MemoryBufferRef >
clang::OptionalFileEntryRefDegradesToFileEntryPtr
Wrapper around Optional<FileEntryRef> that degrades to 'const FileEntry*', facilitating incremental p...
Definition: FileEntry.h:298
clang::SourceManager::isWrittenInScratchSpace
bool isWrittenInScratchSpace(SourceLocation Loc) const
Returns whether Loc is located in a <scratch space> file.
Definition: SourceManager.h:1497
clang::SourceManager::getSLocEntry
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
Definition: SourceManager.h:1721
clang::SourceManager::getIncludeLoc
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
Definition: SourceManager.h:1144
clang::SourceManager::PrintStats
void PrintStats() const
Print statistics to stderr.
Definition: SourceManager.cpp:2154
clang::SourceManager::getPresumedLoc
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
Definition: SourceManager.cpp:1523
clang::SrcMgr::CharacteristicKind
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:79
clang::tooling::X
static ToolExecutorPluginRegistry::Add< AllTUsToolExecutorPlugin > X("all-TUs", "Runs FrontendActions on all TUs in the compilation database. " "Tool results are stored in memory.")
clang::SourceManager::AddLineNote
void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID, bool IsFileEntry, bool IsFileExit, SrcMgr::CharacteristicKind FileKind)
Add a line note to the line table for the FileID and offset specified by Loc.
Definition: SourceManager.cpp:273
clang::SourceManager::isAtStartOfImmediateMacroExpansion
bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the beginning of the immediate macro expansion.
Definition: SourceManager.cpp:1083
clang::SourceManager::AllocateLoadedSLocEntries
std::pair< int, SourceLocation::UIntTy > AllocateLoadedSLocEntries(unsigned NumSLocEntries, SourceLocation::UIntTy TotalSize)
Allocate a number of loaded SLocEntries, which will be actually loaded on demand from the external so...
Definition: SourceManager.cpp:454
clang::SourceManager::pushModuleBuildStack
void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc)
Push an entry to the module build stack.
Definition: SourceManager.h:842
clang::CharSourceRange::setTokenRange
void setTokenRange(bool TR)
Definition: SourceLocation.h:289
clang::SourceManager::setModuleBuildStack
void setModuleBuildStack(ModuleBuildStack stack)
Set the module build stack.
Definition: SourceManager.h:836
clang::SourceManager::isMacroArgExpansion
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument's expansion into the function-lik...
Definition: SourceManager.cpp:1062
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::SrcMgr::ContentCache::SourceLineCache
LineOffsetMapping SourceLineCache
A bump pointer allocated array of offsets for each source line.
Definition: SourceManager.h:161
clang::SourceManager::MemoryBufferSizes
Definition: SourceManager.h:1584
clang::SrcMgr::LineOffsetMapping
Mapping of line offsets into a source file.
Definition: SourceManager.h:99
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:637
clang::SourceManager::getFileEntryForSLocEntry
const FileEntry * getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const
Returns the FileEntry record for the provided SLocEntry.
Definition: SourceManager.h:1065
clang::SourceManager::getSpellingColumnNumber
unsigned getSpellingColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Definition: SourceManager.cpp:1240
clang::SrcMgr::FileInfo::getContentCache
const ContentCache & getContentCache() const
Definition: SourceManager.h:330
llvm::RefCountedBase
Definition: LLVM.h:49
Offset
unsigned Offset
Definition: Format.cpp:2717
clang::SourceManager::setAllFilesAreTransient
void setAllFilesAreTransient(bool Transient)
Specify that all files that are read during this compilation are transient.
Definition: SourceManager.h:1013
clang::SourceManager::loaded_sloc_entry_size
unsigned loaded_sloc_entry_size() const
Get the number of loaded SLocEntries we have.
Definition: SourceManager.h:1710
clang::SourceLocation::IntTy
int32_t IntTy
Definition: SourceLocation.h:94
clang::ExternalSLocEntrySource::getModuleImportLoc
virtual std::pair< SourceLocation, StringRef > getModuleImportLoc(int ID)=0
Retrieve the module import location and name for the given ID, if in fact it was loaded from a module...
clang::SrcMgr::SLocEntry::Expansion
ExpansionInfo Expansion
Definition: SourceManager.h:480
FileEntry.h
clang::SourceManager::getExpansionRange
CharSourceRange getExpansionRange(CharSourceRange Range) const
Given a CharSourceRange object, return the range of tokens or characters covered by the expansion in ...
Definition: SourceManager.h:1203
clang::SrcMgr::ContentCache::getBufferIfLoaded
llvm::Optional< llvm::MemoryBufferRef > getBufferIfLoaded() const
Return the buffer, only if it has been loaded.
Definition: SourceManager.h:237
clang::SrcMgr::ContentCache::OrigEntry
OptionalFileEntryRefDegradesToFileEntryPtr OrigEntry
Reference to the file entry representing this ContentCache.
Definition: SourceManager.h:144
clang::SourceManager::MemoryBufferSizes::malloc_bytes
const size_t malloc_bytes
Definition: SourceManager.h:1585
clang::SourceManager::translateLineCol
SourceLocation translateLineCol(FileID FID, unsigned Line, unsigned Col) const
Get the source location in FID for the given line:col.
Definition: SourceManager.cpp:1701
clang::SrcMgr::SLocEntry::SLocEntry
SLocEntry()
Definition: SourceManager.h:484
clang::SrcMgr::ContentCache::setUnownedBuffer
void setUnownedBuffer(llvm::Optional< llvm::MemoryBufferRef > B)
Set the buffer to one that's not owned (or to nullptr).
Definition: SourceManager.h:260
clang::SourceManager::getTopMacroCallerLoc
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
Definition: SourceManager.cpp:1036
clang::SrcMgr::SLocEntry::File
FileInfo File
Definition: SourceManager.h:479
clang::SrcMgr::ExpansionInfo
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded,...
Definition: SourceManager.h:354
clang::SrcMgr::FileInfo::getName
StringRef getName() const
Returns the name of the file that was used when the file was loaded from the underlying file system.
Definition: SourceManager.h:348
clang::BeforeThanCompare< SourceLocation >::BeforeThanCompare
BeforeThanCompare(SourceManager &SM)
Definition: SourceManager.h:1925
clang::PresumedLoc::getFilename
const char * getFilename() const
Return the presumed filename of this location.
Definition: SourceLocation.h:324
clang::SourceManager::getLineTableFilenameID
unsigned getLineTableFilenameID(StringRef Str)
Return the uniqued ID for the specified filename.
Definition: SourceManager.cpp:266
clang::SrcMgr::FileInfo::hasLineDirectives
bool hasLineDirectives() const
Return true if this FileID has #line directives in it.
Definition: SourceManager.h:340
clang::SourceManager::getMainFileID
FileID getMainFileID() const
Returns the FileID of the main source file.
Definition: SourceManager.h:851
clang::SourceManager::isPointWithin
bool isPointWithin(SourceLocation Location, SourceLocation Start, SourceLocation End) const
Return true if the Point is within Start and End.
Definition: SourceManager.h:1674
clang::FileID::isValid
bool isValid() const
Definition: SourceLocation.h:44
clang::SrcMgr::ContentCache::getBufferDataIfLoaded
llvm::Optional< StringRef > getBufferDataIfLoaded() const
Return a StringRef to the source buffer data, only if it has already been loaded.
Definition: SourceManager.h:245
clang::SrcMgr::SLocEntry::getFile
const FileInfo & getFile() const
Definition: SourceManager.h:491
clang::ExternalSLocEntrySource::ReadSLocEntry
virtual bool ReadSLocEntry(int ID)=0
Read the source location entry with index ID, which will always be less than -1.
Diagnostic.h
clang::SrcMgr::ExpansionInfo::createForMacroArg
static ExpansionInfo createForMacroArg(SourceLocation SpellingLoc, SourceLocation ExpansionLoc)
Return a special ExpansionInfo for the expansion of a macro argument into a function-like macro's bod...
Definition: SourceManager.h:443
clang::SrcMgr::FileInfo::get
static FileInfo get(SourceLocation IL, ContentCache &Con, CharacteristicKind FileCharacter, StringRef Filename)
Return a FileInfo object.
Definition: SourceManager.h:314
clang::ExternalSLocEntrySource::~ExternalSLocEntrySource
virtual ~ExternalSLocEntrySource()
clang::SourceManager::isLoadedSourceLocation
bool isLoadedSourceLocation(SourceLocation Loc) const
Returns true if Loc came from a PCH/Module.
Definition: SourceManager.h:1749
clang::SourceManager::createTokenSplitLoc
SourceLocation createTokenSplitLoc(SourceLocation SpellingLoc, SourceLocation TokenStart, SourceLocation TokenEnd)
Return a new SourceLocation that encodes that the token starting at TokenStart ends prematurely at To...
Definition: SourceManager.cpp:652
clang::InBeforeInTUCacheEntry::InBeforeInTUCacheEntry
InBeforeInTUCacheEntry()=default
clang::SrcMgr::ContentCache::getSizeBytesMapped
unsigned getSizeBytesMapped() const
Returns the number of bytes actually mapped for this ContentCache.
Definition: SourceManager.cpp:56
clang::SourceManager::getContentCacheSize
size_t getContentCacheSize() const
Return the total amount of physical memory allocated by the ContentCache allocator.
Definition: SourceManager.h:1580
clang::SourceManager::getBufferName
StringRef getBufferName(SourceLocation Loc, bool *Invalid=nullptr) const
Return the filename or buffer identifier of the buffer the location is in.
Definition: SourceManager.cpp:1506
clang::SrcMgr::ExpansionInfo::getSpellingLoc
SourceLocation getSpellingLoc() const
Definition: SourceManager.h:372
clang::SourceManager::getFileID
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
Definition: SourceManager.h:1118
bool
#define bool
Definition: stdbool.h:20
clang::SourceManager::getColumnNumber
unsigned getColumnNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Return the column # for the specified file position.
Definition: SourceManager.cpp:1186
clang::SourceManager::isWrittenInCommandLineFile
bool isWrittenInCommandLineFile(SourceLocation Loc) const
Returns whether Loc is located in a <command line> file.
Definition: SourceManager.h:1488
clang::SrcMgr::FileInfo::getFileCharacteristic
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
Definition: SourceManager.h:335
clang::SourceLocation::isFileID
bool isFileID() const
Definition: SourceLocation.h:102
llvm::DenseSet< const FileEntry * >
clang::SrcMgr::LineOffsetMapping::size
unsigned size() const
Definition: SourceManager.h:102
clang::SourceManager::getNonBuiltinFilenameForID
Optional< StringRef > getNonBuiltinFilenameForID(FileID FID) const
Returns the filename for the provided FileID, unless it's a built-in buffer that's not represented by...
Definition: SourceManager.cpp:734
clang::SourceManager::userFilesAreVolatile
bool userFilesAreVolatile() const
True if non-system source files should be treated as volatile (likely to change while trying to use t...
Definition: SourceManager.h:828
clang::SourceManagerForFile
SourceManager and necessary dependencies (e.g.
Definition: SourceManager.h:1947
clang::SourceManager::isInSystemMacro
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
Definition: SourceManager.h:1518
clang::SrcMgr::C_User
@ C_User
Definition: SourceManager.h:80
clang::SourceManager::getLoadedSLocEntry
const SrcMgr::SLocEntry & getLoadedSLocEntry(unsigned Index, bool *Invalid=nullptr) const
Get a loaded SLocEntry. This is exposed for indexing.
Definition: SourceManager.h:1713
clang::SourceManager::getLocForEndOfFile
SourceLocation getLocForEndOfFile(FileID FID) const
Return the source location corresponding to the last byte of the specified file.
Definition: SourceManager.h:1135
clang::ASTWriter
Writes an AST file containing the contents of a translation unit.
Definition: ASTWriter.h:85
Line
const AnnotatedLine * Line
Definition: UsingDeclarationsSorter.cpp:68
clang::SourceManager::clearIDTables
void clearIDTables()
Definition: SourceManager.cpp:337
clang::SourceManager::getBufferDataIfLoaded
llvm::Optional< StringRef > getBufferDataIfLoaded(FileID FID) const
Return a StringRef to the source buffer data for the specified FileID, returning None if it's not yet...
Definition: SourceManager.cpp:749
clang::SrcMgr::LineOffsetMapping::getLines
ArrayRef< unsigned > getLines() const
Definition: SourceManager.h:106
clang::FileEntry
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:366
clang::SourceManager::getDecomposedLoc
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Definition: SourceManager.h:1245
clang::SrcMgr::ContentCache::ContentCache
ContentCache(FileEntryRef Ent, const FileEntry *contentEnt)
Definition: SourceManager.h:188
clang::SrcMgr::ContentCache
One instance of this struct is kept for every file loaded or used.
Definition: SourceManager.h:129
clang::SourceManager::getPresumedColumnNumber
unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Definition: SourceManager.cpp:1254
clang::SourceManager::getLineTable
LineTableInfo & getLineTable()
Retrieve the stored line table.
Definition: SourceManager.cpp:301
clang::SrcMgr::LineOffsetMapping::operator[]
const unsigned & operator[](int I) const
Definition: SourceManager.h:112
clang::SourceManager::isBeforeInTranslationUnit
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
Definition: SourceManager.cpp:2026
clang::SrcMgr::ContentCache::ContentCache
ContentCache(FileEntryRef Ent)
Definition: SourceManager.h:186
clang::SourceManager::isWrittenInSameFile
bool isWrittenInSameFile(SourceLocation Loc1, SourceLocation Loc2) const
Returns true if the spelling locations for both SourceLocations are part of the same file buffer.
Definition: SourceManager.h:1466
clang::SrcMgr::LineOffsetMapping::LineOffsetMapping
LineOffsetMapping()=default
clang::SourceManager::translateFile
FileID translateFile(FileEntryRef SourceFile) const
Definition: SourceManager.h:1616
clang::SourceManager::getLocForStartOfFile
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
Definition: SourceManager.h:1127
clang::SourceManager::getMemoryBufferSizes
MemoryBufferSizes getMemoryBufferSizes() const
Return the amount of memory used by memory buffers, breaking down by heap-backed versus mmap'ed memor...
Definition: SourceManager.cpp:2330
clang::SrcMgr::FileInfo::getIncludeLoc
SourceLocation getIncludeLoc() const
Definition: SourceManager.h:326
clang::PresumedLoc::isInvalid
bool isInvalid() const
Return true if this object is invalid or uninitialized.
Definition: SourceLocation.h:318
clang::SourceManager::isInSLocAddrSpace
bool isInSLocAddrSpace(SourceLocation Loc, SourceLocation Start, unsigned Length, SourceLocation::UIntTy *RelativeOffset=nullptr) const
Returns true if Loc is inside the [Start, +Length) chunk of the source location address space.
Definition: SourceManager.h:1342
clang::SrcMgr::SLocEntry::getExpansion
const ExpansionInfo & getExpansion() const
Definition: SourceManager.h:496
SourceLocation.h
clang::SourceManagerForFile::get
SourceManager & get()
Definition: SourceManager.h:1953
clang::SourceManager::getMemoryBufferForFileOrNone
llvm::Optional< llvm::MemoryBufferRef > getMemoryBufferForFileOrNone(const FileEntry *File)
Retrieve the memory buffer associated with the given file.
Definition: SourceManager.cpp:686
false
#define false
Definition: stdbool.h:22
clang::SrcMgr::ExpansionInfo::isExpansionTokenRange
bool isExpansionTokenRange() const
Definition: SourceManager.h:385
clang::BeforeThanCompare
Comparison function object.
Definition: SourceManager.h:1917
clang::SrcMgr::ContentCache::getBufferOrNone
llvm::Optional< llvm::MemoryBufferRef > getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM, SourceLocation Loc=SourceLocation()) const
Returns the memory buffer for the associated content.
Definition: SourceManager.cpp:103
clang::SourceManager::hasLineTable
bool hasLineTable() const
Determine if the source manager has a line table.
Definition: SourceManager.h:1569
clang::BeforeThanCompare< SourceRange >::operator()
bool operator()(SourceRange LHS, SourceRange RHS) const
Definition: SourceManager.h:1940
clang::InBeforeInTUCacheEntry
Holds the cache used by isBeforeInTranslationUnit.
Definition: SourceManager.h:545
clang::SourceManager::isLocalSourceLocation
bool isLocalSourceLocation(SourceLocation Loc) const
Returns true if Loc did not come from a PCH/Module.
Definition: SourceManager.h:1754
clang::SrcMgr::ContentCache::getSize
unsigned getSize() const
Returns the size of the content encapsulated by this ContentCache.
Definition: SourceManager.cpp:74
clang::SrcMgr::ExpansionInfo::getExpansionLocStart
SourceLocation getExpansionLocStart() const
Definition: SourceManager.h:376
clang::SourceManager::isAtEndOfImmediateMacroExpansion
bool isAtEndOfImmediateMacroExpansion(SourceLocation Loc, SourceLocation *MacroEnd=nullptr) const
Returns true if the given MacroID location points at the character end of the immediate macro expansi...
Definition: SourceManager.cpp:1118
clang::SrcMgr::ContentCache::IsTransient
unsigned IsTransient
True if this file may be transient, that is, if it might not exist at some later point in time when t...
Definition: SourceManager.h:177
Begin
SourceLocation Begin
Definition: USRLocFinder.cpp:165
llvm::ArrayRef< unsigned >
clang::SrcMgr::SLocEntry::isExpansion
bool isExpansion() const
Definition: SourceManager.h:488
clang::SourceManager::getCharacterData
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
Definition: SourceManager.cpp:1160
clang::SourceManagerForFile::SourceManagerForFile
SourceManagerForFile(StringRef FileName, StringRef Content)
Creates SourceManager and necessary dependencies (e.g.
Definition: SourceManager.cpp:2361
clang::CharSourceRange
Represents a character-granular source range.
Definition: SourceLocation.h:253
clang::InBeforeInTUCacheEntry::setCommonLoc
void setCommonLoc(FileID commonFID, unsigned lCommonOffset, unsigned rCommonOffset, bool LParentBeforeRParent)
Definition: SourceManager.h:611
clang::SourceManager::setMainFileID
void setMainFileID(FileID FID)
Set the file ID for the main source file.
Definition: SourceManager.h:854
clang::SourceManager::dump
void dump() const
Definition: SourceManager.cpp:2182
clang::SrcMgr::ExpansionInfo::getExpansionLocEnd
SourceLocation getExpansionLocEnd() const
Definition: SourceManager.h:380
clang::SrcMgr::ContentCache::ContentCache
ContentCache()
Definition: SourceManager.h:181
clang::InBeforeInTUCacheEntry::isCacheValid
bool isCacheValid() const
Return true if the currently cached values match up with the specified LHS/RHS query.
Definition: SourceManager.h:577
clang::SourceManager::getBufferData
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
Definition: SourceManager.cpp:741
clang::CharSourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:284
clang::SrcMgr::LineOffsetMapping::begin
const unsigned * begin() const
Definition: SourceManager.h:110
clang::SrcMgr::C_System_ModuleMap
@ C_System_ModuleMap
Definition: SourceManager.h:84
clang::SourceManager::overrideFileContents
void overrideFileContents(const FileEntry *SourceFile, const llvm::MemoryBufferRef &Buffer)
Override the contents of the given source file by providing an already-allocated buffer.
Definition: SourceManager.h:962
clang::SourceLocation::isMacroID
bool isMacroID() const
Definition: SourceLocation.h:103
clang::SourceManager::fileinfo_end
fileinfo_iterator fileinfo_end() const
Definition: SourceManager.h:1686
clang::SourceManager::isLoadedFileID
bool isLoadedFileID(FileID FID) const
Returns true if FID came from a PCH/Module.
Definition: SourceManager.h:1759
clang::ASTReader
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:359
clang::SourceManager::isInSameSLocAddrSpace
bool isInSameSLocAddrSpace(SourceLocation LHS, SourceLocation RHS, SourceLocation::IntTy *RelativeOffset) const
Return true if both LHS and RHS are in the local source location address space or the loaded one.
Definition: SourceManager.h:1366
clang::SourceManager::isBeforeInSLocAddrSpace
bool isBeforeInSLocAddrSpace(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the "source location address space".
Definition: SourceManager.h:1654
std
Definition: Format.h:4477
clang::SourceManager::initializeForReplay
void initializeForReplay(const SourceManager &Old)
Initialize this source manager suitably to replay the compilation described by Old.
Definition: SourceManager.cpp:362
clang::SourceManager::getNumCreatedFIDsForFileID
unsigned getNumCreatedFIDsForFileID(FileID FID) const
Get the number of FileIDs (files and macros) that were created during preprocessing of FID,...
Definition: SourceManager.h:1091
clang::Builtin::ID
ID
Definition: Builtins.h:52
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang::SourceManager::getMemoryBufferForFileOrFake
llvm::MemoryBufferRef getMemoryBufferForFileOrFake(const FileEntry *File)
Retrieve the memory buffer associated with the given file.
Definition: SourceManager.h:949
clang
Definition: CalledOnceCheck.h:17
clang::SrcMgr::C_ExternCSystem
@ C_ExternCSystem
Definition: SourceManager.h:82
clang::FileManager
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
clang::SourceManager::createFileID
FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
Definition: SourceManager.cpp:534
clang::SourceManager::setNumCreatedFIDsForFileID
void setNumCreatedFIDsForFileID(FileID FID, unsigned NumFIDs, bool Force=false) const
Set the number of FileIDs (files and macros) that were created during preprocessing of FID,...
Definition: SourceManager.h:1099
clang::SourceManager::getDecomposedIncludedLoc
std::pair< FileID, unsigned > getDecomposedIncludedLoc(FileID FID) const
Returns the "included/expanded in" decomposed location of the given FileID.
Definition: SourceManager.cpp:1953
clang::SourceManager::getImmediateMacroCallerLoc
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
Definition: SourceManager.h:1771
clang::SourceManager::isInSystemHeader
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
Definition: SourceManager.h:1506
clang::SourceManager::setPreambleFileID
void setPreambleFileID(FileID Preamble)
Set the file ID for the precompiled preamble.
Definition: SourceManager.h:864
clang::SourceManager::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Definition: SourceManager.h:815
clang::SrcMgr::SLocEntry::get
static SLocEntry get(SourceLocation::UIntTy Offset, const FileInfo &FI)
Definition: SourceManager.h:501
clang::FileID
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Definition: SourceLocation.h:38
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:110
clang::FileID::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:45
clang::SourceManager::getFileEntryForID
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
Definition: SourceManager.h:1045
clang::SrcMgr::isSystem
bool isSystem(CharacteristicKind CK)
Determine whether a file / directory characteristic is for system code.
Definition: SourceManager.h:88
clang::SourceManager::getComposedLoc
SourceLocation getComposedLoc(FileID FID, unsigned Offset) const
Form a SourceLocation from a FileID and Offset pair.
Definition: SourceManager.h:1231
clang::FileEntryRef::getFileEntry
const FileEntry & getFileEntry() const
Definition: FileEntry.h:75
clang::LineTableInfo
Used to hold and unique data used to represent #line information.
Definition: SourceManagerInternals.h:80
clang::SourceManager::getModuleBuildStack
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
Definition: SourceManager.h:831
clang::SourceManager::getFileManager
FileManager & getFileManager() const
Definition: SourceManager.h:817
clang::SourceManager::MemoryBufferSizes::mmap_bytes
const size_t mmap_bytes
Definition: SourceManager.h:1586
clang::SrcMgr::isModuleMap
bool isModuleMap(CharacteristicKind CK)
Determine whether a file characteristic is for a module map.
Definition: SourceManager.h:93
clang::SourceManager::local_sloc_entry_size
unsigned local_sloc_entry_size() const
Get the number of local SLocEntries we have.
Definition: SourceManager.h:1701
clang::SrcMgr::ContentCache::BufferOverridden
unsigned BufferOverridden
Indicates whether the buffer itself was provided to override the actual file contents.
Definition: SourceManager.h:168
clang::SourceManager::getFileEntryRefForID
Optional< FileEntryRef > getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
Definition: SourceManager.h:1052
clang::SrcMgr::FileInfo
Information about a FileID, basically just the logical file that it represents and include stack info...
Definition: SourceManager.h:289
clang::SourceManager::getExpansionLoc
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
Definition: SourceManager.h:1167
clang::SrcMgr::ExpansionInfo::create
static ExpansionInfo create(SourceLocation SpellingLoc, SourceLocation Start, SourceLocation End, bool ExpansionIsTokenRange=true)
Return a ExpansionInfo for an expansion.
Definition: SourceManager.h:413
clang::SourceManager::isBeforeInSLocAddrSpace
bool isBeforeInSLocAddrSpace(SourceLocation LHS, SourceLocation::UIntTy RHS) const
Determines the order of a source location and a source location offset in the "source location addres...
Definition: SourceManager.h:1662
clang::PresumedLoc
Represents an unpacked "presumed" location which can be presented to the user.
Definition: SourceLocation.h:302
clang::SourceManager::translateFileLineCol
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
Definition: SourceManager.cpp:1648
clang::SourceManager::getSpellingLineNumber
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Definition: SourceManager.cpp:1449
FileManager.h
clang::SrcMgr::C_System
@ C_System
Definition: SourceManager.h:81
clang::SourceManager::isLocalFileID
bool isLocalFileID(FileID FID) const
Returns true if FID did not come from a PCH/Module.
Definition: SourceManager.h:1765
clang::SourceManager::hasFileInfo
bool hasFileInfo(const FileEntry *File) const
Definition: SourceManager.h:1687
clang::InBeforeInTUCacheEntry::getCachedResult
bool getCachedResult(unsigned LOffset, unsigned ROffset) const
If the cache is valid, compute the result given the specified offsets in the LHS/RHS FileID's.
Definition: SourceManager.h:583
clang::SourceManager::getExpansionLineNumber
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Definition: SourceManager.cpp:1455
SM
#define SM(sm)
Definition: Cuda.cpp:79
clang::SourceManager::getFileIDSize
unsigned getFileIDSize(FileID FID) const
The size of the SLocEntry that FID represents.
Definition: SourceManager.cpp:1622
clang::SourceManager::bypassFileContentsOverride
Optional< FileEntryRef > bypassFileContentsOverride(FileEntryRef File)
Bypass the overridden contents of a file.
Definition: SourceManager.cpp:717
clang::SrcMgr::FileInfo::setHasLineDirectives
void setHasLineDirectives()
Set the flag that indicates that this FileID has line table entries associated with it.
Definition: SourceManager.h:344
clang::SrcMgr::SLocEntry::isFile
bool isFile() const
Definition: SourceManager.h:489
clang::SourceManager::getDecomposedExpansionLoc
std::pair< FileID, unsigned > getDecomposedExpansionLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Definition: SourceManager.h:1258
clang::ExternalSLocEntrySource
External source of source location entries.
Definition: SourceManager.h:524
clang::SourceManager::getBufferOrFake
llvm::MemoryBufferRef getBufferOrFake(FileID FID, SourceLocation Loc=SourceLocation()) const
Return the buffer for the specified FileID.
Definition: SourceManager.h:1038
clang::SrcMgr::C_User_ModuleMap
@ C_User_ModuleMap
Definition: SourceManager.h:83
clang::SourceManager::translateFile
FileID translateFile(const FileEntry *SourceFile) const
Get the FileID for the given file.
Definition: SourceManager.cpp:1662
clang::SrcMgr::SLocEntry::get
static SLocEntry get(SourceLocation::UIntTy Offset, const ExpansionInfo &Expansion)
Definition: SourceManager.h:510
clang::RISCV::Invalid
@ Invalid
Definition: RISCVVIntrinsicUtils.h:171
clang::SourceManager::isWrittenInMainFile
bool isWrittenInMainFile(SourceLocation Loc) const
Returns true if the spelling location for the given location is in the main file buffer.
Definition: SourceManager.h:1474
clang::SourceManager::getDataStructureSizes
size_t getDataStructureSizes() const
Return the amount of memory used for various side tables and data structures in the SourceManager.
Definition: SourceManager.cpp:2348
clang::SourceManager::createExpansionLoc
SourceLocation createExpansionLoc(SourceLocation SpellingLoc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned Length, bool ExpansionIsTokenRange=true, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Creates an expansion SLocEntry for a macro use.
Definition: SourceManager.cpp:642
clang::SourceManager::MemoryBufferSizes::MemoryBufferSizes
MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
Definition: SourceManager.h:1588
clang::SourceManager::isFileOverridden
bool isFileOverridden(const FileEntry *File) const
Returns true if the file contents have been overridden.
Definition: SourceManager.h:990
clang::SrcMgr::ContentCache::Filename
StringRef Filename
The filename that is used to access OrigEntry.
Definition: SourceManager.h:155
clang::SourceManager::getBufferDataOrNone
llvm::Optional< StringRef > getBufferDataOrNone(FileID FID) const
Return a StringRef to the source buffer data for the specified FileID, returning None if invalid.
Definition: SourceManager.cpp:755
clang::SourceLocation::UIntTy
uint32_t UIntTy
Definition: SourceLocation.h:93
clang::SrcMgr::ExpansionInfo::createForTokenSplit
static ExpansionInfo createForTokenSplit(SourceLocation SpellingLoc, SourceLocation Start, SourceLocation End)
Return a special ExpansionInfo representing a token that ends prematurely.
Definition: SourceManager.h:456
clang::InBeforeInTUCacheEntry::InBeforeInTUCacheEntry
InBeforeInTUCacheEntry(FileID L, FileID R)
Definition: SourceManager.h:569
clang::SkipFunctionBodiesScope::Preamble
@ Preamble
clang::SourceManager::setFileIsTransient
void setFileIsTransient(const FileEntry *SourceFile)
Specify that a file is transient.
Definition: SourceManager.cpp:729
clang::SourceManager::getPresumedLineNumber
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Definition: SourceManager.cpp:1461
clang::SourceManager::getLineNumber
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
Definition: SourceManager.cpp:1352
clang::SrcMgr::SLocEntry
This is a discriminated union of FileInfo and ExpansionInfo.
Definition: SourceManager.h:474
clang::SourceManager::getSpellingLoc
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
Definition: SourceManager.h:1215