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