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/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"
51 #include <cassert>
52 #include <map>
53 #include <memory>
54 #include <vector>
55 
56 namespace clang {
57 
58 class DiagnosticsEngine;
59 class SourceManager;
60 class FileManager;
61 class FileEntry;
62 class LineTableInfo;
63 class LangOptions;
64 class ASTWriter;
65 class ASTReader;
66 
67 /// \brief Public enums and private classes that are part of the
68 /// SourceManager implementation.
69 ///
70 namespace SrcMgr {
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.
73   ///
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.
77   ///
78   enum CharacteristicKind {
79     C_User, C_System, C_ExternCSystem
80   };
81 
82   /// \brief One instance of this struct is kept for every file loaded or used.
83   ///
84   /// This object owns the MemoryBuffer object.
85   class ContentCache {
86     enum CCFlags {
87       /// \brief Whether the buffer is invalid.
88       InvalidFlag = 0x01,
89       /// \brief Whether the buffer should not be freed on destruction.
90       DoNotFreeFlag = 0x02
91     };
92 
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
99     // members.
100     llvm::AlignedCharArray<8, 1> NonceAligner;
101 
102     /// \brief The actual buffer containing the characters from the input
103     /// file.
104     ///
105     /// This is owned by the ContentCache object.  The bits indicate
106     /// whether the buffer is invalid.
107     mutable llvm::PointerIntPair<llvm::MemoryBuffer *, 2> Buffer;
108 
109   public:
110     /// \brief Reference to the file entry representing this ContentCache.
111     ///
112     /// This reference does not own the FileEntry object.
113     ///
114     /// It is possible for this to be NULL if the ContentCache encapsulates
115     /// an imaginary text buffer.
116     const FileEntry *OrigEntry;
117 
118     /// \brief References the file which the contents were actually loaded from.
119     ///
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;
123 
124     /// \brief A bump pointer allocated array of offsets for each source line.
125     ///
126     /// This is lazily computed.  This is owned by the SourceManager
127     /// BumpPointerAllocator object.
128     unsigned *SourceLineCache;
129 
130     /// \brief The number of lines in this ContentCache.
131     ///
132     /// This is only valid if SourceLineCache is non-null.
133     unsigned NumLines : 31;
134 
135     /// \brief Indicates whether the buffer itself was provided to override
136     /// the actual file contents.
137     ///
138     /// When true, the original entry may be a virtual file that does not
139     /// exist.
140     unsigned BufferOverridden : 1;
141 
142     /// \brief True if this content cache was initially created for a source
143     /// file considered as a system one.
144     unsigned IsSystemFile : 1;
145 
146     ContentCache(const FileEntry *Ent = nullptr)
Buffer(nullptr,false)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.
151     }
152 
ContentCache(const FileEntry * Ent,const FileEntry * contentEnt)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) {}
157 
158     ~ContentCache();
159 
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.
ContentCache(const ContentCache & RHS)163     ContentCache(const ContentCache &RHS)
164       : Buffer(nullptr, false), SourceLineCache(nullptr),
165         BufferOverridden(false), IsSystemFile(false) {
166       OrigEntry = RHS.OrigEntry;
167       ContentsEntry = RHS.ContentsEntry;
168 
169       assert(RHS.Buffer.getPointer() == nullptr &&
170              RHS.SourceLineCache == nullptr &&
171              "Passed ContentCache object cannot own a buffer.");
172 
173       NumLines = RHS.NumLines;
174     }
175 
176     /// \brief Returns the memory buffer for the associated content.
177     ///
178     /// \param Diag Object through which diagnostics will be emitted if the
179     ///   buffer cannot be retrieved.
180     ///
181     /// \param Loc If specified, is the location that invalid file diagnostics
182     ///   will be emitted at.
183     ///
184     /// \param Invalid If non-NULL, will be set \c true if an error occurred.
185     llvm::MemoryBuffer *getBuffer(DiagnosticsEngine &Diag,
186                                   const SourceManager &SM,
187                                   SourceLocation Loc = SourceLocation(),
188                                   bool *Invalid = nullptr) const;
189 
190     /// \brief Returns the size of the content encapsulated by this
191     /// ContentCache.
192     ///
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;
197 
198     /// \brief Returns the number of bytes actually mapped for this
199     /// ContentCache.
200     ///
201     /// This can be 0 if the MemBuffer was not actually expanded.
202     unsigned getSizeBytesMapped() const;
203 
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;
207 
setBuffer(std::unique_ptr<llvm::MemoryBuffer> B)208     void setBuffer(std::unique_ptr<llvm::MemoryBuffer> B) {
209       assert(!Buffer.getPointer() && "MemoryBuffer already set.");
210       Buffer.setPointer(B.release());
211       Buffer.setInt(0);
212     }
213 
214     /// \brief Get the underlying buffer, returning NULL if the buffer is not
215     /// yet available.
getRawBuffer()216     llvm::MemoryBuffer *getRawBuffer() const { return Buffer.getPointer(); }
217 
218     /// \brief Replace the existing buffer (which will be deleted)
219     /// with the given buffer.
220     void replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree = false);
221 
222     /// \brief Determine whether the buffer itself is invalid.
isBufferInvalid()223     bool isBufferInvalid() const {
224       return Buffer.getInt() & InvalidFlag;
225     }
226 
227     /// \brief Determine whether the buffer should be freed.
shouldFreeBuffer()228     bool shouldFreeBuffer() const {
229       return (Buffer.getInt() & DoNotFreeFlag) == 0;
230     }
231 
232   private:
233     // Disable assignments.
234     ContentCache &operator=(const ContentCache& RHS) LLVM_DELETED_FUNCTION;
235   };
236 
237   // Assert that the \c ContentCache objects will always be 8-byte aligned so
238   // that we can pack 3 bits of integer into pointers to such objects.
239   static_assert(llvm::AlignOf<ContentCache>::Alignment >= 8,
240                 "ContentCache must be 8-byte aligned.");
241 
242   /// \brief Information about a FileID, basically just the logical file
243   /// that it represents and include stack information.
244   ///
245   /// Each FileInfo has include stack information, indicating where it came
246   /// from. This information encodes the \#include chain that a token was
247   /// expanded from. The main include file has an invalid IncludeLoc.
248   ///
249   /// FileInfos contain a "ContentCache *", with the contents of the file.
250   ///
251   class FileInfo {
252     /// \brief The location of the \#include that brought in this file.
253     ///
254     /// This is an invalid SLOC for the main file (top of the \#include chain).
255     unsigned IncludeLoc;  // Really a SourceLocation
256 
257     /// \brief Number of FileIDs (files and macros) that were created during
258     /// preprocessing of this \#include, including this SLocEntry.
259     ///
260     /// Zero means the preprocessor didn't provide such info for this SLocEntry.
261     unsigned NumCreatedFIDs;
262 
263     /// \brief Contains the ContentCache* and the bits indicating the
264     /// characteristic of the file and whether it has \#line info, all
265     /// bitmangled together.
266     uintptr_t Data;
267 
268     friend class clang::SourceManager;
269     friend class clang::ASTWriter;
270     friend class clang::ASTReader;
271   public:
272     /// \brief Return a FileInfo object.
get(SourceLocation IL,const ContentCache * Con,CharacteristicKind FileCharacter)273     static FileInfo get(SourceLocation IL, const ContentCache *Con,
274                         CharacteristicKind FileCharacter) {
275       FileInfo X;
276       X.IncludeLoc = IL.getRawEncoding();
277       X.NumCreatedFIDs = 0;
278       X.Data = (uintptr_t)Con;
279       assert((X.Data & 7) == 0 &&"ContentCache pointer insufficiently aligned");
280       assert((unsigned)FileCharacter < 4 && "invalid file character");
281       X.Data |= (unsigned)FileCharacter;
282       return X;
283     }
284 
getIncludeLoc()285     SourceLocation getIncludeLoc() const {
286       return SourceLocation::getFromRawEncoding(IncludeLoc);
287     }
getContentCache()288     const ContentCache* getContentCache() const {
289       return reinterpret_cast<const ContentCache*>(Data & ~uintptr_t(7));
290     }
291 
292     /// \brief Return whether this is a system header or not.
getFileCharacteristic()293     CharacteristicKind getFileCharacteristic() const {
294       return (CharacteristicKind)(Data & 3);
295     }
296 
297     /// \brief Return true if this FileID has \#line directives in it.
hasLineDirectives()298     bool hasLineDirectives() const { return (Data & 4) != 0; }
299 
300     /// \brief Set the flag that indicates that this FileID has
301     /// line table entries associated with it.
setHasLineDirectives()302     void setHasLineDirectives() {
303       Data |= 4;
304     }
305   };
306 
307   /// \brief Each ExpansionInfo encodes the expansion location - where
308   /// the token was ultimately expanded, and the SpellingLoc - where the actual
309   /// character data for the token came from.
310   class ExpansionInfo {
311     // Really these are all SourceLocations.
312 
313     /// \brief Where the spelling for the token can be found.
314     unsigned SpellingLoc;
315 
316     /// In a macro expansion, ExpansionLocStart and ExpansionLocEnd
317     /// indicate the start and end of the expansion. In object-like macros,
318     /// they will be the same. In a function-like macro expansion, the start
319     /// will be the identifier and the end will be the ')'. Finally, in
320     /// macro-argument instantiations, the end will be 'SourceLocation()', an
321     /// invalid location.
322     unsigned ExpansionLocStart, ExpansionLocEnd;
323 
324   public:
getSpellingLoc()325     SourceLocation getSpellingLoc() const {
326       return SourceLocation::getFromRawEncoding(SpellingLoc);
327     }
getExpansionLocStart()328     SourceLocation getExpansionLocStart() const {
329       return SourceLocation::getFromRawEncoding(ExpansionLocStart);
330     }
getExpansionLocEnd()331     SourceLocation getExpansionLocEnd() const {
332       SourceLocation EndLoc =
333         SourceLocation::getFromRawEncoding(ExpansionLocEnd);
334       return EndLoc.isInvalid() ? getExpansionLocStart() : EndLoc;
335     }
336 
getExpansionLocRange()337     std::pair<SourceLocation,SourceLocation> getExpansionLocRange() const {
338       return std::make_pair(getExpansionLocStart(), getExpansionLocEnd());
339     }
340 
isMacroArgExpansion()341     bool isMacroArgExpansion() const {
342       // Note that this needs to return false for default constructed objects.
343       return getExpansionLocStart().isValid() &&
344         SourceLocation::getFromRawEncoding(ExpansionLocEnd).isInvalid();
345     }
346 
isMacroBodyExpansion()347     bool isMacroBodyExpansion() const {
348       return getExpansionLocStart().isValid() &&
349         SourceLocation::getFromRawEncoding(ExpansionLocEnd).isValid();
350     }
351 
isFunctionMacroExpansion()352     bool isFunctionMacroExpansion() const {
353       return getExpansionLocStart().isValid() &&
354           getExpansionLocStart() != getExpansionLocEnd();
355     }
356 
357     /// \brief Return a ExpansionInfo for an expansion.
358     ///
359     /// Start and End specify the expansion range (where the macro is
360     /// expanded), and SpellingLoc specifies the spelling location (where
361     /// the characters from the token come from). All three can refer to
362     /// normal File SLocs or expansion locations.
create(SourceLocation SpellingLoc,SourceLocation Start,SourceLocation End)363     static ExpansionInfo create(SourceLocation SpellingLoc,
364                                 SourceLocation Start, SourceLocation End) {
365       ExpansionInfo X;
366       X.SpellingLoc = SpellingLoc.getRawEncoding();
367       X.ExpansionLocStart = Start.getRawEncoding();
368       X.ExpansionLocEnd = End.getRawEncoding();
369       return X;
370     }
371 
372     /// \brief Return a special ExpansionInfo for the expansion of
373     /// a macro argument into a function-like macro's body.
374     ///
375     /// ExpansionLoc specifies the expansion location (where the macro is
376     /// expanded). This doesn't need to be a range because a macro is always
377     /// expanded at a macro parameter reference, and macro parameters are
378     /// always exactly one token. SpellingLoc specifies the spelling location
379     /// (where the characters from the token come from). ExpansionLoc and
380     /// SpellingLoc can both refer to normal File SLocs or expansion locations.
381     ///
382     /// Given the code:
383     /// \code
384     ///   #define F(x) f(x)
385     ///   F(42);
386     /// \endcode
387     ///
388     /// When expanding '\c F(42)', the '\c x' would call this with an
389     /// SpellingLoc pointing at '\c 42' and an ExpansionLoc pointing at its
390     /// location in the definition of '\c F'.
createForMacroArg(SourceLocation SpellingLoc,SourceLocation ExpansionLoc)391     static ExpansionInfo createForMacroArg(SourceLocation SpellingLoc,
392                                            SourceLocation ExpansionLoc) {
393       // We store an intentionally invalid source location for the end of the
394       // expansion range to mark that this is a macro argument ion rather than
395       // a normal one.
396       return create(SpellingLoc, ExpansionLoc, SourceLocation());
397     }
398   };
399 
400   /// \brief This is a discriminated union of FileInfo and ExpansionInfo.
401   ///
402   /// SourceManager keeps an array of these objects, and they are uniquely
403   /// identified by the FileID datatype.
404   class SLocEntry {
405     unsigned Offset;   // low bit is set for expansion info.
406     union {
407       FileInfo File;
408       ExpansionInfo Expansion;
409     };
410   public:
getOffset()411     unsigned getOffset() const { return Offset >> 1; }
412 
isExpansion()413     bool isExpansion() const { return Offset & 1; }
isFile()414     bool isFile() const { return !isExpansion(); }
415 
getFile()416     const FileInfo &getFile() const {
417       assert(isFile() && "Not a file SLocEntry!");
418       return File;
419     }
420 
getExpansion()421     const ExpansionInfo &getExpansion() const {
422       assert(isExpansion() && "Not a macro expansion SLocEntry!");
423       return Expansion;
424     }
425 
get(unsigned Offset,const FileInfo & FI)426     static SLocEntry get(unsigned Offset, const FileInfo &FI) {
427       SLocEntry E;
428       E.Offset = Offset << 1;
429       E.File = FI;
430       return E;
431     }
432 
get(unsigned Offset,const ExpansionInfo & Expansion)433     static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
434       SLocEntry E;
435       E.Offset = (Offset << 1) | 1;
436       E.Expansion = Expansion;
437       return E;
438     }
439   };
440 }  // end SrcMgr namespace.
441 
442 /// \brief External source of source location entries.
443 class ExternalSLocEntrySource {
444 public:
445   virtual ~ExternalSLocEntrySource();
446 
447   /// \brief Read the source location entry with index ID, which will always be
448   /// less than -1.
449   ///
450   /// \returns true if an error occurred that prevented the source-location
451   /// entry from being loaded.
452   virtual bool ReadSLocEntry(int ID) = 0;
453 
454   /// \brief Retrieve the module import location and name for the given ID, if
455   /// in fact it was loaded from a module (rather than, say, a precompiled
456   /// header).
457   virtual std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) = 0;
458 };
459 
460 
461 /// \brief Holds the cache used by isBeforeInTranslationUnit.
462 ///
463 /// The cache structure is complex enough to be worth breaking out of
464 /// SourceManager.
465 class InBeforeInTUCacheEntry {
466   /// \brief The FileID's of the cached query.
467   ///
468   /// If these match up with a subsequent query, the result can be reused.
469   FileID LQueryFID, RQueryFID;
470 
471   /// \brief True if LQueryFID was created before RQueryFID.
472   ///
473   /// This is used to compare macro expansion locations.
474   bool IsLQFIDBeforeRQFID;
475 
476   /// \brief The file found in common between the two \#include traces, i.e.,
477   /// the nearest common ancestor of the \#include tree.
478   FileID CommonFID;
479 
480   /// \brief The offset of the previous query in CommonFID.
481   ///
482   /// Usually, this represents the location of the \#include for QueryFID, but
483   /// if LQueryFID is a parent of RQueryFID (or vice versa) then these can be a
484   /// random token in the parent.
485   unsigned LCommonOffset, RCommonOffset;
486 public:
487   /// \brief Return true if the currently cached values match up with
488   /// the specified LHS/RHS query.
489   ///
490   /// If not, we can't use the cache.
isCacheValid(FileID LHS,FileID RHS)491   bool isCacheValid(FileID LHS, FileID RHS) const {
492     return LQueryFID == LHS && RQueryFID == RHS;
493   }
494 
495   /// \brief If the cache is valid, compute the result given the
496   /// specified offsets in the LHS/RHS FileID's.
getCachedResult(unsigned LOffset,unsigned ROffset)497   bool getCachedResult(unsigned LOffset, unsigned ROffset) const {
498     // If one of the query files is the common file, use the offset.  Otherwise,
499     // use the #include loc in the common file.
500     if (LQueryFID != CommonFID) LOffset = LCommonOffset;
501     if (RQueryFID != CommonFID) ROffset = RCommonOffset;
502 
503     // It is common for multiple macro expansions to be "included" from the same
504     // location (expansion location), in which case use the order of the FileIDs
505     // to determine which came first. This will also take care the case where
506     // one of the locations points at the inclusion/expansion point of the other
507     // in which case its FileID will come before the other.
508     if (LOffset == ROffset)
509       return IsLQFIDBeforeRQFID;
510 
511     return LOffset < ROffset;
512   }
513 
514   /// \brief Set up a new query.
setQueryFIDs(FileID LHS,FileID RHS,bool isLFIDBeforeRFID)515   void setQueryFIDs(FileID LHS, FileID RHS, bool isLFIDBeforeRFID) {
516     assert(LHS != RHS);
517     LQueryFID = LHS;
518     RQueryFID = RHS;
519     IsLQFIDBeforeRQFID = isLFIDBeforeRFID;
520   }
521 
clear()522   void clear() {
523     LQueryFID = RQueryFID = FileID();
524     IsLQFIDBeforeRQFID = false;
525   }
526 
setCommonLoc(FileID commonFID,unsigned lCommonOffset,unsigned rCommonOffset)527   void setCommonLoc(FileID commonFID, unsigned lCommonOffset,
528                     unsigned rCommonOffset) {
529     CommonFID = commonFID;
530     LCommonOffset = lCommonOffset;
531     RCommonOffset = rCommonOffset;
532   }
533 
534 };
535 
536 /// \brief The stack used when building modules on demand, which is used
537 /// to provide a link between the source managers of the different compiler
538 /// instances.
539 typedef ArrayRef<std::pair<std::string, FullSourceLoc> > ModuleBuildStack;
540 
541 /// \brief This class handles loading and caching of source files into memory.
542 ///
543 /// This object owns the MemoryBuffer objects for all of the loaded
544 /// files and assigns unique FileID's for each unique \#include chain.
545 ///
546 /// The SourceManager can be queried for information about SourceLocation
547 /// objects, turning them into either spelling or expansion locations. Spelling
548 /// locations represent where the bytes corresponding to a token came from and
549 /// expansion locations represent where the location is in the user's view. In
550 /// the case of a macro expansion, for example, the spelling location indicates
551 /// where the expanded token came from and the expansion location specifies
552 /// where it was expanded.
553 class SourceManager : public RefCountedBase<SourceManager> {
554   /// \brief DiagnosticsEngine object.
555   DiagnosticsEngine &Diag;
556 
557   FileManager &FileMgr;
558 
559   mutable llvm::BumpPtrAllocator ContentCacheAlloc;
560 
561   /// \brief Memoized information about all of the files tracked by this
562   /// SourceManager.
563   ///
564   /// This map allows us to merge ContentCache entries based
565   /// on their FileEntry*.  All ContentCache objects will thus have unique,
566   /// non-null, FileEntry pointers.
567   llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*> FileInfos;
568 
569   /// \brief True if the ContentCache for files that are overridden by other
570   /// files, should report the original file name. Defaults to true.
571   bool OverridenFilesKeepOriginalName;
572 
573   /// \brief True if non-system source files should be treated as volatile
574   /// (likely to change while trying to use them). Defaults to false.
575   bool UserFilesAreVolatile;
576 
577   struct OverriddenFilesInfoTy {
578     /// \brief Files that have been overridden with the contents from another
579     /// file.
580     llvm::DenseMap<const FileEntry *, const FileEntry *> OverriddenFiles;
581     /// \brief Files that were overridden with a memory buffer.
582     llvm::DenseSet<const FileEntry *> OverriddenFilesWithBuffer;
583   };
584 
585   /// \brief Lazily create the object keeping overridden files info, since
586   /// it is uncommonly used.
587   std::unique_ptr<OverriddenFilesInfoTy> OverriddenFilesInfo;
588 
getOverriddenFilesInfo()589   OverriddenFilesInfoTy &getOverriddenFilesInfo() {
590     if (!OverriddenFilesInfo)
591       OverriddenFilesInfo.reset(new OverriddenFilesInfoTy);
592     return *OverriddenFilesInfo;
593   }
594 
595   /// \brief Information about various memory buffers that we have read in.
596   ///
597   /// All FileEntry* within the stored ContentCache objects are NULL,
598   /// as they do not refer to a file.
599   std::vector<SrcMgr::ContentCache*> MemBufferInfos;
600 
601   /// \brief The table of SLocEntries that are local to this module.
602   ///
603   /// Positive FileIDs are indexes into this table. Entry 0 indicates an invalid
604   /// expansion.
605   SmallVector<SrcMgr::SLocEntry, 0> LocalSLocEntryTable;
606 
607   /// \brief The table of SLocEntries that are loaded from other modules.
608   ///
609   /// Negative FileIDs are indexes into this table. To get from ID to an index,
610   /// use (-ID - 2).
611   mutable SmallVector<SrcMgr::SLocEntry, 0> LoadedSLocEntryTable;
612 
613   /// \brief The starting offset of the next local SLocEntry.
614   ///
615   /// This is LocalSLocEntryTable.back().Offset + the size of that entry.
616   unsigned NextLocalOffset;
617 
618   /// \brief The starting offset of the latest batch of loaded SLocEntries.
619   ///
620   /// This is LoadedSLocEntryTable.back().Offset, except that that entry might
621   /// not have been loaded, so that value would be unknown.
622   unsigned CurrentLoadedOffset;
623 
624   /// \brief The highest possible offset is 2^31-1, so CurrentLoadedOffset
625   /// starts at 2^31.
626   static const unsigned MaxLoadedOffset = 1U << 31U;
627 
628   /// \brief A bitmap that indicates whether the entries of LoadedSLocEntryTable
629   /// have already been loaded from the external source.
630   ///
631   /// Same indexing as LoadedSLocEntryTable.
632   std::vector<bool> SLocEntryLoaded;
633 
634   /// \brief An external source for source location entries.
635   ExternalSLocEntrySource *ExternalSLocEntries;
636 
637   /// \brief A one-entry cache to speed up getFileID.
638   ///
639   /// LastFileIDLookup records the last FileID looked up or created, because it
640   /// is very common to look up many tokens from the same file.
641   mutable FileID LastFileIDLookup;
642 
643   /// \brief Holds information for \#line directives.
644   ///
645   /// This is referenced by indices from SLocEntryTable.
646   LineTableInfo *LineTable;
647 
648   /// \brief These ivars serve as a cache used in the getLineNumber
649   /// method which is used to speedup getLineNumber calls to nearby locations.
650   mutable FileID LastLineNoFileIDQuery;
651   mutable SrcMgr::ContentCache *LastLineNoContentCache;
652   mutable unsigned LastLineNoFilePos;
653   mutable unsigned LastLineNoResult;
654 
655   /// \brief The file ID for the main source file of the translation unit.
656   FileID MainFileID;
657 
658   /// \brief The file ID for the precompiled preamble there is one.
659   FileID PreambleFileID;
660 
661   // Statistics for -print-stats.
662   mutable unsigned NumLinearScans, NumBinaryProbes;
663 
664   /// \brief Associates a FileID with its "included/expanded in" decomposed
665   /// location.
666   ///
667   /// Used to cache results from and speed-up \c getDecomposedIncludedLoc
668   /// function.
669   mutable llvm::DenseMap<FileID, std::pair<FileID, unsigned> > IncludedLocMap;
670 
671   /// The key value into the IsBeforeInTUCache table.
672   typedef std::pair<FileID, FileID> IsBeforeInTUCacheKey;
673 
674   /// The IsBeforeInTranslationUnitCache is a mapping from FileID pairs
675   /// to cache results.
676   typedef llvm::DenseMap<IsBeforeInTUCacheKey, InBeforeInTUCacheEntry>
677           InBeforeInTUCache;
678 
679   /// Cache results for the isBeforeInTranslationUnit method.
680   mutable InBeforeInTUCache IBTUCache;
681   mutable InBeforeInTUCacheEntry IBTUCacheOverflow;
682 
683   /// Return the cache entry for comparing the given file IDs
684   /// for isBeforeInTranslationUnit.
685   InBeforeInTUCacheEntry &getInBeforeInTUCache(FileID LFID, FileID RFID) const;
686 
687   // Cache for the "fake" buffer used for error-recovery purposes.
688   mutable std::unique_ptr<llvm::MemoryBuffer> FakeBufferForRecovery;
689 
690   mutable std::unique_ptr<SrcMgr::ContentCache> FakeContentCacheForRecovery;
691 
692   /// \brief Lazily computed map of macro argument chunks to their expanded
693   /// source location.
694   typedef std::map<unsigned, SourceLocation> MacroArgsMap;
695 
696   mutable llvm::DenseMap<FileID, MacroArgsMap *> MacroArgsCacheMap;
697 
698   /// \brief The stack of modules being built, which is used to detect
699   /// cycles in the module dependency graph as modules are being built, as
700   /// well as to describe why we're rebuilding a particular module.
701   ///
702   /// There is no way to set this value from the command line. If we ever need
703   /// to do so (e.g., if on-demand module construction moves out-of-process),
704   /// we can add a cc1-level option to do so.
705   SmallVector<std::pair<std::string, FullSourceLoc>, 2> StoredModuleBuildStack;
706 
707   // SourceManager doesn't support copy construction.
708   explicit SourceManager(const SourceManager&) LLVM_DELETED_FUNCTION;
709   void operator=(const SourceManager&) LLVM_DELETED_FUNCTION;
710 public:
711   SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
712                 bool UserFilesAreVolatile = false);
713   ~SourceManager();
714 
715   void clearIDTables();
716 
getDiagnostics()717   DiagnosticsEngine &getDiagnostics() const { return Diag; }
718 
getFileManager()719   FileManager &getFileManager() const { return FileMgr; }
720 
721   /// \brief Set true if the SourceManager should report the original file name
722   /// for contents of files that were overridden by other files. Defaults to
723   /// true.
setOverridenFilesKeepOriginalName(bool value)724   void setOverridenFilesKeepOriginalName(bool value) {
725     OverridenFilesKeepOriginalName = value;
726   }
727 
728   /// \brief True if non-system source files should be treated as volatile
729   /// (likely to change while trying to use them).
userFilesAreVolatile()730   bool userFilesAreVolatile() const { return UserFilesAreVolatile; }
731 
732   /// \brief Retrieve the module build stack.
getModuleBuildStack()733   ModuleBuildStack getModuleBuildStack() const {
734     return StoredModuleBuildStack;
735   }
736 
737   /// \brief Set the module build stack.
setModuleBuildStack(ModuleBuildStack stack)738   void setModuleBuildStack(ModuleBuildStack stack) {
739     StoredModuleBuildStack.clear();
740     StoredModuleBuildStack.append(stack.begin(), stack.end());
741   }
742 
743   /// \brief Push an entry to the module build stack.
pushModuleBuildStack(StringRef moduleName,FullSourceLoc importLoc)744   void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc) {
745     StoredModuleBuildStack.push_back(std::make_pair(moduleName.str(),importLoc));
746   }
747 
748   //===--------------------------------------------------------------------===//
749   // MainFileID creation and querying methods.
750   //===--------------------------------------------------------------------===//
751 
752   /// \brief Returns the FileID of the main source file.
getMainFileID()753   FileID getMainFileID() const { return MainFileID; }
754 
755   /// \brief Set the file ID for the main source file.
setMainFileID(FileID FID)756   void setMainFileID(FileID FID) {
757     MainFileID = FID;
758   }
759 
760   /// \brief Set the file ID for the precompiled preamble.
setPreambleFileID(FileID Preamble)761   void setPreambleFileID(FileID Preamble) {
762     assert(PreambleFileID.isInvalid() && "PreambleFileID already set!");
763     PreambleFileID = Preamble;
764   }
765 
766   /// \brief Get the file ID for the precompiled preamble if there is one.
getPreambleFileID()767   FileID getPreambleFileID() const { return PreambleFileID; }
768 
769   //===--------------------------------------------------------------------===//
770   // Methods to create new FileID's and macro expansions.
771   //===--------------------------------------------------------------------===//
772 
773   /// \brief Create a new FileID that represents the specified file
774   /// being \#included from the specified IncludePosition.
775   ///
776   /// This translates NULL into standard input.
777   FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos,
778                       SrcMgr::CharacteristicKind FileCharacter,
779                       int LoadedID = 0, unsigned LoadedOffset = 0) {
780     const SrcMgr::ContentCache *
781       IR = getOrCreateContentCache(SourceFile,
782                               /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
783     assert(IR && "getOrCreateContentCache() cannot return NULL");
784     return createFileID(IR, IncludePos, FileCharacter, LoadedID, LoadedOffset);
785   }
786 
787   /// \brief Create a new FileID that represents the specified memory buffer.
788   ///
789   /// This does no caching of the buffer and takes ownership of the
790   /// MemoryBuffer, so only pass a MemoryBuffer to this once.
791   FileID createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
792                       SrcMgr::CharacteristicKind FileCharacter = SrcMgr::C_User,
793                       int LoadedID = 0, unsigned LoadedOffset = 0,
794                       SourceLocation IncludeLoc = SourceLocation()) {
795     return createFileID(createMemBufferContentCache(std::move(Buffer)),
796                         IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
797   }
798 
799   /// \brief Return a new SourceLocation that encodes the
800   /// fact that a token from SpellingLoc should actually be referenced from
801   /// ExpansionLoc, and that it represents the expansion of a macro argument
802   /// into the function-like macro body.
803   SourceLocation createMacroArgExpansionLoc(SourceLocation Loc,
804                                             SourceLocation ExpansionLoc,
805                                             unsigned TokLength);
806 
807   /// \brief Return a new SourceLocation that encodes the fact
808   /// that a token from SpellingLoc should actually be referenced from
809   /// ExpansionLoc.
810   SourceLocation createExpansionLoc(SourceLocation Loc,
811                                     SourceLocation ExpansionLocStart,
812                                     SourceLocation ExpansionLocEnd,
813                                     unsigned TokLength,
814                                     int LoadedID = 0,
815                                     unsigned LoadedOffset = 0);
816 
817   /// \brief Retrieve the memory buffer associated with the given file.
818   ///
819   /// \param Invalid If non-NULL, will be set \c true if an error
820   /// occurs while retrieving the memory buffer.
821   llvm::MemoryBuffer *getMemoryBufferForFile(const FileEntry *File,
822                                              bool *Invalid = nullptr);
823 
824   /// \brief Override the contents of the given source file by providing an
825   /// already-allocated buffer.
826   ///
827   /// \param SourceFile the source file whose contents will be overridden.
828   ///
829   /// \param Buffer the memory buffer whose contents will be used as the
830   /// data in the given source file.
831   ///
832   /// \param DoNotFree If true, then the buffer will not be freed when the
833   /// source manager is destroyed.
834   void overrideFileContents(const FileEntry *SourceFile,
835                             llvm::MemoryBuffer *Buffer, bool DoNotFree);
overrideFileContents(const FileEntry * SourceFile,std::unique_ptr<llvm::MemoryBuffer> Buffer)836   void overrideFileContents(const FileEntry *SourceFile,
837                             std::unique_ptr<llvm::MemoryBuffer> Buffer) {
838     overrideFileContents(SourceFile, Buffer.release(), /*DoNotFree*/ false);
839   }
840 
841   /// \brief Override the given source file with another one.
842   ///
843   /// \param SourceFile the source file which will be overridden.
844   ///
845   /// \param NewFile the file whose contents will be used as the
846   /// data instead of the contents of the given source file.
847   void overrideFileContents(const FileEntry *SourceFile,
848                             const FileEntry *NewFile);
849 
850   /// \brief Returns true if the file contents have been overridden.
isFileOverridden(const FileEntry * File)851   bool isFileOverridden(const FileEntry *File) {
852     if (OverriddenFilesInfo) {
853       if (OverriddenFilesInfo->OverriddenFilesWithBuffer.count(File))
854         return true;
855       if (OverriddenFilesInfo->OverriddenFiles.find(File) !=
856           OverriddenFilesInfo->OverriddenFiles.end())
857         return true;
858     }
859     return false;
860   }
861 
862   /// \brief Disable overridding the contents of a file, previously enabled
863   /// with #overrideFileContents.
864   ///
865   /// This should be called before parsing has begun.
866   void disableFileContentsOverride(const FileEntry *File);
867 
868   //===--------------------------------------------------------------------===//
869   // FileID manipulation methods.
870   //===--------------------------------------------------------------------===//
871 
872   /// \brief Return the buffer for the specified FileID.
873   ///
874   /// If there is an error opening this buffer the first time, this
875   /// manufactures a temporary buffer and returns a non-empty error string.
876   llvm::MemoryBuffer *getBuffer(FileID FID, SourceLocation Loc,
877                                 bool *Invalid = nullptr) const {
878     bool MyInvalid = false;
879     const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
880     if (MyInvalid || !Entry.isFile()) {
881       if (Invalid)
882         *Invalid = true;
883 
884       return getFakeBufferForRecovery();
885     }
886 
887     return Entry.getFile().getContentCache()->getBuffer(Diag, *this, Loc,
888                                                         Invalid);
889   }
890 
891   llvm::MemoryBuffer *getBuffer(FileID FID, bool *Invalid = nullptr) const {
892     bool MyInvalid = false;
893     const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
894     if (MyInvalid || !Entry.isFile()) {
895       if (Invalid)
896         *Invalid = true;
897 
898       return getFakeBufferForRecovery();
899     }
900 
901     return Entry.getFile().getContentCache()->getBuffer(Diag, *this,
902                                                         SourceLocation(),
903                                                         Invalid);
904   }
905 
906   /// \brief Returns the FileEntry record for the provided FileID.
getFileEntryForID(FileID FID)907   const FileEntry *getFileEntryForID(FileID FID) const {
908     bool MyInvalid = false;
909     const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
910     if (MyInvalid || !Entry.isFile())
911       return nullptr;
912 
913     const SrcMgr::ContentCache *Content = Entry.getFile().getContentCache();
914     if (!Content)
915       return nullptr;
916     return Content->OrigEntry;
917   }
918 
919   /// \brief Returns the FileEntry record for the provided SLocEntry.
getFileEntryForSLocEntry(const SrcMgr::SLocEntry & sloc)920   const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const
921   {
922     const SrcMgr::ContentCache *Content = sloc.getFile().getContentCache();
923     if (!Content)
924       return nullptr;
925     return Content->OrigEntry;
926   }
927 
928   /// \brief Return a StringRef to the source buffer data for the
929   /// specified FileID.
930   ///
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;
934 
935   /// \brief Get the number of FileIDs (files and macros) that were created
936   /// during preprocessing of \p FID, including it.
getNumCreatedFIDsForFileID(FileID FID)937   unsigned getNumCreatedFIDsForFileID(FileID FID) const {
938     bool Invalid = false;
939     const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
940     if (Invalid || !Entry.isFile())
941       return 0;
942 
943     return Entry.getFile().NumCreatedFIDs;
944   }
945 
946   /// \brief Set the number of FileIDs (files and macros) that were created
947   /// during preprocessing of \p FID, including it.
setNumCreatedFIDsForFileID(FileID FID,unsigned NumFIDs)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())
952       return;
953 
954     assert(Entry.getFile().NumCreatedFIDs == 0 && "Already set!");
955     const_cast<SrcMgr::FileInfo &>(Entry.getFile()).NumCreatedFIDs = NumFIDs;
956   }
957 
958   //===--------------------------------------------------------------------===//
959   // SourceLocation manipulation methods.
960   //===--------------------------------------------------------------------===//
961 
962   /// \brief Return the FileID for a SourceLocation.
963   ///
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.
967   ///
getFileID(SourceLocation SpellingLoc)968   FileID getFileID(SourceLocation SpellingLoc) const {
969     unsigned SLocOffset = SpellingLoc.getOffset();
970 
971     // If our one-entry cache covers this offset, just return it.
972     if (isOffsetInFileID(LastFileIDLookup, SLocOffset))
973       return LastFileIDLookup;
974 
975     return getFileIDSlow(SLocOffset);
976   }
977 
978   /// \brief Return the filename of the file containing a SourceLocation.
getFilename(SourceLocation SpellingLoc)979   StringRef getFilename(SourceLocation SpellingLoc) const {
980     if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
981       return F->getName();
982     return StringRef();
983   }
984 
985   /// \brief Return the source location corresponding to the first byte of
986   /// the specified file.
getLocForStartOfFile(FileID FID)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();
992 
993     unsigned FileOffset = Entry.getOffset();
994     return SourceLocation::getFileLoc(FileOffset);
995   }
996 
997   /// \brief Return the source location corresponding to the last byte of the
998   /// specified file.
getLocForEndOfFile(FileID FID)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();
1004 
1005     unsigned FileOffset = Entry.getOffset();
1006     return SourceLocation::getFileLoc(FileOffset + getFileIDSize(FID));
1007   }
1008 
1009   /// \brief Returns the include location if \p FID is a \#include'd file
1010   /// otherwise it returns an invalid location.
getIncludeLoc(FileID FID)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();
1016 
1017     return Entry.getFile().getIncludeLoc();
1018   }
1019 
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>
getModuleImportLoc(SourceLocation Loc)1024   getModuleImportLoc(SourceLocation Loc) const {
1025     FileID FID = getFileID(Loc);
1026 
1027     // Positive file IDs are in the current translation unit, and -1 is a
1028     // placeholder.
1029     if (FID.ID >= -1)
1030       return std::make_pair(SourceLocation(), "");
1031 
1032     return ExternalSLocEntries->getModuleImportLoc(FID.ID);
1033   }
1034 
1035   /// \brief Given a SourceLocation object \p Loc, return the expansion
1036   /// location referenced by the ID.
getExpansionLoc(SourceLocation Loc)1037   SourceLocation getExpansionLoc(SourceLocation Loc) const {
1038     // Handle the non-mapped case inline, defer to out of line code to handle
1039     // expansions.
1040     if (Loc.isFileID()) return Loc;
1041     return getExpansionLocSlowCase(Loc);
1042   }
1043 
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.
getFileLoc(SourceLocation Loc)1047   SourceLocation getFileLoc(SourceLocation Loc) const {
1048     if (Loc.isFileID()) return Loc;
1049     return getFileLocSlowCase(Loc);
1050   }
1051 
1052   /// \brief Return the start/end of the expansion information for an
1053   /// expansion location.
1054   ///
1055   /// \pre \p Loc is required to be an expansion location.
1056   std::pair<SourceLocation,SourceLocation>
1057   getImmediateExpansionRange(SourceLocation Loc) const;
1058 
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;
1063 
1064 
1065   /// \brief Given a SourceLocation object, return the spelling
1066   /// location referenced by the ID.
1067   ///
1068   /// This is the place where the characters that make up the lexed token
1069   /// can be found.
getSpellingLoc(SourceLocation Loc)1070   SourceLocation getSpellingLoc(SourceLocation Loc) const {
1071     // Handle the non-mapped case inline, defer to out of line code to handle
1072     // expansions.
1073     if (Loc.isFileID()) return Loc;
1074     return getSpellingLocSlowCase(Loc);
1075   }
1076 
1077   /// \brief Given a SourceLocation object, return the spelling location
1078   /// referenced by the ID.
1079   ///
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;
1084 
1085   /// \brief Decompose the specified location into a raw FileID + Offset pair.
1086   ///
1087   /// The first element is the FileID, the second is the offset from the
1088   /// start of the buffer of the location.
getDecomposedLoc(SourceLocation Loc)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);
1093     if (Invalid)
1094       return std::make_pair(FileID(), 0);
1095     return std::make_pair(FID, Loc.getOffset()-E.getOffset());
1096   }
1097 
1098   /// \brief Decompose the specified location into a raw FileID + Offset pair.
1099   ///
1100   /// If the location is an expansion record, walk through it until we find
1101   /// the final location expanded.
1102   std::pair<FileID, unsigned>
getDecomposedExpansionLoc(SourceLocation Loc)1103   getDecomposedExpansionLoc(SourceLocation Loc) const {
1104     FileID FID = getFileID(Loc);
1105     bool Invalid = false;
1106     const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
1107     if (Invalid)
1108       return std::make_pair(FileID(), 0);
1109 
1110     unsigned Offset = Loc.getOffset()-E->getOffset();
1111     if (Loc.isFileID())
1112       return std::make_pair(FID, Offset);
1113 
1114     return getDecomposedExpansionLocSlowCase(E);
1115   }
1116 
1117   /// \brief Decompose the specified location into a raw FileID + Offset pair.
1118   ///
1119   /// If the location is an expansion record, walk through it until we find
1120   /// its spelling record.
1121   std::pair<FileID, unsigned>
getDecomposedSpellingLoc(SourceLocation Loc)1122   getDecomposedSpellingLoc(SourceLocation Loc) const {
1123     FileID FID = getFileID(Loc);
1124     bool Invalid = false;
1125     const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
1126     if (Invalid)
1127       return std::make_pair(FileID(), 0);
1128 
1129     unsigned Offset = Loc.getOffset()-E->getOffset();
1130     if (Loc.isFileID())
1131       return std::make_pair(FID, Offset);
1132     return getDecomposedSpellingLocSlowCase(E, Offset);
1133   }
1134 
1135   /// \brief Returns the "included/expanded in" decomposed location of the given
1136   /// FileID.
1137   std::pair<FileID, unsigned> getDecomposedIncludedLoc(FileID FID) const;
1138 
1139   /// \brief Returns the offset from the start of the file that the
1140   /// specified SourceLocation represents.
1141   ///
1142   /// This is not very meaningful for a macro ID.
getFileOffset(SourceLocation SpellingLoc)1143   unsigned getFileOffset(SourceLocation SpellingLoc) const {
1144     return getDecomposedLoc(SpellingLoc).second;
1145   }
1146 
1147   /// \brief Tests whether the given source location represents a macro
1148   /// argument's expansion into the function-like macro definition.
1149   ///
1150   /// Such source locations only appear inside of the expansion
1151   /// locations representing where a particular function-like macro was
1152   /// expanded.
1153   bool isMacroArgExpansion(SourceLocation Loc) const;
1154 
1155   /// \brief Tests whether the given source location represents the expansion of
1156   /// a macro body.
1157   ///
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;
1161 
1162   /// \brief Returns true if the given MacroID location points at the beginning
1163   /// of the immediate macro expansion.
1164   ///
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;
1169 
1170   /// \brief Returns true if the given MacroID location points at the character
1171   /// end of the immediate macro expansion.
1172   ///
1173   /// \param MacroEnd If non-null and function returns true, it is set to the
1174   /// character end location of the immediate macro expansion.
1175   bool
1176   isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1177                                    SourceLocation *MacroEnd = nullptr) const;
1178 
1179   /// \brief Returns true if \p Loc is inside the [\p Start, +\p Length)
1180   /// chunk of the source location address space.
1181   ///
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) {
1196       if (RelativeOffset)
1197         *RelativeOffset = LocOffs - BeginOffs;
1198       return true;
1199     }
1200 
1201     return false;
1202   }
1203 
1204   /// \brief Return true if both \p LHS and \p RHS are in the local source
1205   /// location address space or the loaded one.
1206   ///
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.
isInSameSLocAddrSpace(SourceLocation LHS,SourceLocation RHS,int * RelativeOffset)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;
1214 
1215     if (LHSLoaded == RHSLoaded) {
1216       if (RelativeOffset)
1217         *RelativeOffset = RHSOffs - LHSOffs;
1218       return true;
1219     }
1220 
1221     return false;
1222   }
1223 
1224   //===--------------------------------------------------------------------===//
1225   // Queries about the code at a SourceLocation.
1226   //===--------------------------------------------------------------------===//
1227 
1228   /// \brief Return a pointer to the start of the specified location
1229   /// in the appropriate spelling MemoryBuffer.
1230   ///
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;
1234 
1235   /// \brief Return the column # for the specified file position.
1236   ///
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;
1249 
1250   /// \brief Given a SourceLocation, return the spelling line number
1251   /// for the position indicated.
1252   ///
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
1255   /// diagnostic.
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;
1260 
1261   /// \brief Return the filename or buffer identifier of the buffer the
1262   /// location is in.
1263   ///
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;
1267 
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.
1271   ///
1272   /// This state can be modified with flags on GNU linemarker directives like:
1273   /// \code
1274   ///   # 4 "foo.h" 3
1275   /// \endcode
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;
1279 
1280   /// \brief Returns the "presumed" location of a SourceLocation specifies.
1281   ///
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.
1285   ///
1286   /// Note that a presumed location is always given as the expansion point of
1287   /// an expansion location, not at the spelling location.
1288   ///
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;
1295 
1296   /// \brief Returns whether the PresumedLoc for a given SourceLocation is
1297   /// in the main file.
1298   ///
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
1302   /// account.
1303   bool isInMainFile(SourceLocation Loc) const;
1304 
1305   /// \brief Returns true if the spelling locations for both SourceLocations
1306   /// are part of the same file buffer.
1307   ///
1308   /// This check ignores line marker directives.
isWrittenInSameFile(SourceLocation Loc1,SourceLocation Loc2)1309   bool isWrittenInSameFile(SourceLocation Loc1, SourceLocation Loc2) const {
1310     return getFileID(Loc1) == getFileID(Loc2);
1311   }
1312 
1313   /// \brief Returns true if the spelling location for the given location
1314   /// is in the main file buffer.
1315   ///
1316   /// This check ignores line marker directives.
isWrittenInMainFile(SourceLocation Loc)1317   bool isWrittenInMainFile(SourceLocation Loc) const {
1318     return getFileID(Loc) == getMainFileID();
1319   }
1320 
1321   /// \brief Returns if a SourceLocation is in a system header.
isInSystemHeader(SourceLocation Loc)1322   bool isInSystemHeader(SourceLocation Loc) const {
1323     return getFileCharacteristic(Loc) != SrcMgr::C_User;
1324   }
1325 
1326   /// \brief Returns if a SourceLocation is in an "extern C" system header.
isInExternCSystemHeader(SourceLocation Loc)1327   bool isInExternCSystemHeader(SourceLocation Loc) const {
1328     return getFileCharacteristic(Loc) == SrcMgr::C_ExternCSystem;
1329   }
1330 
1331   /// \brief Returns whether \p Loc is expanded from a macro in a system header.
isInSystemMacro(SourceLocation loc)1332   bool isInSystemMacro(SourceLocation loc) {
1333     return loc.isMacroID() && isInSystemHeader(getSpellingLoc(loc));
1334   }
1335 
1336   /// \brief The size of the SLocEntry that \p FID represents.
1337   unsigned getFileIDSize(FileID FID) const;
1338 
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)) {
1346       if (RelativeOffset)
1347         *RelativeOffset = Offs - getSLocEntry(FID).getOffset();
1348       return true;
1349     }
1350 
1351     return false;
1352   }
1353 
1354   //===--------------------------------------------------------------------===//
1355   // Line Table Manipulation Routines
1356   //===--------------------------------------------------------------------===//
1357 
1358   /// \brief Return the uniqued ID for the specified filename.
1359   ///
1360   unsigned getLineTableFilenameID(StringRef Str);
1361 
1362   /// \brief Add a line note to the line table for the FileID and offset
1363   /// specified by Loc.
1364   ///
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);
1370 
1371   /// \brief Determine if the source manager has a line table.
hasLineTable()1372   bool hasLineTable() const { return LineTable != nullptr; }
1373 
1374   /// \brief Retrieve the stored line table.
1375   LineTableInfo &getLineTable();
1376 
1377   //===--------------------------------------------------------------------===//
1378   // Queries for performance analysis.
1379   //===--------------------------------------------------------------------===//
1380 
1381   /// \brief Return the total amount of physical memory allocated by the
1382   /// ContentCache allocator.
getContentCacheSize()1383   size_t getContentCacheSize() const {
1384     return ContentCacheAlloc.getTotalMemory();
1385   }
1386 
1387   struct MemoryBufferSizes {
1388     const size_t malloc_bytes;
1389     const size_t mmap_bytes;
1390 
MemoryBufferSizesMemoryBufferSizes1391     MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
1392       : malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
1393   };
1394 
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;
1398 
1399   /// \brief Return the amount of memory used for various side tables and
1400   /// data structures in the SourceManager.
1401   size_t getDataStructureSizes() const;
1402 
1403   //===--------------------------------------------------------------------===//
1404   // Other miscellaneous methods.
1405   //===--------------------------------------------------------------------===//
1406 
1407   /// \brief Get the source location for the given file:line:col triplet.
1408   ///
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;
1413 
1414   /// \brief Get the FileID for the given file.
1415   ///
1416   /// If the source file is included multiple times, the FileID will be the
1417   /// first inclusion.
1418   FileID translateFile(const FileEntry *SourceFile) const;
1419 
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;
1424 
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.
1429   /// e.g.
1430   ///   MY_MACRO(foo);
1431   ///             ^
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;
1435 
1436   /// \brief Determines the order of 2 source locations in the translation unit.
1437   ///
1438   /// \returns true if LHS source location comes before RHS, false otherwise.
1439   bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const;
1440 
1441   /// \brief Determines the order of 2 source locations in the "source location
1442   /// address space".
isBeforeInSLocAddrSpace(SourceLocation LHS,SourceLocation RHS)1443   bool isBeforeInSLocAddrSpace(SourceLocation LHS, SourceLocation RHS) const {
1444     return isBeforeInSLocAddrSpace(LHS, RHS.getOffset());
1445   }
1446 
1447   /// \brief Determines the order of a source location and a source location
1448   /// offset in the "source location address space".
1449   ///
1450   /// Note that we always consider source locations loaded from
isBeforeInSLocAddrSpace(SourceLocation LHS,unsigned RHS)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;
1457 
1458     return LHSLoaded;
1459   }
1460 
1461   // Iterators over FileInfos.
1462   typedef llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>
1463       ::const_iterator fileinfo_iterator;
fileinfo_begin()1464   fileinfo_iterator fileinfo_begin() const { return FileInfos.begin(); }
fileinfo_end()1465   fileinfo_iterator fileinfo_end() const { return FileInfos.end(); }
hasFileInfo(const FileEntry * File)1466   bool hasFileInfo(const FileEntry *File) const {
1467     return FileInfos.find(File) != FileInfos.end();
1468   }
1469 
1470   /// \brief Print statistics to stderr.
1471   ///
1472   void PrintStats() const;
1473 
1474   /// \brief Get the number of local SLocEntries we have.
local_sloc_entry_size()1475   unsigned local_sloc_entry_size() const { return LocalSLocEntryTable.size(); }
1476 
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];
1482   }
1483 
1484   /// \brief Get the number of loaded SLocEntries we have.
loaded_sloc_entry_size()1485   unsigned loaded_sloc_entry_size() const { return LoadedSLocEntryTable.size();}
1486 
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);
1494   }
1495 
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];
1501     }
1502     return getSLocEntryByID(FID.ID, Invalid);
1503   }
1504 
getNextLocalOffset()1505   unsigned getNextLocalOffset() const { return NextLocalOffset; }
1506 
setExternalSLocEntrySource(ExternalSLocEntrySource * Source)1507   void setExternalSLocEntrySource(ExternalSLocEntrySource *Source) {
1508     assert(LoadedSLocEntryTable.empty() &&
1509            "Invalidating existing loaded entries");
1510     ExternalSLocEntries = Source;
1511   }
1512 
1513   /// \brief Allocate a number of loaded SLocEntries, which will be actually
1514   /// loaded on demand from the external source.
1515   ///
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);
1521 
1522   /// \brief Returns true if \p Loc came from a PCH/Module.
isLoadedSourceLocation(SourceLocation Loc)1523   bool isLoadedSourceLocation(SourceLocation Loc) const {
1524     return Loc.getOffset() >= CurrentLoadedOffset;
1525   }
1526 
1527   /// \brief Returns true if \p Loc did not come from a PCH/Module.
isLocalSourceLocation(SourceLocation Loc)1528   bool isLocalSourceLocation(SourceLocation Loc) const {
1529     return Loc.getOffset() < NextLocalOffset;
1530   }
1531 
1532   /// \brief Returns true if \p FID came from a PCH/Module.
isLoadedFileID(FileID FID)1533   bool isLoadedFileID(FileID FID) const {
1534     assert(FID.ID != -1 && "Using FileID sentinel value");
1535     return FID.ID < 0;
1536   }
1537 
1538   /// \brief Returns true if \p FID did not come from a PCH/Module.
isLocalFileID(FileID FID)1539   bool isLocalFileID(FileID FID) const {
1540     return !isLoadedFileID(FID);
1541   }
1542 
1543   /// Gets the location of the immediate macro caller, one level up the stack
1544   /// toward the initial macro typed into the source.
getImmediateMacroCallerLoc(SourceLocation Loc)1545   SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const {
1546     if (!Loc.isMacroID()) return Loc;
1547 
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);
1553 
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;
1557   }
1558 
1559 private:
1560   llvm::MemoryBuffer *getFakeBufferForRecovery() const;
1561   const SrcMgr::ContentCache *getFakeContentCacheForRecovery() const;
1562 
1563   const SrcMgr::SLocEntry &loadSLocEntry(unsigned Index, bool *Invalid) const;
1564 
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");
1569     if (ID < 0)
1570       return getLoadedSLocEntryByID(ID, Invalid);
1571     return getLocalSLocEntry(static_cast<unsigned>(ID), Invalid);
1572   }
1573 
1574   const SrcMgr::SLocEntry &
1575   getLoadedSLocEntryByID(int ID, bool *Invalid = nullptr) const {
1576     return getLoadedSLocEntry(static_cast<unsigned>(-ID - 2), Invalid);
1577   }
1578 
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,
1582                                         unsigned TokLength,
1583                                         int LoadedID = 0,
1584                                         unsigned LoadedOffset = 0);
1585 
1586   /// \brief Return true if the specified FileID contains the
1587   /// specified SourceLocation offset.  This is a very hot method.
isOffsetInFileID(FileID FID,unsigned SLocOffset)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;
1592 
1593     // If this is the very last entry then it does.
1594     if (FID.ID == -2)
1595       return true;
1596 
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;
1600 
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();
1604   }
1605 
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;
1609 
1610   /// \brief Returns the next in-order FileID or an invalid FileID if there is
1611   /// no next one.
1612   FileID getNextFileID(FileID FID) const;
1613 
1614   /// \brief Create a new fileID for the specified ContentCache and
1615   /// include position.
1616   ///
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);
1623 
1624   const SrcMgr::ContentCache *
1625     getOrCreateContentCache(const FileEntry *SourceFile,
1626                             bool isSystemFile = false);
1627 
1628   /// \brief Create a new ContentCache for the specified  memory buffer.
1629   const SrcMgr::ContentCache *
1630   createMemBufferContentCache(std::unique_ptr<llvm::MemoryBuffer> Buf);
1631 
1632   FileID getFileIDSlow(unsigned SLocOffset) const;
1633   FileID getFileIDLocal(unsigned SLocOffset) const;
1634   FileID getFileIDLoaded(unsigned SLocOffset) const;
1635 
1636   SourceLocation getExpansionLocSlowCase(SourceLocation Loc) const;
1637   SourceLocation getSpellingLocSlowCase(SourceLocation Loc) const;
1638   SourceLocation getFileLocSlowCase(SourceLocation Loc) const;
1639 
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,
1647                                          FileID FID,
1648                                          SourceLocation SpellLoc,
1649                                          SourceLocation ExpansionLoc,
1650                                          unsigned ExpansionLength) const;
1651   friend class ASTReader;
1652   friend class ASTWriter;
1653 };
1654 
1655 /// \brief Comparison function object.
1656 template<typename T>
1657 class BeforeThanCompare;
1658 
1659 /// \brief Compare two source locations.
1660 template<>
1661 class BeforeThanCompare<SourceLocation> {
1662   SourceManager &SM;
1663 
1664 public:
BeforeThanCompare(SourceManager & SM)1665   explicit BeforeThanCompare(SourceManager &SM) : SM(SM) { }
1666 
operator()1667   bool operator()(SourceLocation LHS, SourceLocation RHS) const {
1668     return SM.isBeforeInTranslationUnit(LHS, RHS);
1669   }
1670 };
1671 
1672 /// \brief Compare two non-overlapping source ranges.
1673 template<>
1674 class BeforeThanCompare<SourceRange> {
1675   SourceManager &SM;
1676 
1677 public:
BeforeThanCompare(SourceManager & SM)1678   explicit BeforeThanCompare(SourceManager &SM) : SM(SM) { }
1679 
operator()1680   bool operator()(SourceRange LHS, SourceRange RHS) const {
1681     return SM.isBeforeInTranslationUnit(LHS.getBegin(), RHS.getBegin());
1682   }
1683 };
1684 
1685 }  // end namespace clang
1686 
1687 
1688 #endif
1689