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