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