1 //===--- SourceManager.h - Track and cache source files ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Defines the SourceManager interface.
13 /// There are three different types of locations in a %file: a spelling
14 /// location, an expansion location, and a presumed location.
16 /// Given an example of:
18 /// #define min(x, y) x < y ? x : y
21 /// and then later on a use of min:
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.
33 //===----------------------------------------------------------------------===//
35 #ifndef LLVM_CLANG_SOURCEMANAGER_H
36 #define LLVM_CLANG_SOURCEMANAGER_H
38 #include "clang/Basic/FileManager.h"
39 #include "clang/Basic/LLVM.h"
40 #include "clang/Basic/SourceLocation.h"
41 #include "llvm/ADT/ArrayRef.h"
42 #include "llvm/ADT/DenseMap.h"
43 #include "llvm/ADT/DenseSet.h"
44 #include "llvm/ADT/IntrusiveRefCntPtr.h"
45 #include "llvm/ADT/PointerIntPair.h"
46 #include "llvm/ADT/PointerUnion.h"
47 #include "llvm/Support/AlignOf.h"
48 #include "llvm/Support/Allocator.h"
49 #include "llvm/Support/DataTypes.h"
50 #include "llvm/Support/MemoryBuffer.h"
58 class DiagnosticsEngine;
67 /// \brief Public enums and private classes that are part of the
68 /// SourceManager implementation.
71 /// \brief Indicates whether a file or directory holds normal user code,
72 /// system code, or system code which is implicitly 'extern "C"' in C++ mode.
74 /// Entire directories can be tagged with this (this is maintained by
75 /// DirectoryLookup and friends) as can specific FileInfos when a \#pragma
76 /// system_header is seen or in various other cases.
78 enum CharacteristicKind {
79 C_User, C_System, C_ExternCSystem
82 /// \brief One instance of this struct is kept for every file loaded or used.
84 /// This object owns the MemoryBuffer object.
87 /// \brief Whether the buffer is invalid.
89 /// \brief Whether the buffer should not be freed on destruction.
93 // Note that the first member of this class is an aligned character buffer
94 // to ensure that this class has an alignment of 8 bytes. This wastes
95 // 8 bytes for every ContentCache object, but each of these corresponds to
96 // a file loaded into memory, so the 8 bytes doesn't seem terribly
97 // important. It is quite awkward to fit this aligner into any other part
98 // of the class due to the lack of portable ways to combine it with other
100 llvm::AlignedCharArray<8, 1> NonceAligner;
102 /// \brief The actual buffer containing the characters from the input
105 /// This is owned by the ContentCache object. The bits indicate
106 /// whether the buffer is invalid.
107 mutable llvm::PointerIntPair<const llvm::MemoryBuffer *, 2> Buffer;
110 /// \brief Reference to the file entry representing this ContentCache.
112 /// This reference does not own the FileEntry object.
114 /// It is possible for this to be NULL if the ContentCache encapsulates
115 /// an imaginary text buffer.
116 const FileEntry *OrigEntry;
118 /// \brief References the file which the contents were actually loaded from.
120 /// Can be different from 'Entry' if we overridden the contents of one file
121 /// with the contents of another file.
122 const FileEntry *ContentsEntry;
124 /// \brief A bump pointer allocated array of offsets for each source line.
126 /// This is lazily computed. This is owned by the SourceManager
127 /// BumpPointerAllocator object.
128 unsigned *SourceLineCache;
130 /// \brief The number of lines in this ContentCache.
132 /// This is only valid if SourceLineCache is non-null.
133 unsigned NumLines : 31;
135 /// \brief Indicates whether the buffer itself was provided to override
136 /// the actual file contents.
138 /// When true, the original entry may be a virtual file that does not
140 unsigned BufferOverridden : 1;
142 /// \brief True if this content cache was initially created for a source
143 /// file considered as a system one.
144 unsigned IsSystemFile : 1;
146 ContentCache(const FileEntry *Ent = nullptr)
147 : Buffer(nullptr, false), OrigEntry(Ent), ContentsEntry(Ent),
148 SourceLineCache(nullptr), NumLines(0), BufferOverridden(false),
149 IsSystemFile(false) {
150 (void)NonceAligner; // Silence warnings about unused member.
153 ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
154 : Buffer(nullptr, false), OrigEntry(Ent), ContentsEntry(contentEnt),
155 SourceLineCache(nullptr), NumLines(0), BufferOverridden(false),
156 IsSystemFile(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), SourceLineCache(nullptr),
165 BufferOverridden(false), IsSystemFile(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 /// \brief Returns the memory buffer for the associated content.
178 /// \param Diag Object through which diagnostics will be emitted if the
179 /// buffer cannot be retrieved.
181 /// \param Loc If specified, is the location that invalid file diagnostics
182 /// will be emitted at.
184 /// \param Invalid If non-NULL, will be set \c true if an error occurred.
185 const llvm::MemoryBuffer *getBuffer(DiagnosticsEngine &Diag,
186 const SourceManager &SM,
187 SourceLocation Loc = SourceLocation(),
188 bool *Invalid = nullptr) const;
190 /// \brief Returns the size of the content encapsulated by this
193 /// This can be the size of the source file or the size of an
194 /// arbitrary scratch buffer. If the ContentCache encapsulates a source
195 /// file this size is retrieved from the file's FileEntry.
196 unsigned getSize() const;
198 /// \brief Returns the number of bytes actually mapped for this
201 /// This can be 0 if the MemBuffer was not actually expanded.
202 unsigned getSizeBytesMapped() const;
204 /// Returns the kind of memory used to back the memory buffer for
205 /// this content cache. This is used for performance analysis.
206 llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const;
208 void setBuffer(const llvm::MemoryBuffer *B) {
209 assert(!Buffer.getPointer() && "MemoryBuffer already set.");
210 Buffer.setPointer(B);
211 Buffer.setInt(false);
214 /// \brief Get the underlying buffer, returning NULL if the buffer is not
216 const llvm::MemoryBuffer *getRawBuffer() const {
217 return Buffer.getPointer();
220 /// \brief Replace the existing buffer (which will be deleted)
221 /// with the given buffer.
222 void replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree = false);
224 /// \brief Determine whether the buffer itself is invalid.
225 bool isBufferInvalid() const {
226 return Buffer.getInt() & InvalidFlag;
229 /// \brief Determine whether the buffer should be freed.
230 bool shouldFreeBuffer() const {
231 return (Buffer.getInt() & DoNotFreeFlag) == 0;
235 // Disable assignments.
236 ContentCache &operator=(const ContentCache& RHS) LLVM_DELETED_FUNCTION;
239 // Assert that the \c ContentCache objects will always be 8-byte aligned so
240 // that we can pack 3 bits of integer into pointers to such objects.
241 static_assert(llvm::AlignOf<ContentCache>::Alignment >= 8,
242 "ContentCache must be 8-byte aligned.");
244 /// \brief Information about a FileID, basically just the logical file
245 /// that it represents and include stack information.
247 /// Each FileInfo has include stack information, indicating where it came
248 /// from. This information encodes the \#include chain that a token was
249 /// expanded from. The main include file has an invalid IncludeLoc.
251 /// FileInfos contain a "ContentCache *", with the contents of the file.
254 /// \brief The location of the \#include that brought in this file.
256 /// This is an invalid SLOC for the main file (top of the \#include chain).
257 unsigned IncludeLoc; // Really a SourceLocation
259 /// \brief Number of FileIDs (files and macros) that were created during
260 /// preprocessing of this \#include, including this SLocEntry.
262 /// Zero means the preprocessor didn't provide such info for this SLocEntry.
263 unsigned NumCreatedFIDs;
265 /// \brief Contains the ContentCache* and the bits indicating the
266 /// characteristic of the file and whether it has \#line info, all
267 /// bitmangled together.
270 friend class clang::SourceManager;
271 friend class clang::ASTWriter;
272 friend class clang::ASTReader;
274 /// \brief Return a FileInfo object.
275 static FileInfo get(SourceLocation IL, const ContentCache *Con,
276 CharacteristicKind FileCharacter) {
278 X.IncludeLoc = IL.getRawEncoding();
279 X.NumCreatedFIDs = 0;
280 X.Data = (uintptr_t)Con;
281 assert((X.Data & 7) == 0 &&"ContentCache pointer insufficiently aligned");
282 assert((unsigned)FileCharacter < 4 && "invalid file character");
283 X.Data |= (unsigned)FileCharacter;
287 SourceLocation getIncludeLoc() const {
288 return SourceLocation::getFromRawEncoding(IncludeLoc);
290 const ContentCache* getContentCache() const {
291 return reinterpret_cast<const ContentCache*>(Data & ~uintptr_t(7));
294 /// \brief Return whether this is a system header or not.
295 CharacteristicKind getFileCharacteristic() const {
296 return (CharacteristicKind)(Data & 3);
299 /// \brief Return true if this FileID has \#line directives in it.
300 bool hasLineDirectives() const { return (Data & 4) != 0; }
302 /// \brief Set the flag that indicates that this FileID has
303 /// line table entries associated with it.
304 void setHasLineDirectives() {
309 /// \brief Each ExpansionInfo encodes the expansion location - where
310 /// the token was ultimately expanded, and the SpellingLoc - where the actual
311 /// character data for the token came from.
312 class ExpansionInfo {
313 // Really these are all SourceLocations.
315 /// \brief Where the spelling for the token can be found.
316 unsigned SpellingLoc;
318 /// In a macro expansion, ExpansionLocStart and ExpansionLocEnd
319 /// indicate the start and end of the expansion. In object-like macros,
320 /// they will be the same. In a function-like macro expansion, the start
321 /// will be the identifier and the end will be the ')'. Finally, in
322 /// macro-argument instantiations, the end will be 'SourceLocation()', an
323 /// invalid location.
324 unsigned ExpansionLocStart, ExpansionLocEnd;
327 SourceLocation getSpellingLoc() const {
328 return SourceLocation::getFromRawEncoding(SpellingLoc);
330 SourceLocation getExpansionLocStart() const {
331 return SourceLocation::getFromRawEncoding(ExpansionLocStart);
333 SourceLocation getExpansionLocEnd() const {
334 SourceLocation EndLoc =
335 SourceLocation::getFromRawEncoding(ExpansionLocEnd);
336 return EndLoc.isInvalid() ? getExpansionLocStart() : EndLoc;
339 std::pair<SourceLocation,SourceLocation> getExpansionLocRange() const {
340 return std::make_pair(getExpansionLocStart(), getExpansionLocEnd());
343 bool isMacroArgExpansion() const {
344 // Note that this needs to return false for default constructed objects.
345 return getExpansionLocStart().isValid() &&
346 SourceLocation::getFromRawEncoding(ExpansionLocEnd).isInvalid();
349 bool isMacroBodyExpansion() const {
350 return getExpansionLocStart().isValid() &&
351 SourceLocation::getFromRawEncoding(ExpansionLocEnd).isValid();
354 bool isFunctionMacroExpansion() const {
355 return getExpansionLocStart().isValid() &&
356 getExpansionLocStart() != getExpansionLocEnd();
359 /// \brief Return a ExpansionInfo for an expansion.
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,
366 SourceLocation Start, SourceLocation End) {
368 X.SpellingLoc = SpellingLoc.getRawEncoding();
369 X.ExpansionLocStart = Start.getRawEncoding();
370 X.ExpansionLocEnd = End.getRawEncoding();
374 /// \brief Return a special ExpansionInfo for the expansion of
375 /// a macro argument into a function-like macro's body.
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.
386 /// #define F(x) f(x)
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'.
393 static ExpansionInfo createForMacroArg(SourceLocation SpellingLoc,
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
398 return create(SpellingLoc, ExpansionLoc, SourceLocation());
402 /// \brief This is a discriminated union of FileInfo and ExpansionInfo.
404 /// SourceManager keeps an array of these objects, and they are uniquely
405 /// identified by the FileID datatype.
407 unsigned Offset; // low bit is set for expansion info.
410 ExpansionInfo Expansion;
413 unsigned getOffset() const { return Offset >> 1; }
415 bool isExpansion() const { return Offset & 1; }
416 bool isFile() const { return !isExpansion(); }
418 const FileInfo &getFile() const {
419 assert(isFile() && "Not a file SLocEntry!");
423 const ExpansionInfo &getExpansion() const {
424 assert(isExpansion() && "Not a macro expansion SLocEntry!");
428 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
430 E.Offset = Offset << 1;
435 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
437 E.Offset = (Offset << 1) | 1;
438 E.Expansion = Expansion;
442 } // end SrcMgr namespace.
444 /// \brief External source of source location entries.
445 class ExternalSLocEntrySource {
447 virtual ~ExternalSLocEntrySource();
449 /// \brief Read the source location entry with index ID, which will always be
452 /// \returns true if an error occurred that prevented the source-location
453 /// entry from being loaded.
454 virtual bool ReadSLocEntry(int ID) = 0;
456 /// \brief Retrieve the module import location and name for the given ID, if
457 /// in fact it was loaded from a module (rather than, say, a precompiled
459 virtual std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) = 0;
463 /// \brief Holds the cache used by isBeforeInTranslationUnit.
465 /// The cache structure is complex enough to be worth breaking out of
467 class InBeforeInTUCacheEntry {
468 /// \brief The FileID's of the cached query.
470 /// If these match up with a subsequent query, the result can be reused.
471 FileID LQueryFID, RQueryFID;
473 /// \brief True if LQueryFID was created before RQueryFID.
475 /// This is used to compare macro expansion locations.
476 bool IsLQFIDBeforeRQFID;
478 /// \brief The file found in common between the two \#include traces, i.e.,
479 /// the nearest common ancestor of the \#include tree.
482 /// \brief The offset of the previous query in CommonFID.
484 /// Usually, this represents the location of the \#include for QueryFID, but
485 /// if LQueryFID is a parent of RQueryFID (or vice versa) then these can be a
486 /// random token in the parent.
487 unsigned LCommonOffset, RCommonOffset;
489 /// \brief Return true if the currently cached values match up with
490 /// the specified LHS/RHS query.
492 /// If not, we can't use the cache.
493 bool isCacheValid(FileID LHS, FileID RHS) const {
494 return LQueryFID == LHS && RQueryFID == RHS;
497 /// \brief If the cache is valid, compute the result given the
498 /// specified offsets in the LHS/RHS FileID's.
499 bool getCachedResult(unsigned LOffset, unsigned ROffset) const {
500 // If one of the query files is the common file, use the offset. Otherwise,
501 // use the #include loc in the common file.
502 if (LQueryFID != CommonFID) LOffset = LCommonOffset;
503 if (RQueryFID != CommonFID) ROffset = RCommonOffset;
505 // It is common for multiple macro expansions to be "included" from the same
506 // location (expansion location), in which case use the order of the FileIDs
507 // to determine which came first. This will also take care the case where
508 // one of the locations points at the inclusion/expansion point of the other
509 // in which case its FileID will come before the other.
510 if (LOffset == ROffset)
511 return IsLQFIDBeforeRQFID;
513 return LOffset < ROffset;
516 /// \brief Set up a new query.
517 void setQueryFIDs(FileID LHS, FileID RHS, bool isLFIDBeforeRFID) {
521 IsLQFIDBeforeRQFID = isLFIDBeforeRFID;
525 LQueryFID = RQueryFID = FileID();
526 IsLQFIDBeforeRQFID = false;
529 void setCommonLoc(FileID commonFID, unsigned lCommonOffset,
530 unsigned rCommonOffset) {
531 CommonFID = commonFID;
532 LCommonOffset = lCommonOffset;
533 RCommonOffset = rCommonOffset;
538 /// \brief The stack used when building modules on demand, which is used
539 /// to provide a link between the source managers of the different compiler
541 typedef ArrayRef<std::pair<std::string, FullSourceLoc> > ModuleBuildStack;
543 /// \brief This class handles loading and caching of source files into memory.
545 /// This object owns the MemoryBuffer objects for all of the loaded
546 /// files and assigns unique FileID's for each unique \#include chain.
548 /// The SourceManager can be queried for information about SourceLocation
549 /// objects, turning them into either spelling or expansion locations. Spelling
550 /// locations represent where the bytes corresponding to a token came from and
551 /// expansion locations represent where the location is in the user's view. In
552 /// the case of a macro expansion, for example, the spelling location indicates
553 /// where the expanded token came from and the expansion location specifies
554 /// where it was expanded.
555 class SourceManager : public RefCountedBase<SourceManager> {
556 /// \brief DiagnosticsEngine object.
557 DiagnosticsEngine &Diag;
559 FileManager &FileMgr;
561 mutable llvm::BumpPtrAllocator ContentCacheAlloc;
563 /// \brief Memoized information about all of the files tracked by this
566 /// This map allows us to merge ContentCache entries based
567 /// on their FileEntry*. All ContentCache objects will thus have unique,
568 /// non-null, FileEntry pointers.
569 llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*> FileInfos;
571 /// \brief True if the ContentCache for files that are overriden by other
572 /// files, should report the original file name. Defaults to true.
573 bool OverridenFilesKeepOriginalName;
575 /// \brief True if non-system source files should be treated as volatile
576 /// (likely to change while trying to use them). Defaults to false.
577 bool UserFilesAreVolatile;
579 struct OverriddenFilesInfoTy {
580 /// \brief Files that have been overriden with the contents from another
582 llvm::DenseMap<const FileEntry *, const FileEntry *> OverriddenFiles;
583 /// \brief Files that were overridden with a memory buffer.
584 llvm::DenseSet<const FileEntry *> OverriddenFilesWithBuffer;
587 /// \brief Lazily create the object keeping overridden files info, since
588 /// it is uncommonly used.
589 std::unique_ptr<OverriddenFilesInfoTy> OverriddenFilesInfo;
591 OverriddenFilesInfoTy &getOverriddenFilesInfo() {
592 if (!OverriddenFilesInfo)
593 OverriddenFilesInfo.reset(new OverriddenFilesInfoTy);
594 return *OverriddenFilesInfo;
597 /// \brief Information about various memory buffers that we have read in.
599 /// All FileEntry* within the stored ContentCache objects are NULL,
600 /// as they do not refer to a file.
601 std::vector<SrcMgr::ContentCache*> MemBufferInfos;
603 /// \brief The table of SLocEntries that are local to this module.
605 /// Positive FileIDs are indexes into this table. Entry 0 indicates an invalid
607 SmallVector<SrcMgr::SLocEntry, 0> LocalSLocEntryTable;
609 /// \brief The table of SLocEntries that are loaded from other modules.
611 /// Negative FileIDs are indexes into this table. To get from ID to an index,
613 mutable SmallVector<SrcMgr::SLocEntry, 0> LoadedSLocEntryTable;
615 /// \brief The starting offset of the next local SLocEntry.
617 /// This is LocalSLocEntryTable.back().Offset + the size of that entry.
618 unsigned NextLocalOffset;
620 /// \brief The starting offset of the latest batch of loaded SLocEntries.
622 /// This is LoadedSLocEntryTable.back().Offset, except that that entry might
623 /// not have been loaded, so that value would be unknown.
624 unsigned CurrentLoadedOffset;
626 /// \brief The highest possible offset is 2^31-1, so CurrentLoadedOffset
628 static const unsigned MaxLoadedOffset = 1U << 31U;
630 /// \brief A bitmap that indicates whether the entries of LoadedSLocEntryTable
631 /// have already been loaded from the external source.
633 /// Same indexing as LoadedSLocEntryTable.
634 std::vector<bool> SLocEntryLoaded;
636 /// \brief An external source for source location entries.
637 ExternalSLocEntrySource *ExternalSLocEntries;
639 /// \brief A one-entry cache to speed up getFileID.
641 /// LastFileIDLookup records the last FileID looked up or created, because it
642 /// is very common to look up many tokens from the same file.
643 mutable FileID LastFileIDLookup;
645 /// \brief Holds information for \#line directives.
647 /// This is referenced by indices from SLocEntryTable.
648 LineTableInfo *LineTable;
650 /// \brief These ivars serve as a cache used in the getLineNumber
651 /// method which is used to speedup getLineNumber calls to nearby locations.
652 mutable FileID LastLineNoFileIDQuery;
653 mutable SrcMgr::ContentCache *LastLineNoContentCache;
654 mutable unsigned LastLineNoFilePos;
655 mutable unsigned LastLineNoResult;
657 /// \brief The file ID for the main source file of the translation unit.
660 /// \brief The file ID for the precompiled preamble there is one.
661 FileID PreambleFileID;
663 // Statistics for -print-stats.
664 mutable unsigned NumLinearScans, NumBinaryProbes;
666 /// \brief Associates a FileID with its "included/expanded in" decomposed
669 /// Used to cache results from and speed-up \c getDecomposedIncludedLoc
671 mutable llvm::DenseMap<FileID, std::pair<FileID, unsigned> > IncludedLocMap;
673 /// The key value into the IsBeforeInTUCache table.
674 typedef std::pair<FileID, FileID> IsBeforeInTUCacheKey;
676 /// The IsBeforeInTranslationUnitCache is a mapping from FileID pairs
677 /// to cache results.
678 typedef llvm::DenseMap<IsBeforeInTUCacheKey, InBeforeInTUCacheEntry>
681 /// Cache results for the isBeforeInTranslationUnit method.
682 mutable InBeforeInTUCache IBTUCache;
683 mutable InBeforeInTUCacheEntry IBTUCacheOverflow;
685 /// Return the cache entry for comparing the given file IDs
686 /// for isBeforeInTranslationUnit.
687 InBeforeInTUCacheEntry &getInBeforeInTUCache(FileID LFID, FileID RFID) const;
689 // Cache for the "fake" buffer used for error-recovery purposes.
690 mutable llvm::MemoryBuffer *FakeBufferForRecovery;
692 mutable SrcMgr::ContentCache *FakeContentCacheForRecovery;
694 /// \brief Lazily computed map of macro argument chunks to their expanded
696 typedef std::map<unsigned, SourceLocation> MacroArgsMap;
698 mutable llvm::DenseMap<FileID, MacroArgsMap *> MacroArgsCacheMap;
700 /// \brief The stack of modules being built, which is used to detect
701 /// cycles in the module dependency graph as modules are being built, as
702 /// well as to describe why we're rebuilding a particular module.
704 /// There is no way to set this value from the command line. If we ever need
705 /// to do so (e.g., if on-demand module construction moves out-of-process),
706 /// we can add a cc1-level option to do so.
707 SmallVector<std::pair<std::string, FullSourceLoc>, 2> StoredModuleBuildStack;
709 // SourceManager doesn't support copy construction.
710 explicit SourceManager(const SourceManager&) LLVM_DELETED_FUNCTION;
711 void operator=(const SourceManager&) LLVM_DELETED_FUNCTION;
713 SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
714 bool UserFilesAreVolatile = false);
717 void clearIDTables();
719 DiagnosticsEngine &getDiagnostics() const { return Diag; }
721 FileManager &getFileManager() const { return FileMgr; }
723 /// \brief Set true if the SourceManager should report the original file name
724 /// for contents of files that were overriden by other files.Defaults to true.
725 void setOverridenFilesKeepOriginalName(bool value) {
726 OverridenFilesKeepOriginalName = value;
729 /// \brief True if non-system source files should be treated as volatile
730 /// (likely to change while trying to use them).
731 bool userFilesAreVolatile() const { return UserFilesAreVolatile; }
733 /// \brief Retrieve the module build stack.
734 ModuleBuildStack getModuleBuildStack() const {
735 return StoredModuleBuildStack;
738 /// \brief Set the module build stack.
739 void setModuleBuildStack(ModuleBuildStack stack) {
740 StoredModuleBuildStack.clear();
741 StoredModuleBuildStack.append(stack.begin(), stack.end());
744 /// \brief Push an entry to the module build stack.
745 void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc) {
746 StoredModuleBuildStack.push_back(std::make_pair(moduleName.str(),importLoc));
749 //===--------------------------------------------------------------------===//
750 // MainFileID creation and querying methods.
751 //===--------------------------------------------------------------------===//
753 /// \brief Returns the FileID of the main source file.
754 FileID getMainFileID() const { return MainFileID; }
756 /// \brief Set the file ID for the main source file.
757 void setMainFileID(FileID FID) {
758 assert(MainFileID.isInvalid() && "MainFileID already set!");
762 /// \brief Set the file ID for the precompiled preamble.
763 void setPreambleFileID(FileID Preamble) {
764 assert(PreambleFileID.isInvalid() && "PreambleFileID already set!");
765 PreambleFileID = Preamble;
768 /// \brief Get the file ID for the precompiled preamble if there is one.
769 FileID getPreambleFileID() const { return PreambleFileID; }
771 //===--------------------------------------------------------------------===//
772 // Methods to create new FileID's and macro expansions.
773 //===--------------------------------------------------------------------===//
775 /// \brief Create a new FileID that represents the specified file
776 /// being \#included from the specified IncludePosition.
778 /// This translates NULL into standard input.
779 FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos,
780 SrcMgr::CharacteristicKind FileCharacter,
781 int LoadedID = 0, unsigned LoadedOffset = 0) {
782 const SrcMgr::ContentCache *
783 IR = getOrCreateContentCache(SourceFile,
784 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
785 assert(IR && "getOrCreateContentCache() cannot return NULL");
786 return createFileID(IR, IncludePos, FileCharacter, LoadedID, LoadedOffset);
789 /// \brief Create a new FileID that represents the specified memory buffer.
791 /// This does no caching of the buffer and takes ownership of the
792 /// MemoryBuffer, so only pass a MemoryBuffer to this once.
793 FileID createFileID(const llvm::MemoryBuffer *Buffer,
794 SrcMgr::CharacteristicKind FileCharacter = SrcMgr::C_User,
795 int LoadedID = 0, unsigned LoadedOffset = 0,
796 SourceLocation IncludeLoc = SourceLocation()) {
797 return createFileID(createMemBufferContentCache(Buffer), IncludeLoc,
798 FileCharacter, LoadedID, LoadedOffset);
801 /// \brief Return a new SourceLocation that encodes the
802 /// fact that a token from SpellingLoc should actually be referenced from
803 /// ExpansionLoc, and that it represents the expansion of a macro argument
804 /// into the function-like macro body.
805 SourceLocation createMacroArgExpansionLoc(SourceLocation Loc,
806 SourceLocation ExpansionLoc,
809 /// \brief Return a new SourceLocation that encodes the fact
810 /// that a token from SpellingLoc should actually be referenced from
812 SourceLocation createExpansionLoc(SourceLocation Loc,
813 SourceLocation ExpansionLocStart,
814 SourceLocation ExpansionLocEnd,
817 unsigned LoadedOffset = 0);
819 /// \brief Retrieve the memory buffer associated with the given file.
821 /// \param Invalid If non-NULL, will be set \c true if an error
822 /// occurs while retrieving the memory buffer.
823 const llvm::MemoryBuffer *getMemoryBufferForFile(const FileEntry *File,
824 bool *Invalid = nullptr);
826 /// \brief Override the contents of the given source file by providing an
827 /// already-allocated buffer.
829 /// \param SourceFile the source file whose contents will be overriden.
831 /// \param Buffer the memory buffer whose contents will be used as the
832 /// data in the given source file.
834 /// \param DoNotFree If true, then the buffer will not be freed when the
835 /// source manager is destroyed.
836 void overrideFileContents(const FileEntry *SourceFile,
837 const llvm::MemoryBuffer *Buffer,
838 bool DoNotFree = false);
840 /// \brief Override the given source file with another one.
842 /// \param SourceFile the source file which will be overriden.
844 /// \param NewFile the file whose contents will be used as the
845 /// data instead of the contents of the given source file.
846 void overrideFileContents(const FileEntry *SourceFile,
847 const FileEntry *NewFile);
849 /// \brief Returns true if the file contents have been overridden.
850 bool isFileOverridden(const FileEntry *File) {
851 if (OverriddenFilesInfo) {
852 if (OverriddenFilesInfo->OverriddenFilesWithBuffer.count(File))
854 if (OverriddenFilesInfo->OverriddenFiles.find(File) !=
855 OverriddenFilesInfo->OverriddenFiles.end())
861 /// \brief Disable overridding the contents of a file, previously enabled
862 /// with #overrideFileContents.
864 /// This should be called before parsing has begun.
865 void disableFileContentsOverride(const FileEntry *File);
867 //===--------------------------------------------------------------------===//
868 // FileID manipulation methods.
869 //===--------------------------------------------------------------------===//
871 /// \brief Return the buffer for the specified FileID.
873 /// If there is an error opening this buffer the first time, this
874 /// manufactures a temporary buffer and returns a non-empty error string.
875 const llvm::MemoryBuffer *getBuffer(FileID FID, SourceLocation Loc,
876 bool *Invalid = nullptr) const {
877 bool MyInvalid = false;
878 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
879 if (MyInvalid || !Entry.isFile()) {
883 return getFakeBufferForRecovery();
886 return Entry.getFile().getContentCache()->getBuffer(Diag, *this, Loc,
890 const llvm::MemoryBuffer *getBuffer(FileID FID,
891 bool *Invalid = nullptr) const {
892 bool MyInvalid = false;
893 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
894 if (MyInvalid || !Entry.isFile()) {
898 return getFakeBufferForRecovery();
901 return Entry.getFile().getContentCache()->getBuffer(Diag, *this,
906 /// \brief Returns the FileEntry record for the provided FileID.
907 const FileEntry *getFileEntryForID(FileID FID) const {
908 bool MyInvalid = false;
909 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
910 if (MyInvalid || !Entry.isFile())
913 const SrcMgr::ContentCache *Content = Entry.getFile().getContentCache();
916 return Content->OrigEntry;
919 /// \brief Returns the FileEntry record for the provided SLocEntry.
920 const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const
922 const SrcMgr::ContentCache *Content = sloc.getFile().getContentCache();
925 return Content->OrigEntry;
928 /// \brief Return a StringRef to the source buffer data for the
929 /// specified FileID.
931 /// \param FID The file ID whose contents will be returned.
932 /// \param Invalid If non-NULL, will be set true if an error occurred.
933 StringRef getBufferData(FileID FID, bool *Invalid = nullptr) const;
935 /// \brief Get the number of FileIDs (files and macros) that were created
936 /// during preprocessing of \p FID, including it.
937 unsigned getNumCreatedFIDsForFileID(FileID FID) const {
938 bool Invalid = false;
939 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
940 if (Invalid || !Entry.isFile())
943 return Entry.getFile().NumCreatedFIDs;
946 /// \brief Set the number of FileIDs (files and macros) that were created
947 /// during preprocessing of \p FID, including it.
948 void setNumCreatedFIDsForFileID(FileID FID, unsigned NumFIDs) const {
949 bool Invalid = false;
950 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
951 if (Invalid || !Entry.isFile())
954 assert(Entry.getFile().NumCreatedFIDs == 0 && "Already set!");
955 const_cast<SrcMgr::FileInfo &>(Entry.getFile()).NumCreatedFIDs = NumFIDs;
958 //===--------------------------------------------------------------------===//
959 // SourceLocation manipulation methods.
960 //===--------------------------------------------------------------------===//
962 /// \brief Return the FileID for a SourceLocation.
964 /// This is a very hot method that is used for all SourceManager queries
965 /// that start with a SourceLocation object. It is responsible for finding
966 /// the entry in SLocEntryTable which contains the specified location.
968 FileID getFileID(SourceLocation SpellingLoc) const {
969 unsigned SLocOffset = SpellingLoc.getOffset();
971 // If our one-entry cache covers this offset, just return it.
972 if (isOffsetInFileID(LastFileIDLookup, SLocOffset))
973 return LastFileIDLookup;
975 return getFileIDSlow(SLocOffset);
978 /// \brief Return the filename of the file containing a SourceLocation.
979 StringRef getFilename(SourceLocation SpellingLoc) const {
980 if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
985 /// \brief Return the source location corresponding to the first byte of
986 /// the specified file.
987 SourceLocation getLocForStartOfFile(FileID FID) const {
988 bool Invalid = false;
989 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
990 if (Invalid || !Entry.isFile())
991 return SourceLocation();
993 unsigned FileOffset = Entry.getOffset();
994 return SourceLocation::getFileLoc(FileOffset);
997 /// \brief Return the source location corresponding to the last byte of the
999 SourceLocation getLocForEndOfFile(FileID FID) const {
1000 bool Invalid = false;
1001 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1002 if (Invalid || !Entry.isFile())
1003 return SourceLocation();
1005 unsigned FileOffset = Entry.getOffset();
1006 return SourceLocation::getFileLoc(FileOffset + getFileIDSize(FID));
1009 /// \brief Returns the include location if \p FID is a \#include'd file
1010 /// otherwise it returns an invalid location.
1011 SourceLocation getIncludeLoc(FileID FID) const {
1012 bool Invalid = false;
1013 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1014 if (Invalid || !Entry.isFile())
1015 return SourceLocation();
1017 return Entry.getFile().getIncludeLoc();
1020 // \brief Returns the import location if the given source location is
1021 // located within a module, or an invalid location if the source location
1022 // is within the current translation unit.
1023 std::pair<SourceLocation, StringRef>
1024 getModuleImportLoc(SourceLocation Loc) const {
1025 FileID FID = getFileID(Loc);
1027 // Positive file IDs are in the current translation unit, and -1 is a
1030 return std::make_pair(SourceLocation(), "");
1032 return ExternalSLocEntries->getModuleImportLoc(FID.ID);
1035 /// \brief Given a SourceLocation object \p Loc, return the expansion
1036 /// location referenced by the ID.
1037 SourceLocation getExpansionLoc(SourceLocation Loc) const {
1038 // Handle the non-mapped case inline, defer to out of line code to handle
1040 if (Loc.isFileID()) return Loc;
1041 return getExpansionLocSlowCase(Loc);
1044 /// \brief Given \p Loc, if it is a macro location return the expansion
1045 /// location or the spelling location, depending on if it comes from a
1046 /// macro argument or not.
1047 SourceLocation getFileLoc(SourceLocation Loc) const {
1048 if (Loc.isFileID()) return Loc;
1049 return getFileLocSlowCase(Loc);
1052 /// \brief Return the start/end of the expansion information for an
1053 /// expansion location.
1055 /// \pre \p Loc is required to be an expansion location.
1056 std::pair<SourceLocation,SourceLocation>
1057 getImmediateExpansionRange(SourceLocation Loc) const;
1059 /// \brief Given a SourceLocation object, return the range of
1060 /// tokens covered by the expansion the ultimate file.
1061 std::pair<SourceLocation,SourceLocation>
1062 getExpansionRange(SourceLocation Loc) const;
1065 /// \brief Given a SourceLocation object, return the spelling
1066 /// location referenced by the ID.
1068 /// This is the place where the characters that make up the lexed token
1070 SourceLocation getSpellingLoc(SourceLocation Loc) const {
1071 // Handle the non-mapped case inline, defer to out of line code to handle
1073 if (Loc.isFileID()) return Loc;
1074 return getSpellingLocSlowCase(Loc);
1077 /// \brief Given a SourceLocation object, return the spelling location
1078 /// referenced by the ID.
1080 /// This is the first level down towards the place where the characters
1081 /// that make up the lexed token can be found. This should not generally
1082 /// be used by clients.
1083 SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const;
1085 /// \brief Decompose the specified location into a raw FileID + Offset pair.
1087 /// The first element is the FileID, the second is the offset from the
1088 /// start of the buffer of the location.
1089 std::pair<FileID, unsigned> getDecomposedLoc(SourceLocation Loc) const {
1090 FileID FID = getFileID(Loc);
1091 bool Invalid = false;
1092 const SrcMgr::SLocEntry &E = getSLocEntry(FID, &Invalid);
1094 return std::make_pair(FileID(), 0);
1095 return std::make_pair(FID, Loc.getOffset()-E.getOffset());
1098 /// \brief Decompose the specified location into a raw FileID + Offset pair.
1100 /// If the location is an expansion record, walk through it until we find
1101 /// the final location expanded.
1102 std::pair<FileID, unsigned>
1103 getDecomposedExpansionLoc(SourceLocation Loc) const {
1104 FileID FID = getFileID(Loc);
1105 bool Invalid = false;
1106 const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
1108 return std::make_pair(FileID(), 0);
1110 unsigned Offset = Loc.getOffset()-E->getOffset();
1112 return std::make_pair(FID, Offset);
1114 return getDecomposedExpansionLocSlowCase(E);
1117 /// \brief Decompose the specified location into a raw FileID + Offset pair.
1119 /// If the location is an expansion record, walk through it until we find
1120 /// its spelling record.
1121 std::pair<FileID, unsigned>
1122 getDecomposedSpellingLoc(SourceLocation Loc) const {
1123 FileID FID = getFileID(Loc);
1124 bool Invalid = false;
1125 const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
1127 return std::make_pair(FileID(), 0);
1129 unsigned Offset = Loc.getOffset()-E->getOffset();
1131 return std::make_pair(FID, Offset);
1132 return getDecomposedSpellingLocSlowCase(E, Offset);
1135 /// \brief Returns the "included/expanded in" decomposed location of the given
1137 std::pair<FileID, unsigned> getDecomposedIncludedLoc(FileID FID) const;
1139 /// \brief Returns the offset from the start of the file that the
1140 /// specified SourceLocation represents.
1142 /// This is not very meaningful for a macro ID.
1143 unsigned getFileOffset(SourceLocation SpellingLoc) const {
1144 return getDecomposedLoc(SpellingLoc).second;
1147 /// \brief Tests whether the given source location represents a macro
1148 /// argument's expansion into the function-like macro definition.
1150 /// Such source locations only appear inside of the expansion
1151 /// locations representing where a particular function-like macro was
1153 bool isMacroArgExpansion(SourceLocation Loc) const;
1155 /// \brief Tests whether the given source location represents the expansion of
1158 /// This is equivalent to testing whether the location is part of a macro
1159 /// expansion but not the expansion of an argument to a function-like macro.
1160 bool isMacroBodyExpansion(SourceLocation Loc) const;
1162 /// \brief Returns true if the given MacroID location points at the beginning
1163 /// of the immediate macro expansion.
1165 /// \param MacroBegin If non-null and function returns true, it is set to the
1166 /// begin location of the immediate macro expansion.
1167 bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1168 SourceLocation *MacroBegin = nullptr) const;
1170 /// \brief Returns true if the given MacroID location points at the character
1171 /// end of the immediate macro expansion.
1173 /// \param MacroEnd If non-null and function returns true, it is set to the
1174 /// character end location of the immediate macro expansion.
1176 isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1177 SourceLocation *MacroEnd = nullptr) const;
1179 /// \brief Returns true if \p Loc is inside the [\p Start, +\p Length)
1180 /// chunk of the source location address space.
1182 /// If it's true and \p RelativeOffset is non-null, it will be set to the
1183 /// relative offset of \p Loc inside the chunk.
1184 bool isInSLocAddrSpace(SourceLocation Loc,
1185 SourceLocation Start, unsigned Length,
1186 unsigned *RelativeOffset = nullptr) const {
1187 assert(((Start.getOffset() < NextLocalOffset &&
1188 Start.getOffset()+Length <= NextLocalOffset) ||
1189 (Start.getOffset() >= CurrentLoadedOffset &&
1190 Start.getOffset()+Length < MaxLoadedOffset)) &&
1191 "Chunk is not valid SLoc address space");
1192 unsigned LocOffs = Loc.getOffset();
1193 unsigned BeginOffs = Start.getOffset();
1194 unsigned EndOffs = BeginOffs + Length;
1195 if (LocOffs >= BeginOffs && LocOffs < EndOffs) {
1197 *RelativeOffset = LocOffs - BeginOffs;
1204 /// \brief Return true if both \p LHS and \p RHS are in the local source
1205 /// location address space or the loaded one.
1207 /// If it's true and \p RelativeOffset is non-null, it will be set to the
1208 /// offset of \p RHS relative to \p LHS.
1209 bool isInSameSLocAddrSpace(SourceLocation LHS, SourceLocation RHS,
1210 int *RelativeOffset) const {
1211 unsigned LHSOffs = LHS.getOffset(), RHSOffs = RHS.getOffset();
1212 bool LHSLoaded = LHSOffs >= CurrentLoadedOffset;
1213 bool RHSLoaded = RHSOffs >= CurrentLoadedOffset;
1215 if (LHSLoaded == RHSLoaded) {
1217 *RelativeOffset = RHSOffs - LHSOffs;
1224 //===--------------------------------------------------------------------===//
1225 // Queries about the code at a SourceLocation.
1226 //===--------------------------------------------------------------------===//
1228 /// \brief Return a pointer to the start of the specified location
1229 /// in the appropriate spelling MemoryBuffer.
1231 /// \param Invalid If non-NULL, will be set \c true if an error occurs.
1232 const char *getCharacterData(SourceLocation SL,
1233 bool *Invalid = nullptr) const;
1235 /// \brief Return the column # for the specified file position.
1237 /// This is significantly cheaper to compute than the line number. This
1238 /// returns zero if the column number isn't known. This may only be called
1239 /// on a file sloc, so you must choose a spelling or expansion location
1240 /// before calling this method.
1241 unsigned getColumnNumber(FileID FID, unsigned FilePos,
1242 bool *Invalid = nullptr) const;
1243 unsigned getSpellingColumnNumber(SourceLocation Loc,
1244 bool *Invalid = nullptr) const;
1245 unsigned getExpansionColumnNumber(SourceLocation Loc,
1246 bool *Invalid = nullptr) const;
1247 unsigned getPresumedColumnNumber(SourceLocation Loc,
1248 bool *Invalid = nullptr) const;
1250 /// \brief Given a SourceLocation, return the spelling line number
1251 /// for the position indicated.
1253 /// This requires building and caching a table of line offsets for the
1254 /// MemoryBuffer, so this is not cheap: use only when about to emit a
1256 unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid = nullptr) const;
1257 unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
1258 unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
1259 unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
1261 /// \brief Return the filename or buffer identifier of the buffer the
1264 /// Note that this name does not respect \#line directives. Use
1265 /// getPresumedLoc for normal clients.
1266 const char *getBufferName(SourceLocation Loc, bool *Invalid = nullptr) const;
1268 /// \brief Return the file characteristic of the specified source
1269 /// location, indicating whether this is a normal file, a system
1270 /// header, or an "implicit extern C" system header.
1272 /// This state can be modified with flags on GNU linemarker directives like:
1276 /// which changes all source locations in the current file after that to be
1277 /// considered to be from a system header.
1278 SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const;
1280 /// \brief Returns the "presumed" location of a SourceLocation specifies.
1282 /// A "presumed location" can be modified by \#line or GNU line marker
1283 /// directives. This provides a view on the data that a user should see
1284 /// in diagnostics, for example.
1286 /// Note that a presumed location is always given as the expansion point of
1287 /// an expansion location, not at the spelling location.
1289 /// \returns The presumed location of the specified SourceLocation. If the
1290 /// presumed location cannot be calculated (e.g., because \p Loc is invalid
1291 /// or the file containing \p Loc has changed on disk), returns an invalid
1292 /// presumed location.
1293 PresumedLoc getPresumedLoc(SourceLocation Loc,
1294 bool UseLineDirectives = true) const;
1296 /// \brief Returns whether the PresumedLoc for a given SourceLocation is
1297 /// in the main file.
1299 /// This computes the "presumed" location for a SourceLocation, then checks
1300 /// whether it came from a file other than the main file. This is different
1301 /// from isWrittenInMainFile() because it takes line marker directives into
1303 bool isInMainFile(SourceLocation Loc) const;
1305 /// \brief Returns true if the spelling locations for both SourceLocations
1306 /// are part of the same file buffer.
1308 /// This check ignores line marker directives.
1309 bool isWrittenInSameFile(SourceLocation Loc1, SourceLocation Loc2) const {
1310 return getFileID(Loc1) == getFileID(Loc2);
1313 /// \brief Returns true if the spelling location for the given location
1314 /// is in the main file buffer.
1316 /// This check ignores line marker directives.
1317 bool isWrittenInMainFile(SourceLocation Loc) const {
1318 return getFileID(Loc) == getMainFileID();
1321 /// \brief Returns if a SourceLocation is in a system header.
1322 bool isInSystemHeader(SourceLocation Loc) const {
1323 return getFileCharacteristic(Loc) != SrcMgr::C_User;
1326 /// \brief Returns if a SourceLocation is in an "extern C" system header.
1327 bool isInExternCSystemHeader(SourceLocation Loc) const {
1328 return getFileCharacteristic(Loc) == SrcMgr::C_ExternCSystem;
1331 /// \brief Returns whether \p Loc is expanded from a macro in a system header.
1332 bool isInSystemMacro(SourceLocation loc) {
1333 return loc.isMacroID() && isInSystemHeader(getSpellingLoc(loc));
1336 /// \brief The size of the SLocEntry that \p FID represents.
1337 unsigned getFileIDSize(FileID FID) const;
1339 /// \brief Given a specific FileID, returns true if \p Loc is inside that
1340 /// FileID chunk and sets relative offset (offset of \p Loc from beginning
1341 /// of FileID) to \p relativeOffset.
1342 bool isInFileID(SourceLocation Loc, FileID FID,
1343 unsigned *RelativeOffset = nullptr) const {
1344 unsigned Offs = Loc.getOffset();
1345 if (isOffsetInFileID(FID, Offs)) {
1347 *RelativeOffset = Offs - getSLocEntry(FID).getOffset();
1354 //===--------------------------------------------------------------------===//
1355 // Line Table Manipulation Routines
1356 //===--------------------------------------------------------------------===//
1358 /// \brief Return the uniqued ID for the specified filename.
1360 unsigned getLineTableFilenameID(StringRef Str);
1362 /// \brief Add a line note to the line table for the FileID and offset
1363 /// specified by Loc.
1365 /// If FilenameID is -1, it is considered to be unspecified.
1366 void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID);
1367 void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID,
1368 bool IsFileEntry, bool IsFileExit,
1369 bool IsSystemHeader, bool IsExternCHeader);
1371 /// \brief Determine if the source manager has a line table.
1372 bool hasLineTable() const { return LineTable != nullptr; }
1374 /// \brief Retrieve the stored line table.
1375 LineTableInfo &getLineTable();
1377 //===--------------------------------------------------------------------===//
1378 // Queries for performance analysis.
1379 //===--------------------------------------------------------------------===//
1381 /// \brief Return the total amount of physical memory allocated by the
1382 /// ContentCache allocator.
1383 size_t getContentCacheSize() const {
1384 return ContentCacheAlloc.getTotalMemory();
1387 struct MemoryBufferSizes {
1388 const size_t malloc_bytes;
1389 const size_t mmap_bytes;
1391 MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
1392 : malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
1395 /// \brief Return the amount of memory used by memory buffers, breaking down
1396 /// by heap-backed versus mmap'ed memory.
1397 MemoryBufferSizes getMemoryBufferSizes() const;
1399 /// \brief Return the amount of memory used for various side tables and
1400 /// data structures in the SourceManager.
1401 size_t getDataStructureSizes() const;
1403 //===--------------------------------------------------------------------===//
1404 // Other miscellaneous methods.
1405 //===--------------------------------------------------------------------===//
1407 /// \brief Get the source location for the given file:line:col triplet.
1409 /// If the source file is included multiple times, the source location will
1410 /// be based upon the first inclusion.
1411 SourceLocation translateFileLineCol(const FileEntry *SourceFile,
1412 unsigned Line, unsigned Col) const;
1414 /// \brief Get the FileID for the given file.
1416 /// If the source file is included multiple times, the FileID will be the
1417 /// first inclusion.
1418 FileID translateFile(const FileEntry *SourceFile) const;
1420 /// \brief Get the source location in \p FID for the given line:col.
1421 /// Returns null location if \p FID is not a file SLocEntry.
1422 SourceLocation translateLineCol(FileID FID,
1423 unsigned Line, unsigned Col) const;
1425 /// \brief If \p Loc points inside a function macro argument, the returned
1426 /// location will be the macro location in which the argument was expanded.
1427 /// If a macro argument is used multiple times, the expanded location will
1428 /// be at the first expansion of the argument.
1432 /// Passing a file location pointing at 'foo', will yield a macro location
1433 /// where 'foo' was expanded into.
1434 SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const;
1436 /// \brief Determines the order of 2 source locations in the translation unit.
1438 /// \returns true if LHS source location comes before RHS, false otherwise.
1439 bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const;
1441 /// \brief Determines the order of 2 source locations in the "source location
1443 bool isBeforeInSLocAddrSpace(SourceLocation LHS, SourceLocation RHS) const {
1444 return isBeforeInSLocAddrSpace(LHS, RHS.getOffset());
1447 /// \brief Determines the order of a source location and a source location
1448 /// offset in the "source location address space".
1450 /// Note that we always consider source locations loaded from
1451 bool isBeforeInSLocAddrSpace(SourceLocation LHS, unsigned RHS) const {
1452 unsigned LHSOffset = LHS.getOffset();
1453 bool LHSLoaded = LHSOffset >= CurrentLoadedOffset;
1454 bool RHSLoaded = RHS >= CurrentLoadedOffset;
1455 if (LHSLoaded == RHSLoaded)
1456 return LHSOffset < RHS;
1461 // Iterators over FileInfos.
1462 typedef llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>
1463 ::const_iterator fileinfo_iterator;
1464 fileinfo_iterator fileinfo_begin() const { return FileInfos.begin(); }
1465 fileinfo_iterator fileinfo_end() const { return FileInfos.end(); }
1466 bool hasFileInfo(const FileEntry *File) const {
1467 return FileInfos.find(File) != FileInfos.end();
1470 /// \brief Print statistics to stderr.
1472 void PrintStats() const;
1474 /// \brief Get the number of local SLocEntries we have.
1475 unsigned local_sloc_entry_size() const { return LocalSLocEntryTable.size(); }
1477 /// \brief Get a local SLocEntry. This is exposed for indexing.
1478 const SrcMgr::SLocEntry &getLocalSLocEntry(unsigned Index,
1479 bool *Invalid = nullptr) const {
1480 assert(Index < LocalSLocEntryTable.size() && "Invalid index");
1481 return LocalSLocEntryTable[Index];
1484 /// \brief Get the number of loaded SLocEntries we have.
1485 unsigned loaded_sloc_entry_size() const { return LoadedSLocEntryTable.size();}
1487 /// \brief Get a loaded SLocEntry. This is exposed for indexing.
1488 const SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index,
1489 bool *Invalid = nullptr) const {
1490 assert(Index < LoadedSLocEntryTable.size() && "Invalid index");
1491 if (SLocEntryLoaded[Index])
1492 return LoadedSLocEntryTable[Index];
1493 return loadSLocEntry(Index, Invalid);
1496 const SrcMgr::SLocEntry &getSLocEntry(FileID FID,
1497 bool *Invalid = nullptr) const {
1498 if (FID.ID == 0 || FID.ID == -1) {
1499 if (Invalid) *Invalid = true;
1500 return LocalSLocEntryTable[0];
1502 return getSLocEntryByID(FID.ID, Invalid);
1505 unsigned getNextLocalOffset() const { return NextLocalOffset; }
1507 void setExternalSLocEntrySource(ExternalSLocEntrySource *Source) {
1508 assert(LoadedSLocEntryTable.empty() &&
1509 "Invalidating existing loaded entries");
1510 ExternalSLocEntries = Source;
1513 /// \brief Allocate a number of loaded SLocEntries, which will be actually
1514 /// loaded on demand from the external source.
1516 /// NumSLocEntries will be allocated, which occupy a total of TotalSize space
1517 /// in the global source view. The lowest ID and the base offset of the
1518 /// entries will be returned.
1519 std::pair<int, unsigned>
1520 AllocateLoadedSLocEntries(unsigned NumSLocEntries, unsigned TotalSize);
1522 /// \brief Returns true if \p Loc came from a PCH/Module.
1523 bool isLoadedSourceLocation(SourceLocation Loc) const {
1524 return Loc.getOffset() >= CurrentLoadedOffset;
1527 /// \brief Returns true if \p Loc did not come from a PCH/Module.
1528 bool isLocalSourceLocation(SourceLocation Loc) const {
1529 return Loc.getOffset() < NextLocalOffset;
1532 /// \brief Returns true if \p FID came from a PCH/Module.
1533 bool isLoadedFileID(FileID FID) const {
1534 assert(FID.ID != -1 && "Using FileID sentinel value");
1538 /// \brief Returns true if \p FID did not come from a PCH/Module.
1539 bool isLocalFileID(FileID FID) const {
1540 return !isLoadedFileID(FID);
1543 /// Gets the location of the immediate macro caller, one level up the stack
1544 /// toward the initial macro typed into the source.
1545 SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const {
1546 if (!Loc.isMacroID()) return Loc;
1548 // When we have the location of (part of) an expanded parameter, its
1549 // spelling location points to the argument as expanded in the macro call,
1550 // and therefore is used to locate the macro caller.
1551 if (isMacroArgExpansion(Loc))
1552 return getImmediateSpellingLoc(Loc);
1554 // Otherwise, the caller of the macro is located where this macro is
1555 // expanded (while the spelling is part of the macro definition).
1556 return getImmediateExpansionRange(Loc).first;
1560 const llvm::MemoryBuffer *getFakeBufferForRecovery() const;
1561 const SrcMgr::ContentCache *getFakeContentCacheForRecovery() const;
1563 const SrcMgr::SLocEntry &loadSLocEntry(unsigned Index, bool *Invalid) const;
1565 /// \brief Get the entry with the given unwrapped FileID.
1566 const SrcMgr::SLocEntry &getSLocEntryByID(int ID,
1567 bool *Invalid = nullptr) const {
1568 assert(ID != -1 && "Using FileID sentinel value");
1570 return getLoadedSLocEntryByID(ID, Invalid);
1571 return getLocalSLocEntry(static_cast<unsigned>(ID), Invalid);
1574 const SrcMgr::SLocEntry &
1575 getLoadedSLocEntryByID(int ID, bool *Invalid = nullptr) const {
1576 return getLoadedSLocEntry(static_cast<unsigned>(-ID - 2), Invalid);
1579 /// Implements the common elements of storing an expansion info struct into
1580 /// the SLocEntry table and producing a source location that refers to it.
1581 SourceLocation createExpansionLocImpl(const SrcMgr::ExpansionInfo &Expansion,
1584 unsigned LoadedOffset = 0);
1586 /// \brief Return true if the specified FileID contains the
1587 /// specified SourceLocation offset. This is a very hot method.
1588 inline bool isOffsetInFileID(FileID FID, unsigned SLocOffset) const {
1589 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID);
1590 // If the entry is after the offset, it can't contain it.
1591 if (SLocOffset < Entry.getOffset()) return false;
1593 // If this is the very last entry then it does.
1597 // If it is the last local entry, then it does if the location is local.
1598 if (FID.ID+1 == static_cast<int>(LocalSLocEntryTable.size()))
1599 return SLocOffset < NextLocalOffset;
1601 // Otherwise, the entry after it has to not include it. This works for both
1602 // local and loaded entries.
1603 return SLocOffset < getSLocEntryByID(FID.ID+1).getOffset();
1606 /// \brief Returns the previous in-order FileID or an invalid FileID if there
1607 /// is no previous one.
1608 FileID getPreviousFileID(FileID FID) const;
1610 /// \brief Returns the next in-order FileID or an invalid FileID if there is
1612 FileID getNextFileID(FileID FID) const;
1614 /// \brief Create a new fileID for the specified ContentCache and
1615 /// include position.
1617 /// This works regardless of whether the ContentCache corresponds to a
1618 /// file or some other input source.
1619 FileID createFileID(const SrcMgr::ContentCache* File,
1620 SourceLocation IncludePos,
1621 SrcMgr::CharacteristicKind DirCharacter,
1622 int LoadedID, unsigned LoadedOffset);
1624 const SrcMgr::ContentCache *
1625 getOrCreateContentCache(const FileEntry *SourceFile,
1626 bool isSystemFile = false);
1628 /// \brief Create a new ContentCache for the specified memory buffer.
1629 const SrcMgr::ContentCache*
1630 createMemBufferContentCache(const llvm::MemoryBuffer *Buf);
1632 FileID getFileIDSlow(unsigned SLocOffset) const;
1633 FileID getFileIDLocal(unsigned SLocOffset) const;
1634 FileID getFileIDLoaded(unsigned SLocOffset) const;
1636 SourceLocation getExpansionLocSlowCase(SourceLocation Loc) const;
1637 SourceLocation getSpellingLocSlowCase(SourceLocation Loc) const;
1638 SourceLocation getFileLocSlowCase(SourceLocation Loc) const;
1640 std::pair<FileID, unsigned>
1641 getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry *E) const;
1642 std::pair<FileID, unsigned>
1643 getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
1644 unsigned Offset) const;
1645 void computeMacroArgsCache(MacroArgsMap *&MacroArgsCache, FileID FID) const;
1646 void associateFileChunkWithMacroArgExp(MacroArgsMap &MacroArgsCache,
1648 SourceLocation SpellLoc,
1649 SourceLocation ExpansionLoc,
1650 unsigned ExpansionLength) const;
1651 friend class ASTReader;
1652 friend class ASTWriter;
1655 /// \brief Comparison function object.
1656 template<typename T>
1657 class BeforeThanCompare;
1659 /// \brief Compare two source locations.
1661 class BeforeThanCompare<SourceLocation> {
1665 explicit BeforeThanCompare(SourceManager &SM) : SM(SM) { }
1667 bool operator()(SourceLocation LHS, SourceLocation RHS) const {
1668 return SM.isBeforeInTranslationUnit(LHS, RHS);
1672 /// \brief Compare two non-overlapping source ranges.
1674 class BeforeThanCompare<SourceRange> {
1678 explicit BeforeThanCompare(SourceManager &SM) : SM(SM) { }
1680 bool operator()(SourceRange LHS, SourceRange RHS) {
1681 return SM.isBeforeInTranslationUnit(LHS.getBegin(), RHS.getBegin());
1685 } // end namespace clang