SourceManager.h revision 2bf1eb09f06a9792fa94dff0703f2aa2c4bace2a
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//  This file defines the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SOURCEMANAGER_H
15#define LLVM_CLANG_SOURCEMANAGER_H
16
17#include "clang/Basic/SourceLocation.h"
18#include "llvm/Support/Allocator.h"
19#include "llvm/Support/DataTypes.h"
20#include "llvm/ADT/DenseMap.h"
21#include <vector>
22#include <cassert>
23
24namespace llvm {
25class MemoryBuffer;
26}
27
28namespace clang {
29
30class SourceManager;
31class FileManager;
32class FileEntry;
33class IdentifierTokenInfo;
34class LineTableInfo;
35
36/// SrcMgr - Public enums and private classes that are part of the
37/// SourceManager implementation.
38///
39namespace SrcMgr {
40  /// CharacteristicKind - This is used to represent whether a file or directory
41  /// holds normal user code, system code, or system code which is implicitly
42  /// 'extern "C"' in C++ mode.  Entire directories can be tagged with this
43  /// (this is maintained by DirectoryLookup and friends) as can specific
44  /// FileIDInfos when a #pragma system_header is seen or various other cases.
45  ///
46  enum CharacteristicKind {
47    C_User, C_System, C_ExternCSystem
48  };
49
50  /// ContentCache - Once instance of this struct is kept for every file
51  /// loaded or used.  This object owns the MemoryBuffer object.
52  class ContentCache {
53    /// Buffer - The actual buffer containing the characters from the input
54    /// file.  This is owned by the ContentCache object.
55    mutable const llvm::MemoryBuffer *Buffer;
56
57  public:
58    /// Reference to the file entry.  This reference does not own
59    /// the FileEntry object.  It is possible for this to be NULL if
60    /// the ContentCache encapsulates an imaginary text buffer.
61    const FileEntry *Entry;
62
63    /// SourceLineCache - A bump pointer allocated array of offsets for each
64    /// source line.  This is lazily computed.  This is owned by the
65    /// SourceManager BumpPointerAllocator object.
66    unsigned *SourceLineCache;
67
68    /// NumLines - The number of lines in this ContentCache.  This is only valid
69    /// if SourceLineCache is non-null.
70    unsigned NumLines;
71
72    /// getBuffer - Returns the memory buffer for the associated content.
73    const llvm::MemoryBuffer *getBuffer() const;
74
75    /// getSize - Returns the size of the content encapsulated by this
76    ///  ContentCache. This can be the size of the source file or the size of an
77    ///  arbitrary scratch buffer.  If the ContentCache encapsulates a source
78    ///  file this size is retrieved from the file's FileEntry.
79    unsigned getSize() const;
80
81    /// getSizeBytesMapped - Returns the number of bytes actually mapped for
82    ///  this ContentCache.  This can be 0 if the MemBuffer was not actually
83    ///  instantiated.
84    unsigned getSizeBytesMapped() const;
85
86    void setBuffer(const llvm::MemoryBuffer *B) {
87      assert(!Buffer && "MemoryBuffer already set.");
88      Buffer = B;
89    }
90
91    ContentCache(const FileEntry *Ent = 0)
92      : Buffer(0), Entry(Ent), SourceLineCache(0), NumLines(0) {}
93
94    ~ContentCache();
95
96    /// The copy ctor does not allow copies where source object has either
97    ///  a non-NULL Buffer or SourceLineCache.  Ownership of allocated memory
98    ///  is not transfered, so this is a logical error.
99    ContentCache(const ContentCache &RHS) : Buffer(0), SourceLineCache(0) {
100      Entry = RHS.Entry;
101
102      assert (RHS.Buffer == 0 && RHS.SourceLineCache == 0
103              && "Passed ContentCache object cannot own a buffer.");
104
105      NumLines = RHS.NumLines;
106    }
107
108  private:
109    // Disable assignments.
110    ContentCache &operator=(const ContentCache& RHS);
111  };
112
113  /// FileInfo - Information about a FileID, basically just the logical file
114  /// that it represents and include stack information.
115  ///
116  /// Each FileInfo has include stack information, indicating where it came
117  /// from.  This information encodes the #include chain that a token was
118  /// instantiated from.  The main include file has an invalid IncludeLoc.
119  ///
120  /// FileInfos contain a "ContentCache *", with the contents of the file.
121  ///
122  class FileInfo {
123    /// IncludeLoc - The location of the #include that brought in this file.
124    /// This is an invalid SLOC for the main file (top of the #include chain).
125    unsigned IncludeLoc;  // Really a SourceLocation
126
127    /// Data - This contains the ContentCache* and the bits indicating the
128    /// characteristic of the file and whether it has #line info, all bitmangled
129    /// together.
130    uintptr_t Data;
131  public:
132    /// get - Return a FileInfo object.
133    static FileInfo get(SourceLocation IL, const ContentCache *Con,
134                        CharacteristicKind FileCharacter) {
135      FileInfo X;
136      X.IncludeLoc = IL.getRawEncoding();
137      X.Data = (uintptr_t)Con;
138      assert((X.Data & 7) == 0 &&"ContentCache pointer insufficiently aligned");
139      assert((unsigned)FileCharacter < 4 && "invalid file character");
140      X.Data |= (unsigned)FileCharacter;
141      return X;
142    }
143
144    SourceLocation getIncludeLoc() const {
145      return SourceLocation::getFromRawEncoding(IncludeLoc);
146    }
147    const ContentCache* getContentCache() const {
148      return reinterpret_cast<const ContentCache*>(Data & ~7UL);
149    }
150
151    /// getCharacteristic - Return whether this is a system header or not.
152    CharacteristicKind getFileCharacteristic() const {
153      return (CharacteristicKind)(Data & 3);
154    }
155
156    /// hasLineDirectives - Return true if this FileID has #line directives in
157    /// it.
158    bool hasLineDirectives() const { return (Data & 4) != 0; }
159
160    /// setHasLineDirectives - Set the flag that indicates that this FileID has
161    /// line table entries associated with it.
162    void setHasLineDirectives() {
163      Data |= 4;
164    }
165  };
166
167  /// InstantiationInfo - Each InstantiationInfo encodes the Instantiation
168  /// location - where the token was ultimately instantiated, and the
169  /// SpellingLoc - where the actual character data for the token came from.
170  class InstantiationInfo {
171     // Really these are all SourceLocations.
172
173    /// SpellingLoc - Where the spelling for the token can be found.
174    unsigned SpellingLoc;
175
176    /// InstantiationLocStart/InstantiationLocEnd - In a macro expansion, these
177    /// indicate the start and end of the instantiation.  In object-like macros,
178    /// these will be the same.  In a function-like macro instantiation, the
179    /// start will be the identifier and the end will be the ')'.
180    unsigned InstantiationLocStart, InstantiationLocEnd;
181  public:
182    SourceLocation getSpellingLoc() const {
183      return SourceLocation::getFromRawEncoding(SpellingLoc);
184    }
185    SourceLocation getInstantiationLocStart() const {
186      return SourceLocation::getFromRawEncoding(InstantiationLocStart);
187    }
188    SourceLocation getInstantiationLocEnd() const {
189      return SourceLocation::getFromRawEncoding(InstantiationLocEnd);
190    }
191
192    std::pair<SourceLocation,SourceLocation> getInstantiationLocRange() const {
193      return std::make_pair(getInstantiationLocStart(),
194                            getInstantiationLocEnd());
195    }
196
197    /// get - Return a InstantiationInfo for an expansion.  IL specifies
198    /// the instantiation location (where the macro is expanded), and SL
199    /// specifies the spelling location (where the characters from the token
200    /// come from).  IL and PL can both refer to normal File SLocs or
201    /// instantiation locations.
202    static InstantiationInfo get(SourceLocation ILStart, SourceLocation ILEnd,
203                                 SourceLocation SL) {
204      InstantiationInfo X;
205      X.SpellingLoc = SL.getRawEncoding();
206      X.InstantiationLocStart = ILStart.getRawEncoding();
207      X.InstantiationLocEnd = ILEnd.getRawEncoding();
208      return X;
209    }
210  };
211
212  /// SLocEntry - This is a discriminated union of FileInfo and
213  /// InstantiationInfo.  SourceManager keeps an array of these objects, and
214  /// they are uniquely identified by the FileID datatype.
215  class SLocEntry {
216    unsigned Offset;   // low bit is set for instantiation info.
217    union {
218      FileInfo File;
219      InstantiationInfo Instantiation;
220    };
221  public:
222    unsigned getOffset() const { return Offset >> 1; }
223
224    bool isInstantiation() const { return Offset & 1; }
225    bool isFile() const { return !isInstantiation(); }
226
227    const FileInfo &getFile() const {
228      assert(isFile() && "Not a file SLocEntry!");
229      return File;
230    }
231
232    const InstantiationInfo &getInstantiation() const {
233      assert(isInstantiation() && "Not an instantiation SLocEntry!");
234      return Instantiation;
235    }
236
237    static SLocEntry get(unsigned Offset, const FileInfo &FI) {
238      SLocEntry E;
239      E.Offset = Offset << 1;
240      E.File = FI;
241      return E;
242    }
243
244    static SLocEntry get(unsigned Offset, const InstantiationInfo &II) {
245      SLocEntry E;
246      E.Offset = (Offset << 1) | 1;
247      E.Instantiation = II;
248      return E;
249    }
250  };
251}  // end SrcMgr namespace.
252
253/// \brief External source of source location entries.
254class ExternalSLocEntrySource {
255public:
256  virtual ~ExternalSLocEntrySource();
257
258  /// \brief Read the source location entry with index ID.
259  virtual void ReadSLocEntry(unsigned ID) = 0;
260};
261
262/// SourceManager - This file handles loading and caching of source files into
263/// memory.  This object owns the MemoryBuffer objects for all of the loaded
264/// files and assigns unique FileID's for each unique #include chain.
265///
266/// The SourceManager can be queried for information about SourceLocation
267/// objects, turning them into either spelling or instantiation locations.
268/// Spelling locations represent where the bytes corresponding to a token came
269/// from and instantiation locations represent where the location is in the
270/// user's view.  In the case of a macro expansion, for example, the spelling
271/// location indicates where the expanded token came from and the instantiation
272/// location specifies where it was expanded.
273class SourceManager {
274  mutable llvm::BumpPtrAllocator ContentCacheAlloc;
275
276  /// FileInfos - Memoized information about all of the files tracked by this
277  /// SourceManager.  This set allows us to merge ContentCache entries based
278  /// on their FileEntry*.  All ContentCache objects will thus have unique,
279  /// non-null, FileEntry pointers.
280  llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*> FileInfos;
281
282  /// MemBufferInfos - Information about various memory buffers that we have
283  /// read in.  All FileEntry* within the stored ContentCache objects are NULL,
284  /// as they do not refer to a file.
285  std::vector<SrcMgr::ContentCache*> MemBufferInfos;
286
287  /// SLocEntryTable - This is an array of SLocEntry's that we have created.
288  /// FileID is an index into this vector.  This array is sorted by the offset.
289  std::vector<SrcMgr::SLocEntry> SLocEntryTable;
290  /// NextOffset - This is the next available offset that a new SLocEntry can
291  /// start at.  It is SLocEntryTable.back().getOffset()+size of back() entry.
292  unsigned NextOffset;
293
294  /// \brief If source location entries are being lazily loaded from
295  /// an external source, this vector indicates whether the Ith source
296  /// location entry has already been loaded from the external storage.
297  std::vector<bool> SLocEntryLoaded;
298
299  /// \brief An external source for source location entries.
300  ExternalSLocEntrySource *ExternalSLocEntries;
301
302  /// LastFileIDLookup - This is a one-entry cache to speed up getFileID.
303  /// LastFileIDLookup records the last FileID looked up or created, because it
304  /// is very common to look up many tokens from the same file.
305  mutable FileID LastFileIDLookup;
306
307  /// LineTable - This holds information for #line directives.  It is referenced
308  /// by indices from SLocEntryTable.
309  LineTableInfo *LineTable;
310
311  /// LastLineNo - These ivars serve as a cache used in the getLineNumber
312  /// method which is used to speedup getLineNumber calls to nearby locations.
313  mutable FileID LastLineNoFileIDQuery;
314  mutable SrcMgr::ContentCache *LastLineNoContentCache;
315  mutable unsigned LastLineNoFilePos;
316  mutable unsigned LastLineNoResult;
317
318  /// MainFileID - The file ID for the main source file of the translation unit.
319  FileID MainFileID;
320
321  // Statistics for -print-stats.
322  mutable unsigned NumLinearScans, NumBinaryProbes;
323
324  // SourceManager doesn't support copy construction.
325  explicit SourceManager(const SourceManager&);
326  void operator=(const SourceManager&);
327public:
328  SourceManager()
329    : ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
330      NumBinaryProbes(0) {
331    clearIDTables();
332  }
333  ~SourceManager();
334
335  void clearIDTables();
336
337  //===--------------------------------------------------------------------===//
338  // MainFileID creation and querying methods.
339  //===--------------------------------------------------------------------===//
340
341  /// getMainFileID - Returns the FileID of the main source file.
342  FileID getMainFileID() const { return MainFileID; }
343
344  /// createMainFileID - Create the FileID for the main source file.
345  FileID createMainFileID(const FileEntry *SourceFile,
346                          SourceLocation IncludePos) {
347    assert(MainFileID.isInvalid() && "MainFileID already set!");
348    MainFileID = createFileID(SourceFile, IncludePos, SrcMgr::C_User);
349    return MainFileID;
350  }
351
352  //===--------------------------------------------------------------------===//
353  // Methods to create new FileID's and instantiations.
354  //===--------------------------------------------------------------------===//
355
356  /// createFileID - Create a new FileID that represents the specified file
357  /// being #included from the specified IncludePosition.  This returns 0 on
358  /// error and translates NULL into standard input.
359  /// PreallocateID should be non-zero to specify which a pre-allocated,
360  /// lazily computed source location is being filled in by this operation.
361  FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos,
362                      SrcMgr::CharacteristicKind FileCharacter,
363                      unsigned PreallocatedID = 0,
364                      unsigned Offset = 0) {
365    const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
366    if (IR == 0) return FileID();    // Error opening file?
367    return createFileID(IR, IncludePos, FileCharacter, PreallocatedID, Offset);
368  }
369
370  /// createFileIDForMemBuffer - Create a new FileID that represents the
371  /// specified memory buffer.  This does no caching of the buffer and takes
372  /// ownership of the MemoryBuffer, so only pass a MemoryBuffer to this once.
373  FileID createFileIDForMemBuffer(const llvm::MemoryBuffer *Buffer,
374                                  unsigned PreallocatedID = 0,
375                                  unsigned Offset = 0) {
376    return createFileID(createMemBufferContentCache(Buffer), SourceLocation(),
377                        SrcMgr::C_User, PreallocatedID, Offset);
378  }
379
380  /// createMainFileIDForMembuffer - Create the FileID for a memory buffer
381  ///  that will represent the FileID for the main source.  One example
382  ///  of when this would be used is when the main source is read from STDIN.
383  FileID createMainFileIDForMemBuffer(const llvm::MemoryBuffer *Buffer) {
384    assert(MainFileID.isInvalid() && "MainFileID already set!");
385    MainFileID = createFileIDForMemBuffer(Buffer);
386    return MainFileID;
387  }
388
389  /// createInstantiationLoc - Return a new SourceLocation that encodes the fact
390  /// that a token at Loc should actually be referenced from InstantiationLoc.
391  /// TokLength is the length of the token being instantiated.
392  SourceLocation createInstantiationLoc(SourceLocation Loc,
393                                        SourceLocation InstantiationLocStart,
394                                        SourceLocation InstantiationLocEnd,
395                                        unsigned TokLength,
396                                        unsigned PreallocatedID = 0,
397                                        unsigned Offset = 0);
398
399  //===--------------------------------------------------------------------===//
400  // FileID manipulation methods.
401  //===--------------------------------------------------------------------===//
402
403  /// getBuffer - Return the buffer for the specified FileID.
404  ///
405  const llvm::MemoryBuffer *getBuffer(FileID FID) const {
406    return getSLocEntry(FID).getFile().getContentCache()->getBuffer();
407  }
408
409  /// getFileEntryForID - Returns the FileEntry record for the provided FileID.
410  const FileEntry *getFileEntryForID(FileID FID) const {
411    return getSLocEntry(FID).getFile().getContentCache()->Entry;
412  }
413
414  /// getBufferData - Return a pointer to the start and end of the source buffer
415  /// data for the specified FileID.
416  std::pair<const char*, const char*> getBufferData(FileID FID) const;
417
418
419  //===--------------------------------------------------------------------===//
420  // SourceLocation manipulation methods.
421  //===--------------------------------------------------------------------===//
422
423  /// getFileID - Return the FileID for a SourceLocation.  This is a very
424  /// hot method that is used for all SourceManager queries that start with a
425  /// SourceLocation object.  It is responsible for finding the entry in
426  /// SLocEntryTable which contains the specified location.
427  ///
428  FileID getFileID(SourceLocation SpellingLoc) const {
429    unsigned SLocOffset = SpellingLoc.getOffset();
430
431    // If our one-entry cache covers this offset, just return it.
432    if (isOffsetInFileID(LastFileIDLookup, SLocOffset))
433      return LastFileIDLookup;
434
435    return getFileIDSlow(SLocOffset);
436  }
437
438  /// getLocForStartOfFile - Return the source location corresponding to the
439  /// first byte of the specified file.
440  SourceLocation getLocForStartOfFile(FileID FID) const {
441    assert(FID.ID < SLocEntryTable.size() && "FileID out of range");
442    assert(getSLocEntry(FID).isFile() && "FileID is not a file");
443    unsigned FileOffset = getSLocEntry(FID).getOffset();
444    return SourceLocation::getFileLoc(FileOffset);
445  }
446
447  /// getInstantiationLoc - Given a SourceLocation object, return the
448  /// instantiation location referenced by the ID.
449  SourceLocation getInstantiationLoc(SourceLocation Loc) const {
450    // Handle the non-mapped case inline, defer to out of line code to handle
451    // instantiations.
452    if (Loc.isFileID()) return Loc;
453    return getInstantiationLocSlowCase(Loc);
454  }
455
456  /// getImmediateInstantiationRange - Loc is required to be an instantiation
457  /// location.  Return the start/end of the instantiation information.
458  std::pair<SourceLocation,SourceLocation>
459  getImmediateInstantiationRange(SourceLocation Loc) const;
460
461  /// getInstantiationRange - Given a SourceLocation object, return the
462  /// range of tokens covered by the instantiation in the ultimate file.
463  std::pair<SourceLocation,SourceLocation>
464  getInstantiationRange(SourceLocation Loc) const;
465
466
467  /// getSpellingLoc - Given a SourceLocation object, return the spelling
468  /// location referenced by the ID.  This is the place where the characters
469  /// that make up the lexed token can be found.
470  SourceLocation getSpellingLoc(SourceLocation Loc) const {
471    // Handle the non-mapped case inline, defer to out of line code to handle
472    // instantiations.
473    if (Loc.isFileID()) return Loc;
474    return getSpellingLocSlowCase(Loc);
475  }
476
477  /// getImmediateSpellingLoc - Given a SourceLocation object, return the
478  /// spelling location referenced by the ID.  This is the first level down
479  /// towards the place where the characters that make up the lexed token can be
480  /// found.  This should not generally be used by clients.
481  SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const;
482
483  /// getDecomposedLoc - Decompose the specified location into a raw FileID +
484  /// Offset pair.  The first element is the FileID, the second is the
485  /// offset from the start of the buffer of the location.
486  std::pair<FileID, unsigned> getDecomposedLoc(SourceLocation Loc) const {
487    FileID FID = getFileID(Loc);
488    return std::make_pair(FID, Loc.getOffset()-getSLocEntry(FID).getOffset());
489  }
490
491  /// getDecomposedInstantiationLoc - Decompose the specified location into a
492  /// raw FileID + Offset pair.  If the location is an instantiation record,
493  /// walk through it until we find the final location instantiated.
494  std::pair<FileID, unsigned>
495  getDecomposedInstantiationLoc(SourceLocation Loc) const {
496    FileID FID = getFileID(Loc);
497    const SrcMgr::SLocEntry *E = &getSLocEntry(FID);
498
499    unsigned Offset = Loc.getOffset()-E->getOffset();
500    if (Loc.isFileID())
501      return std::make_pair(FID, Offset);
502
503    return getDecomposedInstantiationLocSlowCase(E, Offset);
504  }
505
506  /// getDecomposedSpellingLoc - Decompose the specified location into a raw
507  /// FileID + Offset pair.  If the location is an instantiation record, walk
508  /// through it until we find its spelling record.
509  std::pair<FileID, unsigned>
510  getDecomposedSpellingLoc(SourceLocation Loc) const {
511    FileID FID = getFileID(Loc);
512    const SrcMgr::SLocEntry *E = &getSLocEntry(FID);
513
514    unsigned Offset = Loc.getOffset()-E->getOffset();
515    if (Loc.isFileID())
516      return std::make_pair(FID, Offset);
517    return getDecomposedSpellingLocSlowCase(E, Offset);
518  }
519
520  /// getFileOffset - This method returns the offset from the start
521  /// of the file that the specified SourceLocation represents. This is not very
522  /// meaningful for a macro ID.
523  unsigned getFileOffset(SourceLocation SpellingLoc) const {
524    return getDecomposedLoc(SpellingLoc).second;
525  }
526
527
528  //===--------------------------------------------------------------------===//
529  // Queries about the code at a SourceLocation.
530  //===--------------------------------------------------------------------===//
531
532  /// getCharacterData - Return a pointer to the start of the specified location
533  /// in the appropriate spelling MemoryBuffer.
534  const char *getCharacterData(SourceLocation SL) const;
535
536  /// getColumnNumber - Return the column # for the specified file position.
537  /// This is significantly cheaper to compute than the line number.  This
538  /// returns zero if the column number isn't known.  This may only be called on
539  /// a file sloc, so you must choose a spelling or instantiation location
540  /// before calling this method.
541  unsigned getColumnNumber(FileID FID, unsigned FilePos) const;
542  unsigned getSpellingColumnNumber(SourceLocation Loc) const;
543  unsigned getInstantiationColumnNumber(SourceLocation Loc) const;
544
545
546  /// getLineNumber - Given a SourceLocation, return the spelling line number
547  /// for the position indicated.  This requires building and caching a table of
548  /// line offsets for the MemoryBuffer, so this is not cheap: use only when
549  /// about to emit a diagnostic.
550  unsigned getLineNumber(FileID FID, unsigned FilePos) const;
551
552  unsigned getInstantiationLineNumber(SourceLocation Loc) const;
553  unsigned getSpellingLineNumber(SourceLocation Loc) const;
554
555  /// Return the filename or buffer identifier of the buffer the location is in.
556  /// Note that this name does not respect #line directives.  Use getPresumedLoc
557  /// for normal clients.
558  const char *getBufferName(SourceLocation Loc) const;
559
560  /// getFileCharacteristic - return the file characteristic of the specified
561  /// source location, indicating whether this is a normal file, a system
562  /// header, or an "implicit extern C" system header.
563  ///
564  /// This state can be modified with flags on GNU linemarker directives like:
565  ///   # 4 "foo.h" 3
566  /// which changes all source locations in the current file after that to be
567  /// considered to be from a system header.
568  SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const;
569
570  /// getPresumedLoc - This method returns the "presumed" location of a
571  /// SourceLocation specifies.  A "presumed location" can be modified by #line
572  /// or GNU line marker directives.  This provides a view on the data that a
573  /// user should see in diagnostics, for example.
574  ///
575  /// Note that a presumed location is always given as the instantiation point
576  /// of an instantiation location, not at the spelling location.
577  PresumedLoc getPresumedLoc(SourceLocation Loc) const;
578
579  /// isFromSameFile - Returns true if both SourceLocations correspond to
580  ///  the same file.
581  bool isFromSameFile(SourceLocation Loc1, SourceLocation Loc2) const {
582    return getFileID(Loc1) == getFileID(Loc2);
583  }
584
585  /// isFromMainFile - Returns true if the file of provided SourceLocation is
586  ///   the main file.
587  bool isFromMainFile(SourceLocation Loc) const {
588    return getFileID(Loc) == getMainFileID();
589  }
590
591  /// isInSystemHeader - Returns if a SourceLocation is in a system header.
592  bool isInSystemHeader(SourceLocation Loc) const {
593    return getFileCharacteristic(Loc) != SrcMgr::C_User;
594  }
595
596  //===--------------------------------------------------------------------===//
597  // Line Table Manipulation Routines
598  //===--------------------------------------------------------------------===//
599
600  /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
601  ///
602  unsigned getLineTableFilenameID(const char *Ptr, unsigned Len);
603
604  /// AddLineNote - Add a line note to the line table for the FileID and offset
605  /// specified by Loc.  If FilenameID is -1, it is considered to be
606  /// unspecified.
607  void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID);
608  void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID,
609                   bool IsFileEntry, bool IsFileExit,
610                   bool IsSystemHeader, bool IsExternCHeader);
611
612  /// \brief Determine if the source manager has a line table.
613  bool hasLineTable() const { return LineTable != 0; }
614
615  /// \brief Retrieve the stored line table.
616  LineTableInfo &getLineTable();
617
618  //===--------------------------------------------------------------------===//
619  // Other miscellaneous methods.
620  //===--------------------------------------------------------------------===//
621
622  // Iterators over FileInfos.
623  typedef llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>
624      ::const_iterator fileinfo_iterator;
625  fileinfo_iterator fileinfo_begin() const { return FileInfos.begin(); }
626  fileinfo_iterator fileinfo_end() const { return FileInfos.end(); }
627
628  /// PrintStats - Print statistics to stderr.
629  ///
630  void PrintStats() const;
631
632  // Iteration over the source location entry table.
633  typedef std::vector<SrcMgr::SLocEntry>::const_iterator sloc_entry_iterator;
634
635  sloc_entry_iterator sloc_entry_begin() const {
636    return SLocEntryTable.begin();
637  }
638
639  sloc_entry_iterator sloc_entry_end() const {
640    return SLocEntryTable.end();
641  }
642
643  unsigned sloc_entry_size() const { return SLocEntryTable.size(); }
644
645  const SrcMgr::SLocEntry &getSLocEntry(FileID FID) const {
646    assert(FID.ID < SLocEntryTable.size() && "Invalid id");
647    if (ExternalSLocEntries &&
648        FID.ID < SLocEntryLoaded.size() &&
649        !SLocEntryLoaded[FID.ID])
650      ExternalSLocEntries->ReadSLocEntry(FID.ID);
651    return SLocEntryTable[FID.ID];
652  }
653
654  unsigned getNextOffset() const { return NextOffset; }
655
656  /// \brief Preallocate some number of source location entries, which
657  /// will be loaded as needed from the given external source.
658  void PreallocateSLocEntries(ExternalSLocEntrySource *Source,
659                              unsigned NumSLocEntries,
660                              unsigned NextOffset);
661
662  /// \brief Clear out any preallocated source location entries that
663  /// haven't already been loaded.
664  void ClearPreallocatedSLocEntries();
665
666private:
667  /// isOffsetInFileID - Return true if the specified FileID contains the
668  /// specified SourceLocation offset.  This is a very hot method.
669  inline bool isOffsetInFileID(FileID FID, unsigned SLocOffset) const {
670    const SrcMgr::SLocEntry &Entry = getSLocEntry(FID);
671    // If the entry is after the offset, it can't contain it.
672    if (SLocOffset < Entry.getOffset()) return false;
673
674    // If this is the last entry than it does.  Otherwise, the entry after it
675    // has to not include it.
676    if (FID.ID+1 == SLocEntryTable.size()) return true;
677
678    return SLocOffset < getSLocEntry(FileID::get(FID.ID+1)).getOffset();
679  }
680
681  /// createFileID - Create a new fileID for the specified ContentCache and
682  ///  include position.  This works regardless of whether the ContentCache
683  ///  corresponds to a file or some other input source.
684  FileID createFileID(const SrcMgr::ContentCache* File,
685                      SourceLocation IncludePos,
686                      SrcMgr::CharacteristicKind DirCharacter,
687                      unsigned PreallocatedID = 0,
688                      unsigned Offset = 0);
689
690  const SrcMgr::ContentCache *
691    getOrCreateContentCache(const FileEntry *SourceFile);
692
693  /// createMemBufferContentCache - Create a new ContentCache for the specified
694  ///  memory buffer.
695  const SrcMgr::ContentCache*
696  createMemBufferContentCache(const llvm::MemoryBuffer *Buf);
697
698  FileID getFileIDSlow(unsigned SLocOffset) const;
699
700  SourceLocation getInstantiationLocSlowCase(SourceLocation Loc) const;
701  SourceLocation getSpellingLocSlowCase(SourceLocation Loc) const;
702
703  std::pair<FileID, unsigned>
704  getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
705                                        unsigned Offset) const;
706  std::pair<FileID, unsigned>
707  getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
708                                   unsigned Offset) const;
709};
710
711
712}  // end namespace clang
713
714#endif
715