]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Basic/SourceManager.h
Merge ACPICA 20141107 and 20150204.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Basic / SourceManager.h
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_SOURCEMANAGER_H
36 #define LLVM_CLANG_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)
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     
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.
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
208     void setBuffer(llvm::MemoryBuffer *B) {
209       assert(!Buffer.getPointer() && "MemoryBuffer already set.");
210       Buffer.setPointer(B);
211       Buffer.setInt(false);
212     }
213
214     /// \brief Get the underlying buffer, returning NULL if the buffer is not
215     /// yet available.
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.
223     bool isBufferInvalid() const {
224       return Buffer.getInt() & InvalidFlag;
225     }
226
227     /// \brief Determine whether the buffer should be freed.
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.
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
285     SourceLocation getIncludeLoc() const {
286       return SourceLocation::getFromRawEncoding(IncludeLoc);
287     }
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.
293     CharacteristicKind getFileCharacteristic() const {
294       return (CharacteristicKind)(Data & 3);
295     }
296
297     /// \brief Return true if this FileID has \#line directives in it.
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.
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:
325     SourceLocation getSpellingLoc() const {
326       return SourceLocation::getFromRawEncoding(SpellingLoc);
327     }
328     SourceLocation getExpansionLocStart() const {
329       return SourceLocation::getFromRawEncoding(ExpansionLocStart);
330     }
331     SourceLocation getExpansionLocEnd() const {
332       SourceLocation EndLoc =
333         SourceLocation::getFromRawEncoding(ExpansionLocEnd);
334       return EndLoc.isInvalid() ? getExpansionLocStart() : EndLoc;
335     }
336
337     std::pair<SourceLocation,SourceLocation> getExpansionLocRange() const {
338       return std::make_pair(getExpansionLocStart(), getExpansionLocEnd());
339     }
340
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
347     bool isMacroBodyExpansion() const {
348       return getExpansionLocStart().isValid() &&
349         SourceLocation::getFromRawEncoding(ExpansionLocEnd).isValid();
350     }
351
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.
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'.
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:
411     unsigned getOffset() const { return Offset >> 1; }
412
413     bool isExpansion() const { return Offset & 1; }
414     bool isFile() const { return !isExpansion(); }
415
416     const FileInfo &getFile() const {
417       assert(isFile() && "Not a file SLocEntry!");
418       return File;
419     }
420
421     const ExpansionInfo &getExpansion() const {
422       assert(isExpansion() && "Not a macro expansion SLocEntry!");
423       return Expansion;
424     }
425
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
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.
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.
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.
515   void setQueryFIDs(FileID LHS, FileID RHS, bool isLFIDBeforeRFID) {
516     assert(LHS != RHS);
517     LQueryFID = LHS;
518     RQueryFID = RHS;
519     IsLQFIDBeforeRQFID = isLFIDBeforeRFID;
520   }
521
522   void clear() {
523     LQueryFID = RQueryFID = FileID();
524     IsLQFIDBeforeRQFID = false;
525   }
526
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
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 llvm::MemoryBuffer *FakeBufferForRecovery;
689
690   mutable 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
717   DiagnosticsEngine &getDiagnostics() const { return Diag; }
718
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.
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).
730   bool userFilesAreVolatile() const { return UserFilesAreVolatile; }
731
732   /// \brief Retrieve the module build stack.
733   ModuleBuildStack getModuleBuildStack() const {
734     return StoredModuleBuildStack;
735   }
736
737   /// \brief Set the module build 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.
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.
753   FileID getMainFileID() const { return MainFileID; }
754
755   /// \brief Set the file ID for the main source file.
756   void setMainFileID(FileID FID) {
757     assert(MainFileID.isInvalid() && "MainFileID already set!");
758     MainFileID = FID;
759   }
760
761   /// \brief Set the file ID for the precompiled preamble.
762   void setPreambleFileID(FileID Preamble) {
763     assert(PreambleFileID.isInvalid() && "PreambleFileID already set!");
764     PreambleFileID = Preamble;
765   }
766
767   /// \brief Get the file ID for the precompiled preamble if there is one.
768   FileID getPreambleFileID() const { return PreambleFileID; }
769
770   //===--------------------------------------------------------------------===//
771   // Methods to create new FileID's and macro expansions.
772   //===--------------------------------------------------------------------===//
773
774   /// \brief Create a new FileID that represents the specified file
775   /// being \#included from the specified IncludePosition.
776   ///
777   /// This translates NULL into standard input.
778   FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos,
779                       SrcMgr::CharacteristicKind FileCharacter,
780                       int LoadedID = 0, unsigned LoadedOffset = 0) {
781     const SrcMgr::ContentCache *
782       IR = getOrCreateContentCache(SourceFile,
783                               /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
784     assert(IR && "getOrCreateContentCache() cannot return NULL");
785     return createFileID(IR, IncludePos, FileCharacter, LoadedID, LoadedOffset);
786   }
787
788   /// \brief Create a new FileID that represents the specified memory buffer.
789   ///
790   /// This does no caching of the buffer and takes ownership of the
791   /// MemoryBuffer, so only pass a MemoryBuffer to this once.
792   FileID createFileID(llvm::MemoryBuffer *Buffer,
793                       SrcMgr::CharacteristicKind FileCharacter = SrcMgr::C_User,
794                       int LoadedID = 0, unsigned LoadedOffset = 0,
795                       SourceLocation IncludeLoc = SourceLocation()) {
796     return createFileID(createMemBufferContentCache(Buffer), IncludeLoc,
797                         FileCharacter, LoadedID, LoadedOffset);
798   }
799
800   /// \brief Return a new SourceLocation that encodes the
801   /// fact that a token from SpellingLoc should actually be referenced from
802   /// ExpansionLoc, and that it represents the expansion of a macro argument
803   /// into the function-like macro body.
804   SourceLocation createMacroArgExpansionLoc(SourceLocation Loc,
805                                             SourceLocation ExpansionLoc,
806                                             unsigned TokLength);
807
808   /// \brief Return a new SourceLocation that encodes the fact
809   /// that a token from SpellingLoc should actually be referenced from
810   /// ExpansionLoc.
811   SourceLocation createExpansionLoc(SourceLocation Loc,
812                                     SourceLocation ExpansionLocStart,
813                                     SourceLocation ExpansionLocEnd,
814                                     unsigned TokLength,
815                                     int LoadedID = 0,
816                                     unsigned LoadedOffset = 0);
817
818   /// \brief Retrieve the memory buffer associated with the given file.
819   ///
820   /// \param Invalid If non-NULL, will be set \c true if an error
821   /// occurs while retrieving the memory buffer.
822   llvm::MemoryBuffer *getMemoryBufferForFile(const FileEntry *File,
823                                              bool *Invalid = nullptr);
824
825   /// \brief Override the contents of the given source file by providing an
826   /// already-allocated buffer.
827   ///
828   /// \param SourceFile the source file whose contents will be overridden.
829   ///
830   /// \param Buffer the memory buffer whose contents will be used as the
831   /// data in the given source file.
832   ///
833   /// \param DoNotFree If true, then the buffer will not be freed when the
834   /// source manager is destroyed.
835   void overrideFileContents(const FileEntry *SourceFile,
836                             llvm::MemoryBuffer *Buffer, bool DoNotFree = false);
837
838   /// \brief Override the given source file with another one.
839   ///
840   /// \param SourceFile the source file which will be overridden.
841   ///
842   /// \param NewFile the file whose contents will be used as the
843   /// data instead of the contents of the given source file.
844   void overrideFileContents(const FileEntry *SourceFile,
845                             const FileEntry *NewFile);
846
847   /// \brief Returns true if the file contents have been overridden.
848   bool isFileOverridden(const FileEntry *File) {
849     if (OverriddenFilesInfo) {
850       if (OverriddenFilesInfo->OverriddenFilesWithBuffer.count(File))
851         return true;
852       if (OverriddenFilesInfo->OverriddenFiles.find(File) !=
853           OverriddenFilesInfo->OverriddenFiles.end())
854         return true;
855     }
856     return false;
857   }
858
859   /// \brief Disable overridding the contents of a file, previously enabled
860   /// with #overrideFileContents.
861   ///
862   /// This should be called before parsing has begun.
863   void disableFileContentsOverride(const FileEntry *File);
864
865   //===--------------------------------------------------------------------===//
866   // FileID manipulation methods.
867   //===--------------------------------------------------------------------===//
868
869   /// \brief Return the buffer for the specified FileID.
870   ///
871   /// If there is an error opening this buffer the first time, this
872   /// manufactures a temporary buffer and returns a non-empty error string.
873   llvm::MemoryBuffer *getBuffer(FileID FID, SourceLocation Loc,
874                                 bool *Invalid = nullptr) const {
875     bool MyInvalid = false;
876     const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
877     if (MyInvalid || !Entry.isFile()) {
878       if (Invalid)
879         *Invalid = true;
880
881       return getFakeBufferForRecovery();
882     }
883
884     return Entry.getFile().getContentCache()->getBuffer(Diag, *this, Loc,
885                                                         Invalid);
886   }
887
888   llvm::MemoryBuffer *getBuffer(FileID FID, 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,
899                                                         SourceLocation(),
900                                                         Invalid);
901   }
902
903   /// \brief Returns the FileEntry record for the provided FileID.
904   const FileEntry *getFileEntryForID(FileID FID) const {
905     bool MyInvalid = false;
906     const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
907     if (MyInvalid || !Entry.isFile())
908       return nullptr;
909
910     const SrcMgr::ContentCache *Content = Entry.getFile().getContentCache();
911     if (!Content)
912       return nullptr;
913     return Content->OrigEntry;
914   }
915
916   /// \brief Returns the FileEntry record for the provided SLocEntry.
917   const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const
918   {
919     const SrcMgr::ContentCache *Content = sloc.getFile().getContentCache();
920     if (!Content)
921       return nullptr;
922     return Content->OrigEntry;
923   }
924
925   /// \brief Return a StringRef to the source buffer data for the
926   /// specified FileID.
927   ///
928   /// \param FID The file ID whose contents will be returned.
929   /// \param Invalid If non-NULL, will be set true if an error occurred.
930   StringRef getBufferData(FileID FID, bool *Invalid = nullptr) const;
931
932   /// \brief Get the number of FileIDs (files and macros) that were created
933   /// during preprocessing of \p FID, including it.
934   unsigned getNumCreatedFIDsForFileID(FileID FID) const {
935     bool Invalid = false;
936     const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
937     if (Invalid || !Entry.isFile())
938       return 0;
939
940     return Entry.getFile().NumCreatedFIDs;
941   }
942
943   /// \brief Set the number of FileIDs (files and macros) that were created
944   /// during preprocessing of \p FID, including it.
945   void setNumCreatedFIDsForFileID(FileID FID, unsigned NumFIDs) const {
946     bool Invalid = false;
947     const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
948     if (Invalid || !Entry.isFile())
949       return;
950
951     assert(Entry.getFile().NumCreatedFIDs == 0 && "Already set!");
952     const_cast<SrcMgr::FileInfo &>(Entry.getFile()).NumCreatedFIDs = NumFIDs;
953   }
954
955   //===--------------------------------------------------------------------===//
956   // SourceLocation manipulation methods.
957   //===--------------------------------------------------------------------===//
958
959   /// \brief Return the FileID for a SourceLocation.
960   ///
961   /// This is a very hot method that is used for all SourceManager queries
962   /// that start with a SourceLocation object.  It is responsible for finding
963   /// the entry in SLocEntryTable which contains the specified location.
964   ///
965   FileID getFileID(SourceLocation SpellingLoc) const {
966     unsigned SLocOffset = SpellingLoc.getOffset();
967
968     // If our one-entry cache covers this offset, just return it.
969     if (isOffsetInFileID(LastFileIDLookup, SLocOffset))
970       return LastFileIDLookup;
971
972     return getFileIDSlow(SLocOffset);
973   }
974
975   /// \brief Return the filename of the file containing a SourceLocation.
976   StringRef getFilename(SourceLocation SpellingLoc) const {
977     if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
978       return F->getName();
979     return StringRef();
980   }
981
982   /// \brief Return the source location corresponding to the first byte of
983   /// the specified file.
984   SourceLocation getLocForStartOfFile(FileID FID) const {
985     bool Invalid = false;
986     const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
987     if (Invalid || !Entry.isFile())
988       return SourceLocation();
989
990     unsigned FileOffset = Entry.getOffset();
991     return SourceLocation::getFileLoc(FileOffset);
992   }
993   
994   /// \brief Return the source location corresponding to the last byte of the
995   /// specified file.
996   SourceLocation getLocForEndOfFile(FileID FID) const {
997     bool Invalid = false;
998     const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
999     if (Invalid || !Entry.isFile())
1000       return SourceLocation();
1001     
1002     unsigned FileOffset = Entry.getOffset();
1003     return SourceLocation::getFileLoc(FileOffset + getFileIDSize(FID));
1004   }
1005
1006   /// \brief Returns the include location if \p FID is a \#include'd file
1007   /// otherwise it returns an invalid location.
1008   SourceLocation getIncludeLoc(FileID FID) const {
1009     bool Invalid = false;
1010     const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1011     if (Invalid || !Entry.isFile())
1012       return SourceLocation();
1013
1014     return Entry.getFile().getIncludeLoc();
1015   }
1016
1017   // \brief Returns the import location if the given source location is
1018   // located within a module, or an invalid location if the source location
1019   // is within the current translation unit.
1020   std::pair<SourceLocation, StringRef>
1021   getModuleImportLoc(SourceLocation Loc) const {
1022     FileID FID = getFileID(Loc);
1023
1024     // Positive file IDs are in the current translation unit, and -1 is a
1025     // placeholder.
1026     if (FID.ID >= -1)
1027       return std::make_pair(SourceLocation(), "");
1028
1029     return ExternalSLocEntries->getModuleImportLoc(FID.ID);
1030   }
1031
1032   /// \brief Given a SourceLocation object \p Loc, return the expansion
1033   /// location referenced by the ID.
1034   SourceLocation getExpansionLoc(SourceLocation Loc) const {
1035     // Handle the non-mapped case inline, defer to out of line code to handle
1036     // expansions.
1037     if (Loc.isFileID()) return Loc;
1038     return getExpansionLocSlowCase(Loc);
1039   }
1040
1041   /// \brief Given \p Loc, if it is a macro location return the expansion
1042   /// location or the spelling location, depending on if it comes from a
1043   /// macro argument or not.
1044   SourceLocation getFileLoc(SourceLocation Loc) const {
1045     if (Loc.isFileID()) return Loc;
1046     return getFileLocSlowCase(Loc);
1047   }
1048
1049   /// \brief Return the start/end of the expansion information for an
1050   /// expansion location.
1051   ///
1052   /// \pre \p Loc is required to be an expansion location.
1053   std::pair<SourceLocation,SourceLocation>
1054   getImmediateExpansionRange(SourceLocation Loc) const;
1055
1056   /// \brief Given a SourceLocation object, return the range of
1057   /// tokens covered by the expansion the ultimate file.
1058   std::pair<SourceLocation,SourceLocation>
1059   getExpansionRange(SourceLocation Loc) const;
1060
1061
1062   /// \brief Given a SourceLocation object, return the spelling
1063   /// location referenced by the ID.
1064   ///
1065   /// This is the place where the characters that make up the lexed token
1066   /// can be found.
1067   SourceLocation getSpellingLoc(SourceLocation Loc) const {
1068     // Handle the non-mapped case inline, defer to out of line code to handle
1069     // expansions.
1070     if (Loc.isFileID()) return Loc;
1071     return getSpellingLocSlowCase(Loc);
1072   }
1073
1074   /// \brief Given a SourceLocation object, return the spelling location
1075   /// referenced by the ID.
1076   ///
1077   /// This is the first level down towards the place where the characters
1078   /// that make up the lexed token can be found.  This should not generally
1079   /// be used by clients.
1080   SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const;
1081
1082   /// \brief Decompose the specified location into a raw FileID + Offset pair.
1083   ///
1084   /// The first element is the FileID, the second is the offset from the
1085   /// start of the buffer of the location.
1086   std::pair<FileID, unsigned> getDecomposedLoc(SourceLocation Loc) const {
1087     FileID FID = getFileID(Loc);
1088     bool Invalid = false;
1089     const SrcMgr::SLocEntry &E = getSLocEntry(FID, &Invalid);
1090     if (Invalid)
1091       return std::make_pair(FileID(), 0);
1092     return std::make_pair(FID, Loc.getOffset()-E.getOffset());
1093   }
1094
1095   /// \brief Decompose the specified location into a raw FileID + Offset pair.
1096   ///
1097   /// If the location is an expansion record, walk through it until we find
1098   /// the final location expanded.
1099   std::pair<FileID, unsigned>
1100   getDecomposedExpansionLoc(SourceLocation Loc) const {
1101     FileID FID = getFileID(Loc);
1102     bool Invalid = false;
1103     const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
1104     if (Invalid)
1105       return std::make_pair(FileID(), 0);
1106
1107     unsigned Offset = Loc.getOffset()-E->getOffset();
1108     if (Loc.isFileID())
1109       return std::make_pair(FID, Offset);
1110
1111     return getDecomposedExpansionLocSlowCase(E);
1112   }
1113
1114   /// \brief Decompose the specified location into a raw FileID + Offset pair.
1115   ///
1116   /// If the location is an expansion record, walk through it until we find
1117   /// its spelling record.
1118   std::pair<FileID, unsigned>
1119   getDecomposedSpellingLoc(SourceLocation Loc) const {
1120     FileID FID = getFileID(Loc);
1121     bool Invalid = false;
1122     const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
1123     if (Invalid)
1124       return std::make_pair(FileID(), 0);
1125
1126     unsigned Offset = Loc.getOffset()-E->getOffset();
1127     if (Loc.isFileID())
1128       return std::make_pair(FID, Offset);
1129     return getDecomposedSpellingLocSlowCase(E, Offset);
1130   }
1131
1132   /// \brief Returns the "included/expanded in" decomposed location of the given
1133   /// FileID.
1134   std::pair<FileID, unsigned> getDecomposedIncludedLoc(FileID FID) const;
1135
1136   /// \brief Returns the offset from the start of the file that the
1137   /// specified SourceLocation represents.
1138   ///
1139   /// This is not very meaningful for a macro ID.
1140   unsigned getFileOffset(SourceLocation SpellingLoc) const {
1141     return getDecomposedLoc(SpellingLoc).second;
1142   }
1143
1144   /// \brief Tests whether the given source location represents a macro
1145   /// argument's expansion into the function-like macro definition.
1146   ///
1147   /// Such source locations only appear inside of the expansion
1148   /// locations representing where a particular function-like macro was
1149   /// expanded.
1150   bool isMacroArgExpansion(SourceLocation Loc) const;
1151
1152   /// \brief Tests whether the given source location represents the expansion of
1153   /// a macro body.
1154   ///
1155   /// This is equivalent to testing whether the location is part of a macro
1156   /// expansion but not the expansion of an argument to a function-like macro.
1157   bool isMacroBodyExpansion(SourceLocation Loc) const;
1158
1159   /// \brief Returns true if the given MacroID location points at the beginning
1160   /// of the immediate macro expansion.
1161   ///
1162   /// \param MacroBegin If non-null and function returns true, it is set to the
1163   /// begin location of the immediate macro expansion.
1164   bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1165                                     SourceLocation *MacroBegin = nullptr) const;
1166
1167   /// \brief Returns true if the given MacroID location points at the character
1168   /// end of the immediate macro expansion.
1169   ///
1170   /// \param MacroEnd If non-null and function returns true, it is set to the
1171   /// character end location of the immediate macro expansion.
1172   bool
1173   isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1174                                    SourceLocation *MacroEnd = nullptr) const;
1175
1176   /// \brief Returns true if \p Loc is inside the [\p Start, +\p Length)
1177   /// chunk of the source location address space.
1178   ///
1179   /// If it's true and \p RelativeOffset is non-null, it will be set to the
1180   /// relative offset of \p Loc inside the chunk.
1181   bool isInSLocAddrSpace(SourceLocation Loc,
1182                          SourceLocation Start, unsigned Length,
1183                          unsigned *RelativeOffset = nullptr) const {
1184     assert(((Start.getOffset() < NextLocalOffset &&
1185                Start.getOffset()+Length <= NextLocalOffset) ||
1186             (Start.getOffset() >= CurrentLoadedOffset &&
1187                 Start.getOffset()+Length < MaxLoadedOffset)) &&
1188            "Chunk is not valid SLoc address space");
1189     unsigned LocOffs = Loc.getOffset();
1190     unsigned BeginOffs = Start.getOffset();
1191     unsigned EndOffs = BeginOffs + Length;
1192     if (LocOffs >= BeginOffs && LocOffs < EndOffs) {
1193       if (RelativeOffset)
1194         *RelativeOffset = LocOffs - BeginOffs;
1195       return true;
1196     }
1197
1198     return false;
1199   }
1200
1201   /// \brief Return true if both \p LHS and \p RHS are in the local source
1202   /// location address space or the loaded one.
1203   ///
1204   /// If it's true and \p RelativeOffset is non-null, it will be set to the
1205   /// offset of \p RHS relative to \p LHS.
1206   bool isInSameSLocAddrSpace(SourceLocation LHS, SourceLocation RHS,
1207                              int *RelativeOffset) const {
1208     unsigned LHSOffs = LHS.getOffset(), RHSOffs = RHS.getOffset();
1209     bool LHSLoaded = LHSOffs >= CurrentLoadedOffset;
1210     bool RHSLoaded = RHSOffs >= CurrentLoadedOffset;
1211
1212     if (LHSLoaded == RHSLoaded) {
1213       if (RelativeOffset)
1214         *RelativeOffset = RHSOffs - LHSOffs;
1215       return true;
1216     }
1217
1218     return false;
1219   }
1220
1221   //===--------------------------------------------------------------------===//
1222   // Queries about the code at a SourceLocation.
1223   //===--------------------------------------------------------------------===//
1224
1225   /// \brief Return a pointer to the start of the specified location
1226   /// in the appropriate spelling MemoryBuffer.
1227   ///
1228   /// \param Invalid If non-NULL, will be set \c true if an error occurs.
1229   const char *getCharacterData(SourceLocation SL,
1230                                bool *Invalid = nullptr) const;
1231
1232   /// \brief Return the column # for the specified file position.
1233   ///
1234   /// This is significantly cheaper to compute than the line number.  This
1235   /// returns zero if the column number isn't known.  This may only be called
1236   /// on a file sloc, so you must choose a spelling or expansion location
1237   /// before calling this method.
1238   unsigned getColumnNumber(FileID FID, unsigned FilePos,
1239                            bool *Invalid = nullptr) const;
1240   unsigned getSpellingColumnNumber(SourceLocation Loc,
1241                                    bool *Invalid = nullptr) const;
1242   unsigned getExpansionColumnNumber(SourceLocation Loc,
1243                                     bool *Invalid = nullptr) const;
1244   unsigned getPresumedColumnNumber(SourceLocation Loc,
1245                                    bool *Invalid = nullptr) const;
1246
1247   /// \brief Given a SourceLocation, return the spelling line number
1248   /// for the position indicated.
1249   ///
1250   /// This requires building and caching a table of line offsets for the
1251   /// MemoryBuffer, so this is not cheap: use only when about to emit a
1252   /// diagnostic.
1253   unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid = nullptr) const;
1254   unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
1255   unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
1256   unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
1257
1258   /// \brief Return the filename or buffer identifier of the buffer the
1259   /// location is in.
1260   ///
1261   /// Note that this name does not respect \#line directives.  Use
1262   /// getPresumedLoc for normal clients.
1263   const char *getBufferName(SourceLocation Loc, bool *Invalid = nullptr) const;
1264
1265   /// \brief Return the file characteristic of the specified source
1266   /// location, indicating whether this is a normal file, a system
1267   /// header, or an "implicit extern C" system header.
1268   ///
1269   /// This state can be modified with flags on GNU linemarker directives like:
1270   /// \code
1271   ///   # 4 "foo.h" 3
1272   /// \endcode
1273   /// which changes all source locations in the current file after that to be
1274   /// considered to be from a system header.
1275   SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const;
1276
1277   /// \brief Returns the "presumed" location of a SourceLocation specifies.
1278   ///
1279   /// A "presumed location" can be modified by \#line or GNU line marker
1280   /// directives.  This provides a view on the data that a user should see
1281   /// in diagnostics, for example.
1282   ///
1283   /// Note that a presumed location is always given as the expansion point of
1284   /// an expansion location, not at the spelling location.
1285   ///
1286   /// \returns The presumed location of the specified SourceLocation. If the
1287   /// presumed location cannot be calculated (e.g., because \p Loc is invalid
1288   /// or the file containing \p Loc has changed on disk), returns an invalid
1289   /// presumed location.
1290   PresumedLoc getPresumedLoc(SourceLocation Loc,
1291                              bool UseLineDirectives = true) const;
1292
1293   /// \brief Returns whether the PresumedLoc for a given SourceLocation is 
1294   /// in the main file.
1295   ///
1296   /// This computes the "presumed" location for a SourceLocation, then checks
1297   /// whether it came from a file other than the main file. This is different
1298   /// from isWrittenInMainFile() because it takes line marker directives into
1299   /// account.
1300   bool isInMainFile(SourceLocation Loc) const;
1301
1302   /// \brief Returns true if the spelling locations for both SourceLocations
1303   /// are part of the same file buffer.
1304   ///
1305   /// This check ignores line marker directives.
1306   bool isWrittenInSameFile(SourceLocation Loc1, SourceLocation Loc2) const {
1307     return getFileID(Loc1) == getFileID(Loc2);
1308   }
1309
1310   /// \brief Returns true if the spelling location for the given location
1311   /// is in the main file buffer.
1312   ///
1313   /// This check ignores line marker directives.
1314   bool isWrittenInMainFile(SourceLocation Loc) const {
1315     return getFileID(Loc) == getMainFileID();
1316   }
1317
1318   /// \brief Returns if a SourceLocation is in a system header.
1319   bool isInSystemHeader(SourceLocation Loc) const {
1320     return getFileCharacteristic(Loc) != SrcMgr::C_User;
1321   }
1322
1323   /// \brief Returns if a SourceLocation is in an "extern C" system header.
1324   bool isInExternCSystemHeader(SourceLocation Loc) const {
1325     return getFileCharacteristic(Loc) == SrcMgr::C_ExternCSystem;
1326   }
1327
1328   /// \brief Returns whether \p Loc is expanded from a macro in a system header.
1329   bool isInSystemMacro(SourceLocation loc) {
1330     return loc.isMacroID() && isInSystemHeader(getSpellingLoc(loc));
1331   }
1332
1333   /// \brief The size of the SLocEntry that \p FID represents.
1334   unsigned getFileIDSize(FileID FID) const;
1335
1336   /// \brief Given a specific FileID, returns true if \p Loc is inside that
1337   /// FileID chunk and sets relative offset (offset of \p Loc from beginning
1338   /// of FileID) to \p relativeOffset.
1339   bool isInFileID(SourceLocation Loc, FileID FID,
1340                   unsigned *RelativeOffset = nullptr) const {
1341     unsigned Offs = Loc.getOffset();
1342     if (isOffsetInFileID(FID, Offs)) {
1343       if (RelativeOffset)
1344         *RelativeOffset = Offs - getSLocEntry(FID).getOffset();
1345       return true;
1346     }
1347
1348     return false;
1349   }
1350
1351   //===--------------------------------------------------------------------===//
1352   // Line Table Manipulation Routines
1353   //===--------------------------------------------------------------------===//
1354
1355   /// \brief Return the uniqued ID for the specified filename.
1356   ///
1357   unsigned getLineTableFilenameID(StringRef Str);
1358
1359   /// \brief Add a line note to the line table for the FileID and offset
1360   /// specified by Loc.
1361   ///
1362   /// If FilenameID is -1, it is considered to be unspecified.
1363   void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID);
1364   void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID,
1365                    bool IsFileEntry, bool IsFileExit,
1366                    bool IsSystemHeader, bool IsExternCHeader);
1367
1368   /// \brief Determine if the source manager has a line table.
1369   bool hasLineTable() const { return LineTable != nullptr; }
1370
1371   /// \brief Retrieve the stored line table.
1372   LineTableInfo &getLineTable();
1373
1374   //===--------------------------------------------------------------------===//
1375   // Queries for performance analysis.
1376   //===--------------------------------------------------------------------===//
1377
1378   /// \brief Return the total amount of physical memory allocated by the
1379   /// ContentCache allocator.
1380   size_t getContentCacheSize() const {
1381     return ContentCacheAlloc.getTotalMemory();
1382   }
1383
1384   struct MemoryBufferSizes {
1385     const size_t malloc_bytes;
1386     const size_t mmap_bytes;
1387
1388     MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
1389       : malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
1390   };
1391
1392   /// \brief Return the amount of memory used by memory buffers, breaking down
1393   /// by heap-backed versus mmap'ed memory.
1394   MemoryBufferSizes getMemoryBufferSizes() const;
1395
1396   /// \brief Return the amount of memory used for various side tables and
1397   /// data structures in the SourceManager.
1398   size_t getDataStructureSizes() const;
1399
1400   //===--------------------------------------------------------------------===//
1401   // Other miscellaneous methods.
1402   //===--------------------------------------------------------------------===//
1403
1404   /// \brief Get the source location for the given file:line:col triplet.
1405   ///
1406   /// If the source file is included multiple times, the source location will
1407   /// be based upon the first inclusion.
1408   SourceLocation translateFileLineCol(const FileEntry *SourceFile,
1409                                       unsigned Line, unsigned Col) const;
1410
1411   /// \brief Get the FileID for the given file.
1412   ///
1413   /// If the source file is included multiple times, the FileID will be the
1414   /// first inclusion.
1415   FileID translateFile(const FileEntry *SourceFile) const;
1416
1417   /// \brief Get the source location in \p FID for the given line:col.
1418   /// Returns null location if \p FID is not a file SLocEntry.
1419   SourceLocation translateLineCol(FileID FID,
1420                                   unsigned Line, unsigned Col) const;
1421
1422   /// \brief If \p Loc points inside a function macro argument, the returned
1423   /// location will be the macro location in which the argument was expanded.
1424   /// If a macro argument is used multiple times, the expanded location will
1425   /// be at the first expansion of the argument.
1426   /// e.g.
1427   ///   MY_MACRO(foo);
1428   ///             ^
1429   /// Passing a file location pointing at 'foo', will yield a macro location
1430   /// where 'foo' was expanded into.
1431   SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const;
1432
1433   /// \brief Determines the order of 2 source locations in the translation unit.
1434   ///
1435   /// \returns true if LHS source location comes before RHS, false otherwise.
1436   bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const;
1437
1438   /// \brief Determines the order of 2 source locations in the "source location
1439   /// address space".
1440   bool isBeforeInSLocAddrSpace(SourceLocation LHS, SourceLocation RHS) const {
1441     return isBeforeInSLocAddrSpace(LHS, RHS.getOffset());
1442   }
1443
1444   /// \brief Determines the order of a source location and a source location
1445   /// offset in the "source location address space".
1446   ///
1447   /// Note that we always consider source locations loaded from
1448   bool isBeforeInSLocAddrSpace(SourceLocation LHS, unsigned RHS) const {
1449     unsigned LHSOffset = LHS.getOffset();
1450     bool LHSLoaded = LHSOffset >= CurrentLoadedOffset;
1451     bool RHSLoaded = RHS >= CurrentLoadedOffset;
1452     if (LHSLoaded == RHSLoaded)
1453       return LHSOffset < RHS;
1454
1455     return LHSLoaded;
1456   }
1457
1458   // Iterators over FileInfos.
1459   typedef llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>
1460       ::const_iterator fileinfo_iterator;
1461   fileinfo_iterator fileinfo_begin() const { return FileInfos.begin(); }
1462   fileinfo_iterator fileinfo_end() const { return FileInfos.end(); }
1463   bool hasFileInfo(const FileEntry *File) const {
1464     return FileInfos.find(File) != FileInfos.end();
1465   }
1466
1467   /// \brief Print statistics to stderr.
1468   ///
1469   void PrintStats() const;
1470
1471   /// \brief Get the number of local SLocEntries we have.
1472   unsigned local_sloc_entry_size() const { return LocalSLocEntryTable.size(); }
1473
1474   /// \brief Get a local SLocEntry. This is exposed for indexing.
1475   const SrcMgr::SLocEntry &getLocalSLocEntry(unsigned Index,
1476                                              bool *Invalid = nullptr) const {
1477     assert(Index < LocalSLocEntryTable.size() && "Invalid index");
1478     return LocalSLocEntryTable[Index];
1479   }
1480
1481   /// \brief Get the number of loaded SLocEntries we have.
1482   unsigned loaded_sloc_entry_size() const { return LoadedSLocEntryTable.size();}
1483
1484   /// \brief Get a loaded SLocEntry. This is exposed for indexing.
1485   const SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index,
1486                                               bool *Invalid = nullptr) const {
1487     assert(Index < LoadedSLocEntryTable.size() && "Invalid index");
1488     if (SLocEntryLoaded[Index])
1489       return LoadedSLocEntryTable[Index];
1490     return loadSLocEntry(Index, Invalid);
1491   }
1492
1493   const SrcMgr::SLocEntry &getSLocEntry(FileID FID,
1494                                         bool *Invalid = nullptr) const {
1495     if (FID.ID == 0 || FID.ID == -1) {
1496       if (Invalid) *Invalid = true;
1497       return LocalSLocEntryTable[0];
1498     }
1499     return getSLocEntryByID(FID.ID, Invalid);
1500   }
1501
1502   unsigned getNextLocalOffset() const { return NextLocalOffset; }
1503
1504   void setExternalSLocEntrySource(ExternalSLocEntrySource *Source) {
1505     assert(LoadedSLocEntryTable.empty() &&
1506            "Invalidating existing loaded entries");
1507     ExternalSLocEntries = Source;
1508   }
1509
1510   /// \brief Allocate a number of loaded SLocEntries, which will be actually
1511   /// loaded on demand from the external source.
1512   ///
1513   /// NumSLocEntries will be allocated, which occupy a total of TotalSize space
1514   /// in the global source view. The lowest ID and the base offset of the
1515   /// entries will be returned.
1516   std::pair<int, unsigned>
1517   AllocateLoadedSLocEntries(unsigned NumSLocEntries, unsigned TotalSize);
1518
1519   /// \brief Returns true if \p Loc came from a PCH/Module.
1520   bool isLoadedSourceLocation(SourceLocation Loc) const {
1521     return Loc.getOffset() >= CurrentLoadedOffset;
1522   }
1523
1524   /// \brief Returns true if \p Loc did not come from a PCH/Module.
1525   bool isLocalSourceLocation(SourceLocation Loc) const {
1526     return Loc.getOffset() < NextLocalOffset;
1527   }
1528
1529   /// \brief Returns true if \p FID came from a PCH/Module.
1530   bool isLoadedFileID(FileID FID) const {
1531     assert(FID.ID != -1 && "Using FileID sentinel value");
1532     return FID.ID < 0;
1533   }
1534
1535   /// \brief Returns true if \p FID did not come from a PCH/Module.
1536   bool isLocalFileID(FileID FID) const {
1537     return !isLoadedFileID(FID);
1538   }
1539
1540   /// Gets the location of the immediate macro caller, one level up the stack
1541   /// toward the initial macro typed into the source.
1542   SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const {
1543     if (!Loc.isMacroID()) return Loc;
1544
1545     // When we have the location of (part of) an expanded parameter, its
1546     // spelling location points to the argument as expanded in the macro call,
1547     // and therefore is used to locate the macro caller.
1548     if (isMacroArgExpansion(Loc))
1549       return getImmediateSpellingLoc(Loc);
1550
1551     // Otherwise, the caller of the macro is located where this macro is
1552     // expanded (while the spelling is part of the macro definition).
1553     return getImmediateExpansionRange(Loc).first;
1554   }
1555
1556 private:
1557   llvm::MemoryBuffer *getFakeBufferForRecovery() const;
1558   const SrcMgr::ContentCache *getFakeContentCacheForRecovery() const;
1559
1560   const SrcMgr::SLocEntry &loadSLocEntry(unsigned Index, bool *Invalid) const;
1561
1562   /// \brief Get the entry with the given unwrapped FileID.
1563   const SrcMgr::SLocEntry &getSLocEntryByID(int ID,
1564                                             bool *Invalid = nullptr) const {
1565     assert(ID != -1 && "Using FileID sentinel value");
1566     if (ID < 0)
1567       return getLoadedSLocEntryByID(ID, Invalid);
1568     return getLocalSLocEntry(static_cast<unsigned>(ID), Invalid);
1569   }
1570
1571   const SrcMgr::SLocEntry &
1572   getLoadedSLocEntryByID(int ID, bool *Invalid = nullptr) const {
1573     return getLoadedSLocEntry(static_cast<unsigned>(-ID - 2), Invalid);
1574   }
1575
1576   /// Implements the common elements of storing an expansion info struct into
1577   /// the SLocEntry table and producing a source location that refers to it.
1578   SourceLocation createExpansionLocImpl(const SrcMgr::ExpansionInfo &Expansion,
1579                                         unsigned TokLength,
1580                                         int LoadedID = 0,
1581                                         unsigned LoadedOffset = 0);
1582
1583   /// \brief Return true if the specified FileID contains the
1584   /// specified SourceLocation offset.  This is a very hot method.
1585   inline bool isOffsetInFileID(FileID FID, unsigned SLocOffset) const {
1586     const SrcMgr::SLocEntry &Entry = getSLocEntry(FID);
1587     // If the entry is after the offset, it can't contain it.
1588     if (SLocOffset < Entry.getOffset()) return false;
1589
1590     // If this is the very last entry then it does.
1591     if (FID.ID == -2)
1592       return true;
1593
1594     // If it is the last local entry, then it does if the location is local.
1595     if (FID.ID+1 == static_cast<int>(LocalSLocEntryTable.size()))
1596       return SLocOffset < NextLocalOffset;
1597
1598     // Otherwise, the entry after it has to not include it. This works for both
1599     // local and loaded entries.
1600     return SLocOffset < getSLocEntryByID(FID.ID+1).getOffset();
1601   }
1602
1603   /// \brief Returns the previous in-order FileID or an invalid FileID if there
1604   /// is no previous one.
1605   FileID getPreviousFileID(FileID FID) const;
1606
1607   /// \brief Returns the next in-order FileID or an invalid FileID if there is
1608   /// no next one.
1609   FileID getNextFileID(FileID FID) const;
1610
1611   /// \brief Create a new fileID for the specified ContentCache and
1612   /// include position.
1613   ///
1614   /// This works regardless of whether the ContentCache corresponds to a
1615   /// file or some other input source.
1616   FileID createFileID(const SrcMgr::ContentCache* File,
1617                       SourceLocation IncludePos,
1618                       SrcMgr::CharacteristicKind DirCharacter,
1619                       int LoadedID, unsigned LoadedOffset);
1620
1621   const SrcMgr::ContentCache *
1622     getOrCreateContentCache(const FileEntry *SourceFile,
1623                             bool isSystemFile = false);
1624
1625   /// \brief Create a new ContentCache for the specified  memory buffer.
1626   const SrcMgr::ContentCache *
1627   createMemBufferContentCache(llvm::MemoryBuffer *Buf);
1628
1629   FileID getFileIDSlow(unsigned SLocOffset) const;
1630   FileID getFileIDLocal(unsigned SLocOffset) const;
1631   FileID getFileIDLoaded(unsigned SLocOffset) const;
1632
1633   SourceLocation getExpansionLocSlowCase(SourceLocation Loc) const;
1634   SourceLocation getSpellingLocSlowCase(SourceLocation Loc) const;
1635   SourceLocation getFileLocSlowCase(SourceLocation Loc) const;
1636
1637   std::pair<FileID, unsigned>
1638   getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry *E) const;
1639   std::pair<FileID, unsigned>
1640   getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
1641                                    unsigned Offset) const;
1642   void computeMacroArgsCache(MacroArgsMap *&MacroArgsCache, FileID FID) const;
1643   void associateFileChunkWithMacroArgExp(MacroArgsMap &MacroArgsCache,
1644                                          FileID FID,
1645                                          SourceLocation SpellLoc,
1646                                          SourceLocation ExpansionLoc,
1647                                          unsigned ExpansionLength) const;
1648   friend class ASTReader;
1649   friend class ASTWriter;
1650 };
1651
1652 /// \brief Comparison function object.
1653 template<typename T>
1654 class BeforeThanCompare;
1655
1656 /// \brief Compare two source locations.
1657 template<>
1658 class BeforeThanCompare<SourceLocation> {
1659   SourceManager &SM;
1660
1661 public:
1662   explicit BeforeThanCompare(SourceManager &SM) : SM(SM) { }
1663
1664   bool operator()(SourceLocation LHS, SourceLocation RHS) const {
1665     return SM.isBeforeInTranslationUnit(LHS, RHS);
1666   }
1667 };
1668
1669 /// \brief Compare two non-overlapping source ranges.
1670 template<>
1671 class BeforeThanCompare<SourceRange> {
1672   SourceManager &SM;
1673
1674 public:
1675   explicit BeforeThanCompare(SourceManager &SM) : SM(SM) { }
1676
1677   bool operator()(SourceRange LHS, SourceRange RHS) {
1678     return SM.isBeforeInTranslationUnit(LHS.getBegin(), RHS.getBegin());
1679   }
1680 };
1681
1682 }  // end namespace clang
1683
1684
1685 #endif