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