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