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