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