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