1 //===- SourceManager.h - Track and cache source files -----------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
10 /// Defines the SourceManager interface.
12 /// There are three different types of locations in a %file: a spelling
13 /// location, an expansion location, and a presumed location.
15 /// Given an example of:
17 /// #define min(x, y) x < y ? x : y
20 /// and then later on a use of min:
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.
32 //===----------------------------------------------------------------------===//
34 #ifndef LLVM_CLANG_BASIC_SOURCEMANAGER_H
35 #define LLVM_CLANG_BASIC_SOURCEMANAGER_H
37 #include "clang/Basic/Diagnostic.h"
38 #include "clang/Basic/SourceLocation.h"
39 #include "llvm/ADT/ArrayRef.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/DenseSet.h"
43 #include "llvm/ADT/IntrusiveRefCntPtr.h"
44 #include "llvm/ADT/PointerIntPair.h"
45 #include "llvm/ADT/SmallVector.h"
46 #include "llvm/ADT/StringRef.h"
47 #include "llvm/Support/Allocator.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/MemoryBuffer.h"
68 /// Public enums and private classes that are part of the
69 /// SourceManager implementation.
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.
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.
79 enum CharacteristicKind {
80 C_User, C_System, C_ExternCSystem, C_User_ModuleMap, C_System_ModuleMap
83 /// Determine whether a file / directory characteristic is for system code.
84 inline bool isSystem(CharacteristicKind CK) {
85 return CK != C_User && CK != C_User_ModuleMap;
88 /// Determine whether a file characteristic is for a module map.
89 inline bool isModuleMap(CharacteristicKind CK) {
90 return CK == C_User_ModuleMap || CK == C_System_ModuleMap;
93 /// One instance of this struct is kept for every file loaded or used.
95 /// This object owns the MemoryBuffer object.
96 class alignas(8) ContentCache {
98 /// Whether the buffer is invalid.
101 /// Whether the buffer should not be freed on destruction.
105 /// The actual buffer containing the characters from the input
108 /// This is owned by the ContentCache object. The bits indicate
109 /// whether the buffer is invalid.
110 mutable llvm::PointerIntPair<const llvm::MemoryBuffer *, 2> Buffer;
113 /// Reference to the file entry representing this ContentCache.
115 /// This reference does not own the FileEntry object.
117 /// It is possible for this to be NULL if the ContentCache encapsulates
118 /// an imaginary text buffer.
119 const FileEntry *OrigEntry;
121 /// References the file which the contents were actually loaded from.
123 /// Can be different from 'Entry' if we overridden the contents of one file
124 /// with the contents of another file.
125 const FileEntry *ContentsEntry;
127 /// A bump pointer allocated array of offsets for each source line.
129 /// This is lazily computed. This is owned by the SourceManager
130 /// BumpPointerAllocator object.
131 unsigned *SourceLineCache = nullptr;
133 /// The number of lines in this ContentCache.
135 /// This is only valid if SourceLineCache is non-null.
136 unsigned NumLines = 0;
138 /// Indicates whether the buffer itself was provided to override
139 /// the actual file contents.
141 /// When true, the original entry may be a virtual file that does not
143 unsigned BufferOverridden : 1;
145 /// True if this content cache was initially created for a source file
146 /// considered to be volatile (likely to change between stat and open).
147 unsigned IsFileVolatile : 1;
149 /// True if this file may be transient, that is, if it might not
150 /// exist at some later point in time when this content entry is used,
151 /// after serialization and deserialization.
152 unsigned IsTransient : 1;
154 ContentCache(const FileEntry *Ent = nullptr) : ContentCache(Ent, Ent) {}
156 ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
157 : Buffer(nullptr, false), OrigEntry(Ent), ContentsEntry(contentEnt),
158 BufferOverridden(false), IsFileVolatile(false), IsTransient(false) {}
160 /// The copy ctor does not allow copies where source object has either
161 /// a non-NULL Buffer or SourceLineCache. Ownership of allocated memory
162 /// is not transferred, so this is a logical error.
163 ContentCache(const ContentCache &RHS)
164 : Buffer(nullptr, false), BufferOverridden(false),
165 IsFileVolatile(false), IsTransient(false) {
166 OrigEntry = RHS.OrigEntry;
167 ContentsEntry = RHS.ContentsEntry;
169 assert(RHS.Buffer.getPointer() == nullptr &&
170 RHS.SourceLineCache == nullptr &&
171 "Passed ContentCache object cannot own a buffer.");
173 NumLines = RHS.NumLines;
176 ContentCache &operator=(const ContentCache& RHS) = delete;
180 /// Returns the memory buffer for the associated content.
182 /// \param Diag Object through which diagnostics will be emitted if the
183 /// buffer cannot be retrieved.
185 /// \param Loc If specified, is the location that invalid file diagnostics
186 /// will be emitted at.
188 /// \param Invalid If non-NULL, will be set \c true if an error occurred.
189 const llvm::MemoryBuffer *getBuffer(DiagnosticsEngine &Diag,
191 SourceLocation Loc = SourceLocation(),
192 bool *Invalid = nullptr) const;
194 /// Returns the size of the content encapsulated by this
197 /// This can be the size of the source file or the size of an
198 /// arbitrary scratch buffer. If the ContentCache encapsulates a source
199 /// file this size is retrieved from the file's FileEntry.
200 unsigned getSize() const;
202 /// Returns the number of bytes actually mapped for this
205 /// This can be 0 if the MemBuffer was not actually expanded.
206 unsigned getSizeBytesMapped() const;
208 /// Returns the kind of memory used to back the memory buffer for
209 /// this content cache. This is used for performance analysis.
210 llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const;
212 /// Get the underlying buffer, returning NULL if the buffer is not
214 const llvm::MemoryBuffer *getRawBuffer() const {
215 return Buffer.getPointer();
218 /// Replace the existing buffer (which will be deleted)
219 /// with the given buffer.
220 void replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree = false);
222 /// Determine whether the buffer itself is invalid.
223 bool isBufferInvalid() const {
224 return Buffer.getInt() & InvalidFlag;
227 /// Determine whether the buffer should be freed.
228 bool shouldFreeBuffer() const {
229 return (Buffer.getInt() & DoNotFreeFlag) == 0;
232 // If BufStr has an invalid BOM, returns the BOM name; otherwise, returns
234 static const char *getInvalidBOM(StringRef BufStr);
237 // Assert that the \c ContentCache objects will always be 8-byte aligned so
238 // that we can pack 3 bits of integer into pointers to such objects.
239 static_assert(alignof(ContentCache) >= 8,
240 "ContentCache must be 8-byte aligned.");
242 /// Information about a FileID, basically just the logical file
243 /// that it represents and include stack information.
245 /// Each FileInfo has include stack information, indicating where it came
246 /// from. This information encodes the \#include chain that a token was
247 /// expanded from. The main include file has an invalid IncludeLoc.
249 /// FileInfos contain a "ContentCache *", with the contents of the file.
252 friend class clang::SourceManager;
253 friend class clang::ASTWriter;
254 friend class clang::ASTReader;
256 /// The location of the \#include that brought in this file.
258 /// This is an invalid SLOC for the main file (top of the \#include chain).
259 unsigned IncludeLoc; // Really a SourceLocation
261 /// Number of FileIDs (files and macros) that were created during
262 /// preprocessing of this \#include, including this SLocEntry.
264 /// Zero means the preprocessor didn't provide such info for this SLocEntry.
265 unsigned NumCreatedFIDs : 31;
267 /// Whether this FileInfo has any \#line directives.
268 unsigned HasLineDirectives : 1;
270 /// The content cache and the characteristic of the file.
271 llvm::PointerIntPair<const ContentCache*, 3, CharacteristicKind>
274 /// The filename that is used to access the file entry represented by the
279 /// Return a FileInfo object.
280 static FileInfo get(SourceLocation IL, const ContentCache *Con,
281 CharacteristicKind FileCharacter, StringRef Filename) {
283 X.IncludeLoc = IL.getRawEncoding();
284 X.NumCreatedFIDs = 0;
285 X.HasLineDirectives = false;
286 X.ContentAndKind.setPointer(Con);
287 X.ContentAndKind.setInt(FileCharacter);
288 X.Filename = Filename;
292 SourceLocation getIncludeLoc() const {
293 return SourceLocation::getFromRawEncoding(IncludeLoc);
296 const ContentCache *getContentCache() const {
297 return ContentAndKind.getPointer();
300 /// Return whether this is a system header or not.
301 CharacteristicKind getFileCharacteristic() const {
302 return ContentAndKind.getInt();
305 /// Return true if this FileID has \#line directives in it.
306 bool hasLineDirectives() const { return HasLineDirectives; }
308 /// Set the flag that indicates that this FileID has
309 /// line table entries associated with it.
310 void setHasLineDirectives() {
311 HasLineDirectives = true;
314 /// Returns the name of the file that was used when the file was loaded from
315 /// the underlying file system.
316 StringRef getName() const { return Filename; }
319 /// Each ExpansionInfo encodes the expansion location - where
320 /// the token was ultimately expanded, and the SpellingLoc - where the actual
321 /// character data for the token came from.
322 class ExpansionInfo {
323 // Really these are all SourceLocations.
325 /// Where the spelling for the token can be found.
326 unsigned SpellingLoc;
328 /// In a macro expansion, ExpansionLocStart and ExpansionLocEnd
329 /// indicate the start and end of the expansion. In object-like macros,
330 /// they will be the same. In a function-like macro expansion, the start
331 /// will be the identifier and the end will be the ')'. Finally, in
332 /// macro-argument instantiations, the end will be 'SourceLocation()', an
333 /// invalid location.
334 unsigned ExpansionLocStart, ExpansionLocEnd;
336 /// Whether the expansion range is a token range.
337 bool ExpansionIsTokenRange;
340 SourceLocation getSpellingLoc() const {
341 SourceLocation SpellLoc = SourceLocation::getFromRawEncoding(SpellingLoc);
342 return SpellLoc.isInvalid() ? getExpansionLocStart() : SpellLoc;
345 SourceLocation getExpansionLocStart() const {
346 return SourceLocation::getFromRawEncoding(ExpansionLocStart);
349 SourceLocation getExpansionLocEnd() const {
350 SourceLocation EndLoc =
351 SourceLocation::getFromRawEncoding(ExpansionLocEnd);
352 return EndLoc.isInvalid() ? getExpansionLocStart() : EndLoc;
355 bool isExpansionTokenRange() const {
356 return ExpansionIsTokenRange;
359 CharSourceRange getExpansionLocRange() const {
360 return CharSourceRange(
361 SourceRange(getExpansionLocStart(), getExpansionLocEnd()),
362 isExpansionTokenRange());
365 bool isMacroArgExpansion() const {
366 // Note that this needs to return false for default constructed objects.
367 return getExpansionLocStart().isValid() &&
368 SourceLocation::getFromRawEncoding(ExpansionLocEnd).isInvalid();
371 bool isMacroBodyExpansion() const {
372 return getExpansionLocStart().isValid() &&
373 SourceLocation::getFromRawEncoding(ExpansionLocEnd).isValid();
376 bool isFunctionMacroExpansion() const {
377 return getExpansionLocStart().isValid() &&
378 getExpansionLocStart() != getExpansionLocEnd();
381 /// Return a ExpansionInfo for an expansion.
383 /// Start and End specify the expansion range (where the macro is
384 /// expanded), and SpellingLoc specifies the spelling location (where
385 /// the characters from the token come from). All three can refer to
386 /// normal File SLocs or expansion locations.
387 static ExpansionInfo create(SourceLocation SpellingLoc,
388 SourceLocation Start, SourceLocation End,
389 bool ExpansionIsTokenRange = true) {
391 X.SpellingLoc = SpellingLoc.getRawEncoding();
392 X.ExpansionLocStart = Start.getRawEncoding();
393 X.ExpansionLocEnd = End.getRawEncoding();
394 X.ExpansionIsTokenRange = ExpansionIsTokenRange;
398 /// Return a special ExpansionInfo for the expansion of
399 /// a macro argument into a function-like macro's body.
401 /// ExpansionLoc specifies the expansion location (where the macro is
402 /// expanded). This doesn't need to be a range because a macro is always
403 /// expanded at a macro parameter reference, and macro parameters are
404 /// always exactly one token. SpellingLoc specifies the spelling location
405 /// (where the characters from the token come from). ExpansionLoc and
406 /// SpellingLoc can both refer to normal File SLocs or expansion locations.
410 /// #define F(x) f(x)
414 /// When expanding '\c F(42)', the '\c x' would call this with an
415 /// SpellingLoc pointing at '\c 42' and an ExpansionLoc pointing at its
416 /// location in the definition of '\c F'.
417 static ExpansionInfo createForMacroArg(SourceLocation SpellingLoc,
418 SourceLocation ExpansionLoc) {
419 // We store an intentionally invalid source location for the end of the
420 // expansion range to mark that this is a macro argument location rather
421 // than a normal one.
422 return create(SpellingLoc, ExpansionLoc, SourceLocation());
425 /// Return a special ExpansionInfo representing a token that ends
426 /// prematurely. This is used to model a '>>' token that has been split
427 /// into '>' tokens and similar cases. Unlike for the other forms of
428 /// expansion, the expansion range in this case is a character range, not
430 static ExpansionInfo createForTokenSplit(SourceLocation SpellingLoc,
431 SourceLocation Start,
432 SourceLocation End) {
433 return create(SpellingLoc, Start, End, false);
437 /// This is a discriminated union of FileInfo and ExpansionInfo.
439 /// SourceManager keeps an array of these objects, and they are uniquely
440 /// identified by the FileID datatype.
442 unsigned Offset : 31;
443 unsigned IsExpansion : 1;
446 ExpansionInfo Expansion;
450 SLocEntry() : Offset(), IsExpansion(), File() {}
452 unsigned getOffset() const { return Offset; }
454 bool isExpansion() const { return IsExpansion; }
455 bool isFile() const { return !isExpansion(); }
457 const FileInfo &getFile() const {
458 assert(isFile() && "Not a file SLocEntry!");
462 const ExpansionInfo &getExpansion() const {
463 assert(isExpansion() && "Not a macro expansion SLocEntry!");
467 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
468 assert(!(Offset & (1u << 31)) && "Offset is too large");
471 E.IsExpansion = false;
476 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
477 assert(!(Offset & (1u << 31)) && "Offset is too large");
480 E.IsExpansion = true;
481 E.Expansion = Expansion;
486 } // namespace SrcMgr
488 /// External source of source location entries.
489 class ExternalSLocEntrySource {
491 virtual ~ExternalSLocEntrySource();
493 /// Read the source location entry with index ID, which will always be
496 /// \returns true if an error occurred that prevented the source-location
497 /// entry from being loaded.
498 virtual bool ReadSLocEntry(int ID) = 0;
500 /// Retrieve the module import location and name for the given ID, if
501 /// in fact it was loaded from a module (rather than, say, a precompiled
503 virtual std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) = 0;
506 /// Holds the cache used by isBeforeInTranslationUnit.
508 /// The cache structure is complex enough to be worth breaking out of
510 class InBeforeInTUCacheEntry {
511 /// The FileID's of the cached query.
513 /// If these match up with a subsequent query, the result can be reused.
514 FileID LQueryFID, RQueryFID;
516 /// True if LQueryFID was created before RQueryFID.
518 /// This is used to compare macro expansion locations.
519 bool IsLQFIDBeforeRQFID;
521 /// The file found in common between the two \#include traces, i.e.,
522 /// the nearest common ancestor of the \#include tree.
525 /// The offset of the previous query in CommonFID.
527 /// Usually, this represents the location of the \#include for QueryFID, but
528 /// if LQueryFID is a parent of RQueryFID (or vice versa) then these can be a
529 /// random token in the parent.
530 unsigned LCommonOffset, RCommonOffset;
533 /// Return true if the currently cached values match up with
534 /// the specified LHS/RHS query.
536 /// If not, we can't use the cache.
537 bool isCacheValid(FileID LHS, FileID RHS) const {
538 return LQueryFID == LHS && RQueryFID == RHS;
541 /// If the cache is valid, compute the result given the
542 /// specified offsets in the LHS/RHS FileID's.
543 bool getCachedResult(unsigned LOffset, unsigned ROffset) const {
544 // If one of the query files is the common file, use the offset. Otherwise,
545 // use the #include loc in the common file.
546 if (LQueryFID != CommonFID) LOffset = LCommonOffset;
547 if (RQueryFID != CommonFID) ROffset = RCommonOffset;
549 // It is common for multiple macro expansions to be "included" from the same
550 // location (expansion location), in which case use the order of the FileIDs
551 // to determine which came first. This will also take care the case where
552 // one of the locations points at the inclusion/expansion point of the other
553 // in which case its FileID will come before the other.
554 if (LOffset == ROffset)
555 return IsLQFIDBeforeRQFID;
557 return LOffset < ROffset;
560 /// Set up a new query.
561 void setQueryFIDs(FileID LHS, FileID RHS, bool isLFIDBeforeRFID) {
565 IsLQFIDBeforeRQFID = isLFIDBeforeRFID;
569 LQueryFID = RQueryFID = FileID();
570 IsLQFIDBeforeRQFID = false;
573 void setCommonLoc(FileID commonFID, unsigned lCommonOffset,
574 unsigned rCommonOffset) {
575 CommonFID = commonFID;
576 LCommonOffset = lCommonOffset;
577 RCommonOffset = rCommonOffset;
581 /// The stack used when building modules on demand, which is used
582 /// to provide a link between the source managers of the different compiler
584 using ModuleBuildStack = ArrayRef<std::pair<std::string, FullSourceLoc>>;
586 /// This class handles loading and caching of source files into memory.
588 /// This object owns the MemoryBuffer objects for all of the loaded
589 /// files and assigns unique FileID's for each unique \#include chain.
591 /// The SourceManager can be queried for information about SourceLocation
592 /// objects, turning them into either spelling or expansion locations. Spelling
593 /// locations represent where the bytes corresponding to a token came from and
594 /// expansion locations represent where the location is in the user's view. In
595 /// the case of a macro expansion, for example, the spelling location indicates
596 /// where the expanded token came from and the expansion location specifies
597 /// where it was expanded.
598 class SourceManager : public RefCountedBase<SourceManager> {
599 /// DiagnosticsEngine object.
600 DiagnosticsEngine &Diag;
602 FileManager &FileMgr;
604 mutable llvm::BumpPtrAllocator ContentCacheAlloc;
606 /// Memoized information about all of the files tracked by this
609 /// This map allows us to merge ContentCache entries based
610 /// on their FileEntry*. All ContentCache objects will thus have unique,
611 /// non-null, FileEntry pointers.
612 llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*> FileInfos;
614 /// True if the ContentCache for files that are overridden by other
615 /// files, should report the original file name. Defaults to true.
616 bool OverridenFilesKeepOriginalName = true;
618 /// True if non-system source files should be treated as volatile
619 /// (likely to change while trying to use them). Defaults to false.
620 bool UserFilesAreVolatile;
622 /// True if all files read during this compilation should be treated
623 /// as transient (may not be present in later compilations using a module
624 /// file created from this compilation). Defaults to false.
625 bool FilesAreTransient = false;
627 struct OverriddenFilesInfoTy {
628 /// Files that have been overridden with the contents from another
630 llvm::DenseMap<const FileEntry *, const FileEntry *> OverriddenFiles;
632 /// Files that were overridden with a memory buffer.
633 llvm::DenseSet<const FileEntry *> OverriddenFilesWithBuffer;
636 /// Lazily create the object keeping overridden files info, since
637 /// it is uncommonly used.
638 std::unique_ptr<OverriddenFilesInfoTy> OverriddenFilesInfo;
640 OverriddenFilesInfoTy &getOverriddenFilesInfo() {
641 if (!OverriddenFilesInfo)
642 OverriddenFilesInfo.reset(new OverriddenFilesInfoTy);
643 return *OverriddenFilesInfo;
646 /// Information about various memory buffers that we have read in.
648 /// All FileEntry* within the stored ContentCache objects are NULL,
649 /// as they do not refer to a file.
650 std::vector<SrcMgr::ContentCache*> MemBufferInfos;
652 /// The table of SLocEntries that are local to this module.
654 /// Positive FileIDs are indexes into this table. Entry 0 indicates an invalid
656 SmallVector<SrcMgr::SLocEntry, 0> LocalSLocEntryTable;
658 /// The table of SLocEntries that are loaded from other modules.
660 /// Negative FileIDs are indexes into this table. To get from ID to an index,
662 mutable SmallVector<SrcMgr::SLocEntry, 0> LoadedSLocEntryTable;
664 /// The starting offset of the next local SLocEntry.
666 /// This is LocalSLocEntryTable.back().Offset + the size of that entry.
667 unsigned NextLocalOffset;
669 /// The starting offset of the latest batch of loaded SLocEntries.
671 /// This is LoadedSLocEntryTable.back().Offset, except that that entry might
672 /// not have been loaded, so that value would be unknown.
673 unsigned CurrentLoadedOffset;
675 /// The highest possible offset is 2^31-1, so CurrentLoadedOffset
677 static const unsigned MaxLoadedOffset = 1U << 31U;
679 /// A bitmap that indicates whether the entries of LoadedSLocEntryTable
680 /// have already been loaded from the external source.
682 /// Same indexing as LoadedSLocEntryTable.
683 llvm::BitVector SLocEntryLoaded;
685 /// An external source for source location entries.
686 ExternalSLocEntrySource *ExternalSLocEntries = nullptr;
688 /// A one-entry cache to speed up getFileID.
690 /// LastFileIDLookup records the last FileID looked up or created, because it
691 /// is very common to look up many tokens from the same file.
692 mutable FileID LastFileIDLookup;
694 /// Holds information for \#line directives.
696 /// This is referenced by indices from SLocEntryTable.
697 std::unique_ptr<LineTableInfo> LineTable;
699 /// These ivars serve as a cache used in the getLineNumber
700 /// method which is used to speedup getLineNumber calls to nearby locations.
701 mutable FileID LastLineNoFileIDQuery;
702 mutable SrcMgr::ContentCache *LastLineNoContentCache;
703 mutable unsigned LastLineNoFilePos;
704 mutable unsigned LastLineNoResult;
706 /// The file ID for the main source file of the translation unit.
709 /// The file ID for the precompiled preamble there is one.
710 FileID PreambleFileID;
712 // Statistics for -print-stats.
713 mutable unsigned NumLinearScans = 0;
714 mutable unsigned NumBinaryProbes = 0;
716 /// Associates a FileID with its "included/expanded in" decomposed
719 /// Used to cache results from and speed-up \c getDecomposedIncludedLoc
721 mutable llvm::DenseMap<FileID, std::pair<FileID, unsigned>> IncludedLocMap;
723 /// The key value into the IsBeforeInTUCache table.
724 using IsBeforeInTUCacheKey = std::pair<FileID, FileID>;
726 /// The IsBeforeInTranslationUnitCache is a mapping from FileID pairs
727 /// to cache results.
728 using InBeforeInTUCache =
729 llvm::DenseMap<IsBeforeInTUCacheKey, InBeforeInTUCacheEntry>;
731 /// Cache results for the isBeforeInTranslationUnit method.
732 mutable InBeforeInTUCache IBTUCache;
733 mutable InBeforeInTUCacheEntry IBTUCacheOverflow;
735 /// Return the cache entry for comparing the given file IDs
736 /// for isBeforeInTranslationUnit.
737 InBeforeInTUCacheEntry &getInBeforeInTUCache(FileID LFID, FileID RFID) const;
739 // Cache for the "fake" buffer used for error-recovery purposes.
740 mutable std::unique_ptr<llvm::MemoryBuffer> FakeBufferForRecovery;
742 mutable std::unique_ptr<SrcMgr::ContentCache> FakeContentCacheForRecovery;
744 /// Lazily computed map of macro argument chunks to their expanded
746 using MacroArgsMap = std::map<unsigned, SourceLocation>;
748 mutable llvm::DenseMap<FileID, std::unique_ptr<MacroArgsMap>>
751 /// The stack of modules being built, which is used to detect
752 /// cycles in the module dependency graph as modules are being built, as
753 /// well as to describe why we're rebuilding a particular module.
755 /// There is no way to set this value from the command line. If we ever need
756 /// to do so (e.g., if on-demand module construction moves out-of-process),
757 /// we can add a cc1-level option to do so.
758 SmallVector<std::pair<std::string, FullSourceLoc>, 2> StoredModuleBuildStack;
761 SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
762 bool UserFilesAreVolatile = false);
763 explicit SourceManager(const SourceManager &) = delete;
764 SourceManager &operator=(const SourceManager &) = delete;
767 void clearIDTables();
769 /// Initialize this source manager suitably to replay the compilation
770 /// described by \p Old. Requires that \p Old outlive \p *this.
771 void initializeForReplay(const SourceManager &Old);
773 DiagnosticsEngine &getDiagnostics() const { return Diag; }
775 FileManager &getFileManager() const { return FileMgr; }
777 /// Set true if the SourceManager should report the original file name
778 /// for contents of files that were overridden by other files. Defaults to
780 void setOverridenFilesKeepOriginalName(bool value) {
781 OverridenFilesKeepOriginalName = value;
784 /// True if non-system source files should be treated as volatile
785 /// (likely to change while trying to use them).
786 bool userFilesAreVolatile() const { return UserFilesAreVolatile; }
788 /// Retrieve the module build stack.
789 ModuleBuildStack getModuleBuildStack() const {
790 return StoredModuleBuildStack;
793 /// Set the module build stack.
794 void setModuleBuildStack(ModuleBuildStack stack) {
795 StoredModuleBuildStack.clear();
796 StoredModuleBuildStack.append(stack.begin(), stack.end());
799 /// Push an entry to the module build stack.
800 void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc) {
801 StoredModuleBuildStack.push_back(std::make_pair(moduleName.str(),importLoc));
804 //===--------------------------------------------------------------------===//
805 // MainFileID creation and querying methods.
806 //===--------------------------------------------------------------------===//
808 /// Returns the FileID of the main source file.
809 FileID getMainFileID() const { return MainFileID; }
811 /// Set the file ID for the main source file.
812 void setMainFileID(FileID FID) {
816 /// Returns true when the given FileEntry corresponds to the main file.
818 /// The main file should be set prior to calling this function.
819 bool isMainFile(FileEntryRef SourceFile);
821 /// Set the file ID for the precompiled preamble.
822 void setPreambleFileID(FileID Preamble) {
823 assert(PreambleFileID.isInvalid() && "PreambleFileID already set!");
824 PreambleFileID = Preamble;
827 /// Get the file ID for the precompiled preamble if there is one.
828 FileID getPreambleFileID() const { return PreambleFileID; }
830 //===--------------------------------------------------------------------===//
831 // Methods to create new FileID's and macro expansions.
832 //===--------------------------------------------------------------------===//
834 /// Create a new FileID that represents the specified file
835 /// being \#included from the specified IncludePosition.
837 /// This translates NULL into standard input.
838 FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos,
839 SrcMgr::CharacteristicKind FileCharacter,
840 int LoadedID = 0, unsigned LoadedOffset = 0);
842 FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos,
843 SrcMgr::CharacteristicKind FileCharacter,
844 int LoadedID = 0, unsigned LoadedOffset = 0);
846 /// Create a new FileID that represents the specified memory buffer.
848 /// This does no caching of the buffer and takes ownership of the
849 /// MemoryBuffer, so only pass a MemoryBuffer to this once.
850 FileID createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
851 SrcMgr::CharacteristicKind FileCharacter = SrcMgr::C_User,
852 int LoadedID = 0, unsigned LoadedOffset = 0,
853 SourceLocation IncludeLoc = SourceLocation());
855 enum UnownedTag { Unowned };
857 /// Create a new FileID that represents the specified memory buffer.
859 /// This does not take ownership of the MemoryBuffer. The memory buffer must
860 /// outlive the SourceManager.
861 FileID createFileID(UnownedTag, const llvm::MemoryBuffer *Buffer,
862 SrcMgr::CharacteristicKind FileCharacter = SrcMgr::C_User,
863 int LoadedID = 0, unsigned LoadedOffset = 0,
864 SourceLocation IncludeLoc = SourceLocation());
866 /// Get the FileID for \p SourceFile if it exists. Otherwise, create a
867 /// new FileID for the \p SourceFile.
868 FileID getOrCreateFileID(const FileEntry *SourceFile,
869 SrcMgr::CharacteristicKind FileCharacter);
871 /// Return a new SourceLocation that encodes the
872 /// fact that a token from SpellingLoc should actually be referenced from
873 /// ExpansionLoc, and that it represents the expansion of a macro argument
874 /// into the function-like macro body.
875 SourceLocation createMacroArgExpansionLoc(SourceLocation Loc,
876 SourceLocation ExpansionLoc,
879 /// Return a new SourceLocation that encodes the fact
880 /// that a token from SpellingLoc should actually be referenced from
882 SourceLocation createExpansionLoc(SourceLocation Loc,
883 SourceLocation ExpansionLocStart,
884 SourceLocation ExpansionLocEnd,
886 bool ExpansionIsTokenRange = true,
888 unsigned LoadedOffset = 0);
890 /// Return a new SourceLocation that encodes that the token starting
891 /// at \p TokenStart ends prematurely at \p TokenEnd.
892 SourceLocation createTokenSplitLoc(SourceLocation SpellingLoc,
893 SourceLocation TokenStart,
894 SourceLocation TokenEnd);
896 /// Retrieve the memory buffer associated with the given file.
898 /// \param Invalid If non-NULL, will be set \c true if an error
899 /// occurs while retrieving the memory buffer.
900 const llvm::MemoryBuffer *getMemoryBufferForFile(const FileEntry *File,
901 bool *Invalid = nullptr);
903 /// Override the contents of the given source file by providing an
904 /// already-allocated buffer.
906 /// \param SourceFile the source file whose contents will be overridden.
908 /// \param Buffer the memory buffer whose contents will be used as the
909 /// data in the given source file.
911 /// \param DoNotFree If true, then the buffer will not be freed when the
912 /// source manager is destroyed.
913 void overrideFileContents(const FileEntry *SourceFile,
914 llvm::MemoryBuffer *Buffer, bool DoNotFree);
915 void overrideFileContents(const FileEntry *SourceFile,
916 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
917 overrideFileContents(SourceFile, Buffer.release(), /*DoNotFree*/ false);
920 /// Override the given source file with another one.
922 /// \param SourceFile the source file which will be overridden.
924 /// \param NewFile the file whose contents will be used as the
925 /// data instead of the contents of the given source file.
926 void overrideFileContents(const FileEntry *SourceFile,
927 const FileEntry *NewFile);
929 /// Returns true if the file contents have been overridden.
930 bool isFileOverridden(const FileEntry *File) const {
931 if (OverriddenFilesInfo) {
932 if (OverriddenFilesInfo->OverriddenFilesWithBuffer.count(File))
934 if (OverriddenFilesInfo->OverriddenFiles.find(File) !=
935 OverriddenFilesInfo->OverriddenFiles.end())
941 /// Bypass the overridden contents of a file. This creates a new FileEntry
942 /// and initializes the content cache for it. Returns nullptr if there is no
943 /// such file in the filesystem.
945 /// This should be called before parsing has begun.
946 const FileEntry *bypassFileContentsOverride(const FileEntry &File);
948 /// Specify that a file is transient.
949 void setFileIsTransient(const FileEntry *SourceFile);
951 /// Specify that all files that are read during this compilation are
953 void setAllFilesAreTransient(bool Transient) {
954 FilesAreTransient = Transient;
957 //===--------------------------------------------------------------------===//
958 // FileID manipulation methods.
959 //===--------------------------------------------------------------------===//
961 /// Return the buffer for the specified FileID.
963 /// If there is an error opening this buffer the first time, this
964 /// manufactures a temporary buffer and returns a non-empty error string.
965 const llvm::MemoryBuffer *getBuffer(FileID FID, SourceLocation Loc,
966 bool *Invalid = nullptr) const {
967 bool MyInvalid = false;
968 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
969 if (MyInvalid || !Entry.isFile()) {
973 return getFakeBufferForRecovery();
976 return Entry.getFile().getContentCache()->getBuffer(Diag, getFileManager(),
980 const llvm::MemoryBuffer *getBuffer(FileID FID,
981 bool *Invalid = nullptr) const {
982 bool MyInvalid = false;
983 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
984 if (MyInvalid || !Entry.isFile()) {
988 return getFakeBufferForRecovery();
991 return Entry.getFile().getContentCache()->getBuffer(
992 Diag, getFileManager(), SourceLocation(), Invalid);
995 /// Returns the FileEntry record for the provided FileID.
996 const FileEntry *getFileEntryForID(FileID FID) const {
997 bool MyInvalid = false;
998 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
999 if (MyInvalid || !Entry.isFile())
1002 const SrcMgr::ContentCache *Content = Entry.getFile().getContentCache();
1005 return Content->OrigEntry;
1008 /// Returns the FileEntryRef for the provided FileID.
1009 Optional<FileEntryRef> getFileEntryRefForID(FileID FID) const;
1011 /// Returns the FileEntry record for the provided SLocEntry.
1012 const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const
1014 const SrcMgr::ContentCache *Content = sloc.getFile().getContentCache();
1017 return Content->OrigEntry;
1020 /// Return a StringRef to the source buffer data for the
1021 /// specified FileID.
1023 /// \param FID The file ID whose contents will be returned.
1024 /// \param Invalid If non-NULL, will be set true if an error occurred.
1025 StringRef getBufferData(FileID FID, bool *Invalid = nullptr) const;
1027 /// Get the number of FileIDs (files and macros) that were created
1028 /// during preprocessing of \p FID, including it.
1029 unsigned getNumCreatedFIDsForFileID(FileID FID) const {
1030 bool Invalid = false;
1031 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1032 if (Invalid || !Entry.isFile())
1035 return Entry.getFile().NumCreatedFIDs;
1038 /// Set the number of FileIDs (files and macros) that were created
1039 /// during preprocessing of \p FID, including it.
1040 void setNumCreatedFIDsForFileID(FileID FID, unsigned NumFIDs,
1041 bool Force = false) const {
1042 bool Invalid = false;
1043 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1044 if (Invalid || !Entry.isFile())
1047 assert((Force || Entry.getFile().NumCreatedFIDs == 0) && "Already set!");
1048 const_cast<SrcMgr::FileInfo &>(Entry.getFile()).NumCreatedFIDs = NumFIDs;
1051 //===--------------------------------------------------------------------===//
1052 // SourceLocation manipulation methods.
1053 //===--------------------------------------------------------------------===//
1055 /// Return the FileID for a SourceLocation.
1057 /// This is a very hot method that is used for all SourceManager queries
1058 /// that start with a SourceLocation object. It is responsible for finding
1059 /// the entry in SLocEntryTable which contains the specified location.
1061 FileID getFileID(SourceLocation SpellingLoc) const {
1062 unsigned SLocOffset = SpellingLoc.getOffset();
1064 // If our one-entry cache covers this offset, just return it.
1065 if (isOffsetInFileID(LastFileIDLookup, SLocOffset))
1066 return LastFileIDLookup;
1068 return getFileIDSlow(SLocOffset);
1071 /// Return the filename of the file containing a SourceLocation.
1072 StringRef getFilename(SourceLocation SpellingLoc) const;
1074 /// Return the source location corresponding to the first byte of
1075 /// the specified file.
1076 SourceLocation getLocForStartOfFile(FileID FID) const {
1077 bool Invalid = false;
1078 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1079 if (Invalid || !Entry.isFile())
1080 return SourceLocation();
1082 unsigned FileOffset = Entry.getOffset();
1083 return SourceLocation::getFileLoc(FileOffset);
1086 /// Return the source location corresponding to the last byte of the
1088 SourceLocation getLocForEndOfFile(FileID FID) const {
1089 bool Invalid = false;
1090 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1091 if (Invalid || !Entry.isFile())
1092 return SourceLocation();
1094 unsigned FileOffset = Entry.getOffset();
1095 return SourceLocation::getFileLoc(FileOffset + getFileIDSize(FID));
1098 /// Returns the include location if \p FID is a \#include'd file
1099 /// otherwise it returns an invalid location.
1100 SourceLocation getIncludeLoc(FileID FID) const {
1101 bool Invalid = false;
1102 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1103 if (Invalid || !Entry.isFile())
1104 return SourceLocation();
1106 return Entry.getFile().getIncludeLoc();
1109 // Returns the import location if the given source location is
1110 // located within a module, or an invalid location if the source location
1111 // is within the current translation unit.
1112 std::pair<SourceLocation, StringRef>
1113 getModuleImportLoc(SourceLocation Loc) const {
1114 FileID FID = getFileID(Loc);
1116 // Positive file IDs are in the current translation unit, and -1 is a
1119 return std::make_pair(SourceLocation(), "");
1121 return ExternalSLocEntries->getModuleImportLoc(FID.ID);
1124 /// Given a SourceLocation object \p Loc, return the expansion
1125 /// location referenced by the ID.
1126 SourceLocation getExpansionLoc(SourceLocation Loc) const {
1127 // Handle the non-mapped case inline, defer to out of line code to handle
1129 if (Loc.isFileID()) return Loc;
1130 return getExpansionLocSlowCase(Loc);
1133 /// Given \p Loc, if it is a macro location return the expansion
1134 /// location or the spelling location, depending on if it comes from a
1135 /// macro argument or not.
1136 SourceLocation getFileLoc(SourceLocation Loc) const {
1137 if (Loc.isFileID()) return Loc;
1138 return getFileLocSlowCase(Loc);
1141 /// Return the start/end of the expansion information for an
1142 /// expansion location.
1144 /// \pre \p Loc is required to be an expansion location.
1145 CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const;
1147 /// Given a SourceLocation object, return the range of
1148 /// tokens covered by the expansion in the ultimate file.
1149 CharSourceRange getExpansionRange(SourceLocation Loc) const;
1151 /// Given a SourceRange object, return the range of
1152 /// tokens or characters covered by the expansion in the ultimate file.
1153 CharSourceRange getExpansionRange(SourceRange Range) const {
1154 SourceLocation Begin = getExpansionRange(Range.getBegin()).getBegin();
1155 CharSourceRange End = getExpansionRange(Range.getEnd());
1156 return CharSourceRange(SourceRange(Begin, End.getEnd()),
1157 End.isTokenRange());
1160 /// Given a CharSourceRange object, return the range of
1161 /// tokens or characters covered by the expansion in the ultimate file.
1162 CharSourceRange getExpansionRange(CharSourceRange Range) const {
1163 CharSourceRange Expansion = getExpansionRange(Range.getAsRange());
1164 if (Expansion.getEnd() == Range.getEnd())
1165 Expansion.setTokenRange(Range.isTokenRange());
1169 /// Given a SourceLocation object, return the spelling
1170 /// location referenced by the ID.
1172 /// This is the place where the characters that make up the lexed token
1174 SourceLocation getSpellingLoc(SourceLocation Loc) const {
1175 // Handle the non-mapped case inline, defer to out of line code to handle
1177 if (Loc.isFileID()) return Loc;
1178 return getSpellingLocSlowCase(Loc);
1181 /// Given a SourceLocation object, return the spelling location
1182 /// referenced by the ID.
1184 /// This is the first level down towards the place where the characters
1185 /// that make up the lexed token can be found. This should not generally
1186 /// be used by clients.
1187 SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const;
1189 /// Form a SourceLocation from a FileID and Offset pair.
1190 SourceLocation getComposedLoc(FileID FID, unsigned Offset) const {
1191 bool Invalid = false;
1192 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1194 return SourceLocation();
1196 unsigned GlobalOffset = Entry.getOffset() + Offset;
1197 return Entry.isFile() ? SourceLocation::getFileLoc(GlobalOffset)
1198 : SourceLocation::getMacroLoc(GlobalOffset);
1201 /// Decompose the specified location into a raw FileID + Offset pair.
1203 /// The first element is the FileID, the second is the offset from the
1204 /// start of the buffer of the location.
1205 std::pair<FileID, unsigned> getDecomposedLoc(SourceLocation Loc) const {
1206 FileID FID = getFileID(Loc);
1207 bool Invalid = false;
1208 const SrcMgr::SLocEntry &E = getSLocEntry(FID, &Invalid);
1210 return std::make_pair(FileID(), 0);
1211 return std::make_pair(FID, Loc.getOffset()-E.getOffset());
1214 /// Decompose the specified location into a raw FileID + Offset pair.
1216 /// If the location is an expansion record, walk through it until we find
1217 /// the final location expanded.
1218 std::pair<FileID, unsigned>
1219 getDecomposedExpansionLoc(SourceLocation Loc) const {
1220 FileID FID = getFileID(Loc);
1221 bool Invalid = false;
1222 const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
1224 return std::make_pair(FileID(), 0);
1226 unsigned Offset = Loc.getOffset()-E->getOffset();
1228 return std::make_pair(FID, Offset);
1230 return getDecomposedExpansionLocSlowCase(E);
1233 /// Decompose the specified location into a raw FileID + Offset pair.
1235 /// If the location is an expansion record, walk through it until we find
1236 /// its spelling record.
1237 std::pair<FileID, unsigned>
1238 getDecomposedSpellingLoc(SourceLocation Loc) const {
1239 FileID FID = getFileID(Loc);
1240 bool Invalid = false;
1241 const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
1243 return std::make_pair(FileID(), 0);
1245 unsigned Offset = Loc.getOffset()-E->getOffset();
1247 return std::make_pair(FID, Offset);
1248 return getDecomposedSpellingLocSlowCase(E, Offset);
1251 /// Returns the "included/expanded in" decomposed location of the given
1253 std::pair<FileID, unsigned> getDecomposedIncludedLoc(FileID FID) const;
1255 /// Returns the offset from the start of the file that the
1256 /// specified SourceLocation represents.
1258 /// This is not very meaningful for a macro ID.
1259 unsigned getFileOffset(SourceLocation SpellingLoc) const {
1260 return getDecomposedLoc(SpellingLoc).second;
1263 /// Tests whether the given source location represents a macro
1264 /// argument's expansion into the function-like macro definition.
1266 /// \param StartLoc If non-null and function returns true, it is set to the
1267 /// start location of the macro argument expansion.
1269 /// Such source locations only appear inside of the expansion
1270 /// locations representing where a particular function-like macro was
1272 bool isMacroArgExpansion(SourceLocation Loc,
1273 SourceLocation *StartLoc = nullptr) const;
1275 /// Tests whether the given source location represents the expansion of
1278 /// This is equivalent to testing whether the location is part of a macro
1279 /// expansion but not the expansion of an argument to a function-like macro.
1280 bool isMacroBodyExpansion(SourceLocation Loc) const;
1282 /// Returns true if the given MacroID location points at the beginning
1283 /// of the immediate macro expansion.
1285 /// \param MacroBegin If non-null and function returns true, it is set to the
1286 /// begin location of the immediate macro expansion.
1287 bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1288 SourceLocation *MacroBegin = nullptr) const;
1290 /// Returns true if the given MacroID location points at the character
1291 /// end of the immediate macro expansion.
1293 /// \param MacroEnd If non-null and function returns true, it is set to the
1294 /// character end location of the immediate macro expansion.
1296 isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1297 SourceLocation *MacroEnd = nullptr) const;
1299 /// Returns true if \p Loc is inside the [\p Start, +\p Length)
1300 /// chunk of the source location address space.
1302 /// If it's true and \p RelativeOffset is non-null, it will be set to the
1303 /// relative offset of \p Loc inside the chunk.
1304 bool isInSLocAddrSpace(SourceLocation Loc,
1305 SourceLocation Start, unsigned Length,
1306 unsigned *RelativeOffset = nullptr) const {
1307 assert(((Start.getOffset() < NextLocalOffset &&
1308 Start.getOffset()+Length <= NextLocalOffset) ||
1309 (Start.getOffset() >= CurrentLoadedOffset &&
1310 Start.getOffset()+Length < MaxLoadedOffset)) &&
1311 "Chunk is not valid SLoc address space");
1312 unsigned LocOffs = Loc.getOffset();
1313 unsigned BeginOffs = Start.getOffset();
1314 unsigned EndOffs = BeginOffs + Length;
1315 if (LocOffs >= BeginOffs && LocOffs < EndOffs) {
1317 *RelativeOffset = LocOffs - BeginOffs;
1324 /// Return true if both \p LHS and \p RHS are in the local source
1325 /// location address space or the loaded one.
1327 /// If it's true and \p RelativeOffset is non-null, it will be set to the
1328 /// offset of \p RHS relative to \p LHS.
1329 bool isInSameSLocAddrSpace(SourceLocation LHS, SourceLocation RHS,
1330 int *RelativeOffset) const {
1331 unsigned LHSOffs = LHS.getOffset(), RHSOffs = RHS.getOffset();
1332 bool LHSLoaded = LHSOffs >= CurrentLoadedOffset;
1333 bool RHSLoaded = RHSOffs >= CurrentLoadedOffset;
1335 if (LHSLoaded == RHSLoaded) {
1337 *RelativeOffset = RHSOffs - LHSOffs;
1344 //===--------------------------------------------------------------------===//
1345 // Queries about the code at a SourceLocation.
1346 //===--------------------------------------------------------------------===//
1348 /// Return a pointer to the start of the specified location
1349 /// in the appropriate spelling MemoryBuffer.
1351 /// \param Invalid If non-NULL, will be set \c true if an error occurs.
1352 const char *getCharacterData(SourceLocation SL,
1353 bool *Invalid = nullptr) const;
1355 /// Return the column # for the specified file position.
1357 /// This is significantly cheaper to compute than the line number. This
1358 /// returns zero if the column number isn't known. This may only be called
1359 /// on a file sloc, so you must choose a spelling or expansion location
1360 /// before calling this method.
1361 unsigned getColumnNumber(FileID FID, unsigned FilePos,
1362 bool *Invalid = nullptr) const;
1363 unsigned getSpellingColumnNumber(SourceLocation Loc,
1364 bool *Invalid = nullptr) const;
1365 unsigned getExpansionColumnNumber(SourceLocation Loc,
1366 bool *Invalid = nullptr) const;
1367 unsigned getPresumedColumnNumber(SourceLocation Loc,
1368 bool *Invalid = nullptr) const;
1370 /// Given a SourceLocation, return the spelling line number
1371 /// for the position indicated.
1373 /// This requires building and caching a table of line offsets for the
1374 /// MemoryBuffer, so this is not cheap: use only when about to emit a
1376 unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid = nullptr) const;
1377 unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
1378 unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
1379 unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
1381 /// Return the filename or buffer identifier of the buffer the
1384 /// Note that this name does not respect \#line directives. Use
1385 /// getPresumedLoc for normal clients.
1386 StringRef getBufferName(SourceLocation Loc, bool *Invalid = nullptr) const;
1388 /// Return the file characteristic of the specified source
1389 /// location, indicating whether this is a normal file, a system
1390 /// header, or an "implicit extern C" system header.
1392 /// This state can be modified with flags on GNU linemarker directives like:
1396 /// which changes all source locations in the current file after that to be
1397 /// considered to be from a system header.
1398 SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const;
1400 /// Returns the "presumed" location of a SourceLocation specifies.
1402 /// A "presumed location" can be modified by \#line or GNU line marker
1403 /// directives. This provides a view on the data that a user should see
1404 /// in diagnostics, for example.
1406 /// Note that a presumed location is always given as the expansion point of
1407 /// an expansion location, not at the spelling location.
1409 /// \returns The presumed location of the specified SourceLocation. If the
1410 /// presumed location cannot be calculated (e.g., because \p Loc is invalid
1411 /// or the file containing \p Loc has changed on disk), returns an invalid
1412 /// presumed location.
1413 PresumedLoc getPresumedLoc(SourceLocation Loc,
1414 bool UseLineDirectives = true) const;
1416 /// Returns whether the PresumedLoc for a given SourceLocation is
1417 /// in the main file.
1419 /// This computes the "presumed" location for a SourceLocation, then checks
1420 /// whether it came from a file other than the main file. This is different
1421 /// from isWrittenInMainFile() because it takes line marker directives into
1423 bool isInMainFile(SourceLocation Loc) const;
1425 /// Returns true if the spelling locations for both SourceLocations
1426 /// are part of the same file buffer.
1428 /// This check ignores line marker directives.
1429 bool isWrittenInSameFile(SourceLocation Loc1, SourceLocation Loc2) const {
1430 return getFileID(Loc1) == getFileID(Loc2);
1433 /// Returns true if the spelling location for the given location
1434 /// is in the main file buffer.
1436 /// This check ignores line marker directives.
1437 bool isWrittenInMainFile(SourceLocation Loc) const {
1438 return getFileID(Loc) == getMainFileID();
1441 /// Returns whether \p Loc is located in a <built-in> file.
1442 bool isWrittenInBuiltinFile(SourceLocation Loc) const {
1443 StringRef Filename(getPresumedLoc(Loc).getFilename());
1444 return Filename.equals("<built-in>");
1447 /// Returns whether \p Loc is located in a <command line> file.
1448 bool isWrittenInCommandLineFile(SourceLocation Loc) const {
1449 StringRef Filename(getPresumedLoc(Loc).getFilename());
1450 return Filename.equals("<command line>");
1453 /// Returns whether \p Loc is located in a <scratch space> file.
1454 bool isWrittenInScratchSpace(SourceLocation Loc) const {
1455 StringRef Filename(getPresumedLoc(Loc).getFilename());
1456 return Filename.equals("<scratch space>");
1459 /// Returns if a SourceLocation is in a system header.
1460 bool isInSystemHeader(SourceLocation Loc) const {
1461 return isSystem(getFileCharacteristic(Loc));
1464 /// Returns if a SourceLocation is in an "extern C" system header.
1465 bool isInExternCSystemHeader(SourceLocation Loc) const {
1466 return getFileCharacteristic(Loc) == SrcMgr::C_ExternCSystem;
1469 /// Returns whether \p Loc is expanded from a macro in a system header.
1470 bool isInSystemMacro(SourceLocation loc) const {
1471 if (!loc.isMacroID())
1474 // This happens when the macro is the result of a paste, in that case
1475 // its spelling is the scratch memory, so we take the parent context.
1476 // There can be several level of token pasting.
1477 if (isWrittenInScratchSpace(getSpellingLoc(loc))) {
1479 loc = getImmediateMacroCallerLoc(loc);
1480 } while (isWrittenInScratchSpace(getSpellingLoc(loc)));
1481 return isInSystemMacro(loc);
1484 return isInSystemHeader(getSpellingLoc(loc));
1487 /// The size of the SLocEntry that \p FID represents.
1488 unsigned getFileIDSize(FileID FID) const;
1490 /// Given a specific FileID, returns true if \p Loc is inside that
1491 /// FileID chunk and sets relative offset (offset of \p Loc from beginning
1492 /// of FileID) to \p relativeOffset.
1493 bool isInFileID(SourceLocation Loc, FileID FID,
1494 unsigned *RelativeOffset = nullptr) const {
1495 unsigned Offs = Loc.getOffset();
1496 if (isOffsetInFileID(FID, Offs)) {
1498 *RelativeOffset = Offs - getSLocEntry(FID).getOffset();
1505 //===--------------------------------------------------------------------===//
1506 // Line Table Manipulation Routines
1507 //===--------------------------------------------------------------------===//
1509 /// Return the uniqued ID for the specified filename.
1510 unsigned getLineTableFilenameID(StringRef Str);
1512 /// Add a line note to the line table for the FileID and offset
1513 /// specified by Loc.
1515 /// If FilenameID is -1, it is considered to be unspecified.
1516 void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID,
1517 bool IsFileEntry, bool IsFileExit,
1518 SrcMgr::CharacteristicKind FileKind);
1520 /// Determine if the source manager has a line table.
1521 bool hasLineTable() const { return LineTable != nullptr; }
1523 /// Retrieve the stored line table.
1524 LineTableInfo &getLineTable();
1526 //===--------------------------------------------------------------------===//
1527 // Queries for performance analysis.
1528 //===--------------------------------------------------------------------===//
1530 /// Return the total amount of physical memory allocated by the
1531 /// ContentCache allocator.
1532 size_t getContentCacheSize() const {
1533 return ContentCacheAlloc.getTotalMemory();
1536 struct MemoryBufferSizes {
1537 const size_t malloc_bytes;
1538 const size_t mmap_bytes;
1540 MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
1541 : malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
1544 /// Return the amount of memory used by memory buffers, breaking down
1545 /// by heap-backed versus mmap'ed memory.
1546 MemoryBufferSizes getMemoryBufferSizes() const;
1548 /// Return the amount of memory used for various side tables and
1549 /// data structures in the SourceManager.
1550 size_t getDataStructureSizes() const;
1552 //===--------------------------------------------------------------------===//
1553 // Other miscellaneous methods.
1554 //===--------------------------------------------------------------------===//
1556 /// Get the source location for the given file:line:col triplet.
1558 /// If the source file is included multiple times, the source location will
1559 /// be based upon the first inclusion.
1560 SourceLocation translateFileLineCol(const FileEntry *SourceFile,
1561 unsigned Line, unsigned Col) const;
1563 /// Get the FileID for the given file.
1565 /// If the source file is included multiple times, the FileID will be the
1566 /// first inclusion.
1567 FileID translateFile(const FileEntry *SourceFile) const;
1569 /// Get the source location in \p FID for the given line:col.
1570 /// Returns null location if \p FID is not a file SLocEntry.
1571 SourceLocation translateLineCol(FileID FID,
1572 unsigned Line, unsigned Col) const;
1574 /// If \p Loc points inside a function macro argument, the returned
1575 /// location will be the macro location in which the argument was expanded.
1576 /// If a macro argument is used multiple times, the expanded location will
1577 /// be at the first expansion of the argument.
1581 /// Passing a file location pointing at 'foo', will yield a macro location
1582 /// where 'foo' was expanded into.
1583 SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const;
1585 /// Determines the order of 2 source locations in the translation unit.
1587 /// \returns true if LHS source location comes before RHS, false otherwise.
1588 bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const;
1590 /// Determines whether the two decomposed source location is in the
1591 /// same translation unit. As a byproduct, it also calculates the order
1592 /// of the source locations in case they are in the same TU.
1594 /// \returns Pair of bools the first component is true if the two locations
1595 /// are in the same TU. The second bool is true if the first is true
1596 /// and \p LOffs is before \p ROffs.
1597 std::pair<bool, bool>
1598 isInTheSameTranslationUnit(std::pair<FileID, unsigned> &LOffs,
1599 std::pair<FileID, unsigned> &ROffs) const;
1601 /// Determines the order of 2 source locations in the "source location
1603 bool isBeforeInSLocAddrSpace(SourceLocation LHS, SourceLocation RHS) const {
1604 return isBeforeInSLocAddrSpace(LHS, RHS.getOffset());
1607 /// Determines the order of a source location and a source location
1608 /// offset in the "source location address space".
1610 /// Note that we always consider source locations loaded from
1611 bool isBeforeInSLocAddrSpace(SourceLocation LHS, unsigned RHS) const {
1612 unsigned LHSOffset = LHS.getOffset();
1613 bool LHSLoaded = LHSOffset >= CurrentLoadedOffset;
1614 bool RHSLoaded = RHS >= CurrentLoadedOffset;
1615 if (LHSLoaded == RHSLoaded)
1616 return LHSOffset < RHS;
1621 /// Return true if the Point is within Start and End.
1622 bool isPointWithin(SourceLocation Location, SourceLocation Start,
1623 SourceLocation End) const {
1624 return Location == Start || Location == End ||
1625 (isBeforeInTranslationUnit(Start, Location) &&
1626 isBeforeInTranslationUnit(Location, End));
1629 // Iterators over FileInfos.
1630 using fileinfo_iterator =
1631 llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::const_iterator;
1633 fileinfo_iterator fileinfo_begin() const { return FileInfos.begin(); }
1634 fileinfo_iterator fileinfo_end() const { return FileInfos.end(); }
1635 bool hasFileInfo(const FileEntry *File) const {
1636 return FileInfos.find(File) != FileInfos.end();
1639 /// Print statistics to stderr.
1640 void PrintStats() const;
1644 /// Get the number of local SLocEntries we have.
1645 unsigned local_sloc_entry_size() const { return LocalSLocEntryTable.size(); }
1647 /// Get a local SLocEntry. This is exposed for indexing.
1648 const SrcMgr::SLocEntry &getLocalSLocEntry(unsigned Index) const {
1649 assert(Index < LocalSLocEntryTable.size() && "Invalid index");
1650 return LocalSLocEntryTable[Index];
1653 /// Get the number of loaded SLocEntries we have.
1654 unsigned loaded_sloc_entry_size() const { return LoadedSLocEntryTable.size();}
1656 /// Get a loaded SLocEntry. This is exposed for indexing.
1657 const SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index,
1658 bool *Invalid = nullptr) const {
1659 assert(Index < LoadedSLocEntryTable.size() && "Invalid index");
1660 if (SLocEntryLoaded[Index])
1661 return LoadedSLocEntryTable[Index];
1662 return loadSLocEntry(Index, Invalid);
1665 const SrcMgr::SLocEntry &getSLocEntry(FileID FID,
1666 bool *Invalid = nullptr) const {
1667 if (FID.ID == 0 || FID.ID == -1) {
1668 if (Invalid) *Invalid = true;
1669 return LocalSLocEntryTable[0];
1671 return getSLocEntryByID(FID.ID, Invalid);
1674 unsigned getNextLocalOffset() const { return NextLocalOffset; }
1676 void setExternalSLocEntrySource(ExternalSLocEntrySource *Source) {
1677 assert(LoadedSLocEntryTable.empty() &&
1678 "Invalidating existing loaded entries");
1679 ExternalSLocEntries = Source;
1682 /// Allocate a number of loaded SLocEntries, which will be actually
1683 /// loaded on demand from the external source.
1685 /// NumSLocEntries will be allocated, which occupy a total of TotalSize space
1686 /// in the global source view. The lowest ID and the base offset of the
1687 /// entries will be returned.
1688 std::pair<int, unsigned>
1689 AllocateLoadedSLocEntries(unsigned NumSLocEntries, unsigned TotalSize);
1691 /// Returns true if \p Loc came from a PCH/Module.
1692 bool isLoadedSourceLocation(SourceLocation Loc) const {
1693 return Loc.getOffset() >= CurrentLoadedOffset;
1696 /// Returns true if \p Loc did not come from a PCH/Module.
1697 bool isLocalSourceLocation(SourceLocation Loc) const {
1698 return Loc.getOffset() < NextLocalOffset;
1701 /// Returns true if \p FID came from a PCH/Module.
1702 bool isLoadedFileID(FileID FID) const {
1703 assert(FID.ID != -1 && "Using FileID sentinel value");
1707 /// Returns true if \p FID did not come from a PCH/Module.
1708 bool isLocalFileID(FileID FID) const {
1709 return !isLoadedFileID(FID);
1712 /// Gets the location of the immediate macro caller, one level up the stack
1713 /// toward the initial macro typed into the source.
1714 SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const {
1715 if (!Loc.isMacroID()) return Loc;
1717 // When we have the location of (part of) an expanded parameter, its
1718 // spelling location points to the argument as expanded in the macro call,
1719 // and therefore is used to locate the macro caller.
1720 if (isMacroArgExpansion(Loc))
1721 return getImmediateSpellingLoc(Loc);
1723 // Otherwise, the caller of the macro is located where this macro is
1724 // expanded (while the spelling is part of the macro definition).
1725 return getImmediateExpansionRange(Loc).getBegin();
1728 /// \return Location of the top-level macro caller.
1729 SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const;
1732 friend class ASTReader;
1733 friend class ASTWriter;
1735 llvm::MemoryBuffer *getFakeBufferForRecovery() const;
1736 const SrcMgr::ContentCache *getFakeContentCacheForRecovery() const;
1738 const SrcMgr::SLocEntry &loadSLocEntry(unsigned Index, bool *Invalid) const;
1740 /// Get the entry with the given unwrapped FileID.
1741 /// Invalid will not be modified for Local IDs.
1742 const SrcMgr::SLocEntry &getSLocEntryByID(int ID,
1743 bool *Invalid = nullptr) const {
1744 assert(ID != -1 && "Using FileID sentinel value");
1746 return getLoadedSLocEntryByID(ID, Invalid);
1747 return getLocalSLocEntry(static_cast<unsigned>(ID));
1750 const SrcMgr::SLocEntry &
1751 getLoadedSLocEntryByID(int ID, bool *Invalid = nullptr) const {
1752 return getLoadedSLocEntry(static_cast<unsigned>(-ID - 2), Invalid);
1755 /// Implements the common elements of storing an expansion info struct into
1756 /// the SLocEntry table and producing a source location that refers to it.
1757 SourceLocation createExpansionLocImpl(const SrcMgr::ExpansionInfo &Expansion,
1760 unsigned LoadedOffset = 0);
1762 /// Return true if the specified FileID contains the
1763 /// specified SourceLocation offset. This is a very hot method.
1764 inline bool isOffsetInFileID(FileID FID, unsigned SLocOffset) const {
1765 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID);
1766 // If the entry is after the offset, it can't contain it.
1767 if (SLocOffset < Entry.getOffset()) return false;
1769 // If this is the very last entry then it does.
1773 // If it is the last local entry, then it does if the location is local.
1774 if (FID.ID+1 == static_cast<int>(LocalSLocEntryTable.size()))
1775 return SLocOffset < NextLocalOffset;
1777 // Otherwise, the entry after it has to not include it. This works for both
1778 // local and loaded entries.
1779 return SLocOffset < getSLocEntryByID(FID.ID+1).getOffset();
1782 /// Returns the previous in-order FileID or an invalid FileID if there
1783 /// is no previous one.
1784 FileID getPreviousFileID(FileID FID) const;
1786 /// Returns the next in-order FileID or an invalid FileID if there is
1788 FileID getNextFileID(FileID FID) const;
1790 /// Create a new fileID for the specified ContentCache and
1791 /// include position.
1793 /// This works regardless of whether the ContentCache corresponds to a
1794 /// file or some other input source.
1795 FileID createFileID(const SrcMgr::ContentCache *File, StringRef Filename,
1796 SourceLocation IncludePos,
1797 SrcMgr::CharacteristicKind DirCharacter, int LoadedID,
1798 unsigned LoadedOffset);
1800 const SrcMgr::ContentCache *
1801 getOrCreateContentCache(const FileEntry *SourceFile,
1802 bool isSystemFile = false);
1804 /// Create a new ContentCache for the specified memory buffer.
1805 const SrcMgr::ContentCache *
1806 createMemBufferContentCache(const llvm::MemoryBuffer *Buf, bool DoNotFree);
1808 FileID getFileIDSlow(unsigned SLocOffset) const;
1809 FileID getFileIDLocal(unsigned SLocOffset) const;
1810 FileID getFileIDLoaded(unsigned SLocOffset) const;
1812 SourceLocation getExpansionLocSlowCase(SourceLocation Loc) const;
1813 SourceLocation getSpellingLocSlowCase(SourceLocation Loc) const;
1814 SourceLocation getFileLocSlowCase(SourceLocation Loc) const;
1816 std::pair<FileID, unsigned>
1817 getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry *E) const;
1818 std::pair<FileID, unsigned>
1819 getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
1820 unsigned Offset) const;
1821 void computeMacroArgsCache(MacroArgsMap &MacroArgsCache, FileID FID) const;
1822 void associateFileChunkWithMacroArgExp(MacroArgsMap &MacroArgsCache,
1824 SourceLocation SpellLoc,
1825 SourceLocation ExpansionLoc,
1826 unsigned ExpansionLength) const;
1829 /// Comparison function object.
1830 template<typename T>
1831 class BeforeThanCompare;
1833 /// Compare two source locations.
1835 class BeforeThanCompare<SourceLocation> {
1839 explicit BeforeThanCompare(SourceManager &SM) : SM(SM) {}
1841 bool operator()(SourceLocation LHS, SourceLocation RHS) const {
1842 return SM.isBeforeInTranslationUnit(LHS, RHS);
1846 /// Compare two non-overlapping source ranges.
1848 class BeforeThanCompare<SourceRange> {
1852 explicit BeforeThanCompare(SourceManager &SM) : SM(SM) {}
1854 bool operator()(SourceRange LHS, SourceRange RHS) const {
1855 return SM.isBeforeInTranslationUnit(LHS.getBegin(), RHS.getBegin());
1859 /// SourceManager and necessary depdencies (e.g. VFS, FileManager) for a single
1860 /// in-memorty file.
1861 class SourceManagerForFile {
1863 /// Creates SourceManager and necessary depdencies (e.g. VFS, FileManager).
1864 /// The main file in the SourceManager will be \p FileName with \p Content.
1865 SourceManagerForFile(StringRef FileName, StringRef Content);
1867 SourceManager &get() {
1873 // The order of these fields are important - they should be in the same order
1874 // as they are created in `createSourceManagerForFile` so that they can be
1875 // deleted in the reverse order as they are created.
1876 std::unique_ptr<FileManager> FileMgr;
1877 std::unique_ptr<DiagnosticsEngine> Diagnostics;
1878 std::unique_ptr<SourceManager> SourceMgr;
1881 } // namespace clang
1883 #endif // LLVM_CLANG_BASIC_SOURCEMANAGER_H