blob: d6c4c16cec745157fab122f0b62aec1b5ff22112 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregord4f77aa2009-04-13 15:31:25 +000015#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregoraea67db2010-03-15 22:54:52 +000016#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/FileManager.h"
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000018#include "llvm/ADT/StringSwitch.h"
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000019#include "llvm/ADT/Optional.h"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000020#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "llvm/Support/MemoryBuffer.h"
Chris Lattnerd57a7ef2009-08-23 22:45:33 +000022#include "llvm/Support/raw_ostream.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000023#include "llvm/Support/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include <algorithm>
Douglas Gregoraea67db2010-03-15 22:54:52 +000025#include <string>
Douglas Gregorf715ca12010-03-16 00:06:06 +000026#include <cstring>
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000027#include <sys/stat.h>
Douglas Gregoraea67db2010-03-15 22:54:52 +000028
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30using namespace SrcMgr;
31using llvm::MemoryBuffer;
32
Chris Lattner23b5dc62009-02-04 00:40:31 +000033//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000034// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000035//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000036
Ted Kremenek78d85f52007-10-30 21:08:08 +000037ContentCache::~ContentCache() {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000038 if (shouldFreeBuffer())
39 delete Buffer.getPointer();
Reid Spencer5f016e22007-07-11 17:01:13 +000040}
41
Ted Kremenekc16c2082009-01-06 01:55:26 +000042/// getSizeBytesMapped - Returns the number of bytes actually mapped for
43/// this ContentCache. This can be 0 if the MemBuffer was not actually
44/// instantiated.
45unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000046 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000047}
48
Ted Kremenekf61b8312011-04-28 20:36:42 +000049/// Returns the kind of memory used to back the memory buffer for
50/// this content cache. This is used for performance analysis.
51llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
52 assert(Buffer.getPointer());
53
54 // Should be unreachable, but keep for sanity.
55 if (!Buffer.getPointer())
56 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
57
58 const llvm::MemoryBuffer *buf = Buffer.getPointer();
59 return buf->getBufferKind();
60}
61
Ted Kremenekc16c2082009-01-06 01:55:26 +000062/// getSize - Returns the size of the content encapsulated by this ContentCache.
63/// This can be the size of the source file or the size of an arbitrary
64/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +000065/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000066unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000067 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000068 : (unsigned) ContentsEntry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000069}
70
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000071void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
72 bool DoNotFree) {
Douglas Gregorc8151082010-03-16 22:53:51 +000073 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000074
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000075 if (shouldFreeBuffer())
76 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000077 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000078 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000079}
80
Douglas Gregor36c35ba2010-03-16 00:35:39 +000081const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner5c5db4e2010-04-20 20:49:23 +000082 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000083 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000084 bool *Invalid) const {
Chris Lattnerb088cd32010-11-23 08:50:03 +000085 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000086 // computed it, just return what we have.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000087 if (Buffer.getPointer() || ContentsEntry == 0) {
Chris Lattnerb088cd32010-11-23 08:50:03 +000088 if (Invalid)
89 *Invalid = isBufferInvalid();
Chris Lattner38caec42010-04-20 18:14:03 +000090
Chris Lattnerb088cd32010-11-23 08:50:03 +000091 return Buffer.getPointer();
92 }
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000093
Chris Lattnerb088cd32010-11-23 08:50:03 +000094 std::string ErrorStr;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000095 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
Chris Lattnerb088cd32010-11-23 08:50:03 +000096
97 // If we were unable to open the file, then we are in an inconsistent
98 // situation where the content cache referenced a file which no longer
99 // exists. Most likely, we were using a stat cache with an invalid entry but
100 // the file could also have been removed during processing. Since we can't
101 // really deal with this situation, just create an empty buffer.
102 //
103 // FIXME: This is definitely not ideal, but our immediate clients can't
104 // currently handle returning a null entry here. Ideally we should detect
105 // that we are in an inconsistent situation and error out as quickly as
106 // possible.
107 if (!Buffer.getPointer()) {
108 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000109 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattnerb088cd32010-11-23 08:50:03 +0000110 "<invalid>"));
111 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000112 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000113 Ptr[i] = FillStr[i % FillStr.size()];
114
115 if (Diag.isDiagnosticInFlight())
116 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000117 ContentsEntry->getName(), ErrorStr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000118 else
119 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000120 << ContentsEntry->getName() << ErrorStr;
Chris Lattnerb088cd32010-11-23 08:50:03 +0000121
122 Buffer.setInt(Buffer.getInt() | InvalidFlag);
123
124 if (Invalid) *Invalid = true;
125 return Buffer.getPointer();
126 }
127
128 // Check that the file's size is the same as in the file entry (which may
129 // have come from a stat cache).
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000130 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000131 if (Diag.isDiagnosticInFlight())
132 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000133 ContentsEntry->getName());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000134 else
135 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000136 << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000137
138 Buffer.setInt(Buffer.getInt() | InvalidFlag);
139 if (Invalid) *Invalid = true;
140 return Buffer.getPointer();
141 }
Eric Christopher156119d2011-04-09 00:01:04 +0000142
Chris Lattnerb088cd32010-11-23 08:50:03 +0000143 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher156119d2011-04-09 00:01:04 +0000144 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattnerb088cd32010-11-23 08:50:03 +0000145 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
146 llvm::StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher156119d2011-04-09 00:01:04 +0000147 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000148 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
149 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
150 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
151 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
152 .StartsWith("\x2B\x2F\x76", "UTF-7")
153 .StartsWith("\xF7\x64\x4C", "UTF-1")
154 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
155 .StartsWith("\x0E\xFE\xFF", "SDSU")
156 .StartsWith("\xFB\xEE\x28", "BOCU-1")
157 .StartsWith("\x84\x31\x95\x33", "GB-18030")
158 .Default(0);
159
Eric Christopher156119d2011-04-09 00:01:04 +0000160 if (InvalidBOM) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000161 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher156119d2011-04-09 00:01:04 +0000162 << InvalidBOM << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000163 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000164 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000165
Douglas Gregorc8151082010-03-16 22:53:51 +0000166 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000167 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000168
169 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000170}
171
Jay Foad65aa6882011-06-21 15:13:30 +0000172unsigned LineTableInfo::getLineTableFilenameID(llvm::StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000173 // Look up the filename in the string table, returning the pre-existing value
174 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000175 llvm::StringMapEntry<unsigned> &Entry =
Jay Foad65aa6882011-06-21 15:13:30 +0000176 FilenameIDs.GetOrCreateValue(Name, ~0U);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000177 if (Entry.getValue() != ~0U)
178 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattner5b9a5042009-01-26 07:57:50 +0000180 // Otherwise, assign this the next available ID.
181 Entry.setValue(FilenamesByID.size());
182 FilenamesByID.push_back(&Entry);
183 return FilenamesByID.size()-1;
184}
185
Chris Lattnerac50e342009-02-03 22:13:05 +0000186/// AddLineNote - Add a line note to the line table that indicates that there
187/// is a #line at the specified FID/Offset location which changes the presumed
188/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000189void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000190 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000191 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattner23b5dc62009-02-04 00:40:31 +0000193 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
194 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattner9d79eba2009-02-04 05:21:58 +0000196 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000197 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattner9d79eba2009-02-04 05:21:58 +0000199 if (!Entries.empty()) {
200 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
201 // that we are still in "foo.h".
202 if (FilenameID == -1)
203 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Chris Lattner137b6a62009-02-04 06:25:26 +0000205 // If we are after a line marker that switched us to system header mode, or
206 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000207 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000208 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000209 }
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Chris Lattner137b6a62009-02-04 06:25:26 +0000211 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
212 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000213}
214
Chris Lattner9d79eba2009-02-04 05:21:58 +0000215/// AddLineNote This is the same as the previous version of AddLineNote, but is
216/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
217/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
218/// this is a file exit. FileKind specifies whether this is a system header or
219/// extern C system header.
220void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
221 unsigned LineNo, int FilenameID,
222 unsigned EntryExit,
223 SrcMgr::CharacteristicKind FileKind) {
224 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Chris Lattner9d79eba2009-02-04 05:21:58 +0000226 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattner9d79eba2009-02-04 05:21:58 +0000228 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
229 "Adding line entries out of order!");
230
Chris Lattner137b6a62009-02-04 06:25:26 +0000231 unsigned IncludeOffset = 0;
232 if (EntryExit == 0) { // No #include stack change.
233 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
234 } else if (EntryExit == 1) {
235 IncludeOffset = Offset-1;
236 } else if (EntryExit == 2) {
237 assert(!Entries.empty() && Entries.back().IncludeOffset &&
238 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Chris Lattner137b6a62009-02-04 06:25:26 +0000240 // Get the include loc of the last entries' include loc as our include loc.
241 IncludeOffset = 0;
242 if (const LineEntry *PrevEntry =
243 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
244 IncludeOffset = PrevEntry->IncludeOffset;
245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattner137b6a62009-02-04 06:25:26 +0000247 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
248 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000249}
250
251
Chris Lattner3cd949c2009-02-04 01:55:42 +0000252/// FindNearestLineEntry - Find the line entry nearest to FID that is before
253/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000254const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000255 unsigned Offset) {
256 const std::vector<LineEntry> &Entries = LineEntries[FID];
257 assert(!Entries.empty() && "No #line entries for this FID after all!");
258
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000259 // It is very common for the query to be after the last #line, check this
260 // first.
261 if (Entries.back().FileOffset <= Offset)
262 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000263
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000264 // Do a binary search to find the maximal element that is still before Offset.
265 std::vector<LineEntry>::const_iterator I =
266 std::upper_bound(Entries.begin(), Entries.end(), Offset);
267 if (I == Entries.begin()) return 0;
268 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000269}
Chris Lattnerac50e342009-02-03 22:13:05 +0000270
Douglas Gregorbd945002009-04-13 16:31:14 +0000271/// \brief Add a new line entry that has already been encoded into
272/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000273void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000274 const std::vector<LineEntry> &Entries) {
275 LineEntries[FID] = Entries;
276}
Chris Lattnerac50e342009-02-03 22:13:05 +0000277
Chris Lattner5b9a5042009-01-26 07:57:50 +0000278/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000279///
Jay Foad65aa6882011-06-21 15:13:30 +0000280unsigned SourceManager::getLineTableFilenameID(llvm::StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000281 if (LineTable == 0)
282 LineTable = new LineTableInfo();
Jay Foad65aa6882011-06-21 15:13:30 +0000283 return LineTable->getLineTableFilenameID(Name);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000284}
285
286
Chris Lattner4c4ea172009-02-03 21:52:55 +0000287/// AddLineNote - Add a line note to the line table for the FileID and offset
288/// specified by Loc. If FilenameID is -1, it is considered to be
289/// unspecified.
290void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
291 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000292 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Douglas Gregore23ac652011-04-20 00:21:03 +0000294 bool Invalid = false;
295 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
296 if (!Entry.isFile() || Invalid)
297 return;
298
299 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattnerac50e342009-02-03 22:13:05 +0000300
301 // Remember that this file has #line directives now if it doesn't already.
302 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattnerac50e342009-02-03 22:13:05 +0000304 if (LineTable == 0)
305 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000306 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000307}
308
Chris Lattner9d79eba2009-02-04 05:21:58 +0000309/// AddLineNote - Add a GNU line marker to the line table.
310void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
311 int FilenameID, bool IsFileEntry,
312 bool IsFileExit, bool IsSystemHeader,
313 bool IsExternCHeader) {
314 // If there is no filename and no flags, this is treated just like a #line,
315 // which does not change the flags of the previous line marker.
316 if (FilenameID == -1) {
317 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
318 "Can't set flags without setting the filename!");
319 return AddLineNote(Loc, LineNo, FilenameID);
320 }
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattner9d79eba2009-02-04 05:21:58 +0000322 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +0000323
324 bool Invalid = false;
325 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
326 if (!Entry.isFile() || Invalid)
327 return;
328
329 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Chris Lattner9d79eba2009-02-04 05:21:58 +0000331 // Remember that this file has #line directives now if it doesn't already.
332 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Chris Lattner9d79eba2009-02-04 05:21:58 +0000334 if (LineTable == 0)
335 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Chris Lattner9d79eba2009-02-04 05:21:58 +0000337 SrcMgr::CharacteristicKind FileKind;
338 if (IsExternCHeader)
339 FileKind = SrcMgr::C_ExternCSystem;
340 else if (IsSystemHeader)
341 FileKind = SrcMgr::C_System;
342 else
343 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Chris Lattner9d79eba2009-02-04 05:21:58 +0000345 unsigned EntryExit = 0;
346 if (IsFileEntry)
347 EntryExit = 1;
348 else if (IsFileExit)
349 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Chris Lattner9d79eba2009-02-04 05:21:58 +0000351 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
352 EntryExit, FileKind);
353}
354
Douglas Gregorbd945002009-04-13 16:31:14 +0000355LineTableInfo &SourceManager::getLineTable() {
356 if (LineTable == 0)
357 LineTable = new LineTableInfo();
358 return *LineTable;
359}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000360
Chris Lattner23b5dc62009-02-04 00:40:31 +0000361//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000362// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000363//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000364
Chris Lattner39b49bc2010-11-23 08:35:12 +0000365SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000366 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000367 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
Douglas Gregore23ac652011-04-20 00:21:03 +0000368 NumBinaryProbes(0), FakeBufferForRecovery(0) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000369 clearIDTables();
370 Diag.setSourceManager(this);
371}
372
Chris Lattner5b9a5042009-01-26 07:57:50 +0000373SourceManager::~SourceManager() {
374 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000376 // Delete FileEntry objects corresponding to content caches. Since the actual
377 // content cache objects are bump pointer allocated, we just have to run the
378 // dtors, but we call the deallocate method for completeness.
379 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
380 MemBufferInfos[i]->~ContentCache();
381 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
382 }
383 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
384 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
385 I->second->~ContentCache();
386 ContentCacheAlloc.Deallocate(I->second);
387 }
Douglas Gregore23ac652011-04-20 00:21:03 +0000388
389 delete FakeBufferForRecovery;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000390}
391
392void SourceManager::clearIDTables() {
393 MainFileID = FileID();
394 SLocEntryTable.clear();
395 LastLineNoFileIDQuery = FileID();
396 LastLineNoContentCache = 0;
397 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Chris Lattner5b9a5042009-01-26 07:57:50 +0000399 if (LineTable)
400 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Chris Lattner5b9a5042009-01-26 07:57:50 +0000402 // Use up FileID #0 as an invalid instantiation.
403 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000404 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000405}
406
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000407/// getOrCreateContentCache - Create or return a cached ContentCache for the
408/// specified file.
409const ContentCache *
410SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000414 ContentCache *&Entry = FileInfos[FileEnt];
415 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Chris Lattner00282d62009-02-03 07:41:46 +0000417 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
418 // so that FileInfo can use the low 3 bits of the pointer for its own
419 // nefarious purposes.
420 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
421 EntryAlign = std::max(8U, EntryAlign);
422 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000423
424 // If the file contents are overridden with contents from another file,
425 // pass that file to ContentCache.
426 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
427 overI = OverriddenFiles.find(FileEnt);
428 if (overI == OverriddenFiles.end())
429 new (Entry) ContentCache(FileEnt);
430 else
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000431 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
432 : overI->second,
433 overI->second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000434
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000435 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000436}
437
438
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000439/// createMemBufferContentCache - Create a new ContentCache for the specified
440/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000441const ContentCache*
442SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000443 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
444 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
445 // the pointer for its own nefarious purposes.
446 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
447 EntryAlign = std::max(8U, EntryAlign);
448 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000449 new (Entry) ContentCache();
450 MemBufferInfos.push_back(Entry);
451 Entry->setBuffer(Buffer);
452 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000453}
454
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000455void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
456 unsigned NumSLocEntries,
457 unsigned NextOffset) {
458 ExternalSLocEntries = Source;
459 this->NextOffset = NextOffset;
Sebastian Redlb86238d2010-07-28 21:07:02 +0000460 unsigned CurPrealloc = SLocEntryLoaded.size();
461 // If we've ever preallocated, we must not count the dummy entry.
462 if (CurPrealloc) --CurPrealloc;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000463 SLocEntryLoaded.resize(NumSLocEntries + 1);
464 SLocEntryLoaded[0] = true;
Sebastian Redlb86238d2010-07-28 21:07:02 +0000465 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries - CurPrealloc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000466}
467
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000468void SourceManager::ClearPreallocatedSLocEntries() {
469 unsigned I = 0;
470 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
471 if (!SLocEntryLoaded[I])
472 break;
473
474 // We've already loaded all preallocated source location entries.
475 if (I == SLocEntryLoaded.size())
476 return;
477
478 // Remove everything from location I onward.
479 SLocEntryTable.resize(I);
480 SLocEntryLoaded.clear();
481 ExternalSLocEntries = 0;
482}
483
Douglas Gregore23ac652011-04-20 00:21:03 +0000484/// \brief As part of recovering from missing or changed content, produce a
485/// fake, non-empty buffer.
486const llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
487 if (!FakeBufferForRecovery)
488 FakeBufferForRecovery
489 = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
490
491 return FakeBufferForRecovery;
492}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000493
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000494//===----------------------------------------------------------------------===//
495// Methods to create new FileID's and instantiations.
496//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000497
Dan Gohman3f86b782010-08-26 21:27:06 +0000498/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000499/// include position. This works regardless of whether the ContentCache
500/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000501FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000502 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000503 SrcMgr::CharacteristicKind FileCharacter,
504 unsigned PreallocatedID,
505 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000506 if (PreallocatedID) {
507 // If we're filling in a preallocated ID, just load in the file
508 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000509 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000510 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000511 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000512 "Source location entry already loaded");
513 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000514 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000515 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
516 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000517 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor5de65722010-03-19 06:12:06 +0000518 return FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000519 }
520
Mike Stump1eb44332009-09-09 15:08:12 +0000521 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000522 FileInfo::get(IncludePos, File,
523 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000524 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000525 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
526 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000528 // Set LastFileIDLookup to the newly created file. The next getFileID call is
529 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000530 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000531 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000532}
533
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000534/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000535/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000536/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000537SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000538 SourceLocation ILocStart,
539 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000540 unsigned TokLength,
541 unsigned PreallocatedID,
542 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000543 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000544 if (PreallocatedID) {
545 // If we're filling in a preallocated ID, just load in the
546 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000547 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000548 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000549 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000550 "Source location entry already loaded");
551 assert(Offset && "Preallocate source location cannot have zero offset");
552 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
553 SLocEntryLoaded[PreallocatedID] = true;
554 return SourceLocation::getMacroLoc(Offset);
555 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000556 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000557 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
558 NextOffset += TokLength+1;
559 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000560}
561
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000562const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000563SourceManager::getMemoryBufferForFile(const FileEntry *File,
564 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000565 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000566 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000567 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000568}
569
Dan Gohman0d06e992010-10-26 20:47:28 +0000570void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000571 const llvm::MemoryBuffer *Buffer,
572 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000573 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000574 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000575
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000576 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor29684422009-12-02 06:49:09 +0000577}
578
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000579void SourceManager::overrideFileContents(const FileEntry *SourceFile,
580 const FileEntry *NewFile) {
581 assert(SourceFile->getSize() == NewFile->getSize() &&
582 "Different sizes, use the FileManager to create a virtual file with "
583 "the correct size");
584 assert(FileInfos.count(SourceFile) == 0 &&
585 "This function should be called at the initialization stage, before "
586 "any parsing occurs.");
587 OverriddenFiles[SourceFile] = NewFile;
588}
589
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000590llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000591 bool MyInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +0000592 const SLocEntry &SLoc = getSLocEntry(FID.ID, &MyInvalid);
593 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor3de84242011-01-31 22:42:36 +0000594 if (Invalid)
595 *Invalid = true;
596 return "<<<<<INVALID SOURCE LOCATION>>>>>";
597 }
598
599 const llvm::MemoryBuffer *Buf
600 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
601 &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000602 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000603 *Invalid = MyInvalid;
604
605 if (MyInvalid)
Douglas Gregor3de84242011-01-31 22:42:36 +0000606 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000607
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000608 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000609}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000610
Chris Lattner23b5dc62009-02-04 00:40:31 +0000611//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000612// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000613//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000614
615/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
616/// method that is used for all SourceManager queries that start with a
617/// SourceLocation object. It is responsible for finding the entry in
618/// SLocEntryTable which contains the specified location.
619///
620FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregore23ac652011-04-20 00:21:03 +0000621 if (!SLocOffset)
622 return FileID::get(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000624 // After the first and second level caches, I see two common sorts of
625 // behavior: 1) a lot of searched FileID's are "near" the cached file location
626 // or are "near" the cached instantiation location. 2) others are just
627 // completely random and may be a very long way away.
628 //
629 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
630 // then we fall back to a less cache efficient, but more scalable, binary
631 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000633 // See if this is near the file point - worst case we start scanning from the
634 // most newly created FileID.
635 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000637 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
638 // Neither loc prunes our search.
639 I = SLocEntryTable.end();
640 } else {
641 // Perhaps it is near the file point.
642 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
643 }
644
645 // Find the FileID that contains this. "I" is an iterator that points to a
646 // FileID whose offset is known to be larger than SLocOffset.
647 unsigned NumProbes = 0;
648 while (1) {
649 --I;
Douglas Gregore23ac652011-04-20 00:21:03 +0000650 if (ExternalSLocEntries) {
651 bool Invalid = false;
652 getSLocEntry(FileID::get(I - SLocEntryTable.begin()), &Invalid);
653 if (Invalid)
654 return FileID::get(0);
655 }
656
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000657 if (I->getOffset() <= SLocOffset) {
658#if 0
659 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
660 I-SLocEntryTable.begin(),
661 I->isInstantiation() ? "inst" : "file",
662 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
663#endif
664 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000665
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000666 // If this isn't an instantiation, remember it. We have good locality
667 // across FileID lookups.
668 if (!I->isInstantiation())
669 LastFileIDLookup = Res;
670 NumLinearScans += NumProbes+1;
671 return Res;
672 }
673 if (++NumProbes == 8)
674 break;
675 }
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000677 // Convert "I" back into an index. We know that it is an entry whose index is
678 // larger than the offset we are looking for.
679 unsigned GreaterIndex = I-SLocEntryTable.begin();
680 // LessIndex - This is the lower bound of the range that we're searching.
681 // We know that the offset corresponding to the FileID is is less than
682 // SLocOffset.
683 unsigned LessIndex = 0;
684 NumProbes = 0;
685 while (1) {
Douglas Gregore23ac652011-04-20 00:21:03 +0000686 bool Invalid = false;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000687 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregore23ac652011-04-20 00:21:03 +0000688 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex), &Invalid)
689 .getOffset();
690 if (Invalid)
691 return FileID::get(0);
692
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000693 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000695 // If the offset of the midpoint is too large, chop the high side of the
696 // range to the midpoint.
697 if (MidOffset > SLocOffset) {
698 GreaterIndex = MiddleIndex;
699 continue;
700 }
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000702 // If the middle index contains the value, succeed and return.
703 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
704#if 0
705 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
706 I-SLocEntryTable.begin(),
707 I->isInstantiation() ? "inst" : "file",
708 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
709#endif
710 FileID Res = FileID::get(MiddleIndex);
711
712 // If this isn't an instantiation, remember it. We have good locality
713 // across FileID lookups.
714 if (!I->isInstantiation())
715 LastFileIDLookup = Res;
716 NumBinaryProbes += NumProbes;
717 return Res;
718 }
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000720 // Otherwise, move the low-side up to the middle index.
721 LessIndex = MiddleIndex;
722 }
723}
724
Chris Lattneraddb7972009-01-26 20:04:19 +0000725SourceLocation SourceManager::
726getInstantiationLocSlowCase(SourceLocation Loc) const {
727 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000728 // Note: If Loc indicates an offset into a token that came from a macro
729 // expansion (e.g. the 5th character of the token) we do not want to add
730 // this offset when going to the instantiation location. The instatiation
731 // location is the macro invocation, which the offset has nothing to do
732 // with. This is unlike when we get the spelling loc, because the offset
733 // directly correspond to the token whose spelling we're inspecting.
734 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000735 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000736 } while (!Loc.isFileID());
737
738 return Loc;
739}
740
741SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
742 do {
743 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
744 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
745 Loc = Loc.getFileLocWithOffset(LocInfo.second);
746 } while (!Loc.isFileID());
747 return Loc;
748}
749
750
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000751std::pair<FileID, unsigned>
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000752SourceManager::getDecomposedInstantiationLocSlowCase(
753 const SrcMgr::SLocEntry *E) const {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000754 // If this is an instantiation record, walk through all the instantiation
755 // points.
756 FileID FID;
757 SourceLocation Loc;
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000758 unsigned Offset;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000759 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000760 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000762 FID = getFileID(Loc);
763 E = &getSLocEntry(FID);
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000764 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000765 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000767 return std::make_pair(FID, Offset);
768}
769
770std::pair<FileID, unsigned>
771SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
772 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000773 // If this is an instantiation record, walk through all the instantiation
774 // points.
775 FileID FID;
776 SourceLocation Loc;
777 do {
778 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000780 FID = getFileID(Loc);
781 E = &getSLocEntry(FID);
782 Offset += Loc.getOffset()-E->getOffset();
783 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000785 return std::make_pair(FID, Offset);
786}
787
Chris Lattner387616e2009-02-17 08:04:48 +0000788/// getImmediateSpellingLoc - Given a SourceLocation object, return the
789/// spelling location referenced by the ID. This is the first level down
790/// towards the place where the characters that make up the lexed token can be
791/// found. This should not generally be used by clients.
792SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
793 if (Loc.isFileID()) return Loc;
794 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
795 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
796 return Loc.getFileLocWithOffset(LocInfo.second);
797}
798
799
Chris Lattnere7fb4842009-02-15 20:52:18 +0000800/// getImmediateInstantiationRange - Loc is required to be an instantiation
801/// location. Return the start/end of the instantiation information.
802std::pair<SourceLocation,SourceLocation>
803SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
804 assert(Loc.isMacroID() && "Not an instantiation loc!");
805 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
806 return II.getInstantiationLocRange();
807}
808
Chris Lattner66781332009-02-15 21:26:50 +0000809/// getInstantiationRange - Given a SourceLocation object, return the
810/// range of tokens covered by the instantiation in the ultimate file.
811std::pair<SourceLocation,SourceLocation>
812SourceManager::getInstantiationRange(SourceLocation Loc) const {
813 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Chris Lattner66781332009-02-15 21:26:50 +0000815 std::pair<SourceLocation,SourceLocation> Res =
816 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Chris Lattner66781332009-02-15 21:26:50 +0000818 // Fully resolve the start and end locations to their ultimate instantiation
819 // points.
820 while (!Res.first.isFileID())
821 Res.first = getImmediateInstantiationRange(Res.first).first;
822 while (!Res.second.isFileID())
823 Res.second = getImmediateInstantiationRange(Res.second).second;
824 return Res;
825}
826
Chris Lattnere7fb4842009-02-15 20:52:18 +0000827
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000828
829//===----------------------------------------------------------------------===//
830// Queries about the code at a SourceLocation.
831//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000832
833/// getCharacterData - Return a pointer to the start of the specified location
834/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000835const char *SourceManager::getCharacterData(SourceLocation SL,
836 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 // Note that this is a hot function in the getSpelling() path, which is
838 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000839 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Ted Kremenekc16c2082009-01-06 01:55:26 +0000841 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000842 bool CharDataInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +0000843 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
844 if (CharDataInvalid || !Entry.isFile()) {
845 if (Invalid)
846 *Invalid = true;
847
848 return "<<<<INVALID BUFFER>>>>";
849 }
Douglas Gregor50f6af72010-03-16 05:20:39 +0000850 const llvm::MemoryBuffer *Buffer
Douglas Gregore23ac652011-04-20 00:21:03 +0000851 = Entry.getFile().getContentCache()
852 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000853 if (Invalid)
854 *Invalid = CharDataInvalid;
855 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000856}
857
Reid Spencer5f016e22007-07-11 17:01:13 +0000858
Chris Lattner9dc1f532007-07-20 16:37:10 +0000859/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000860/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000861unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
862 bool *Invalid) const {
863 bool MyInvalid = false;
864 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
865 if (Invalid)
866 *Invalid = MyInvalid;
867
868 if (MyInvalid)
869 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Reid Spencer5f016e22007-07-11 17:01:13 +0000871 unsigned LineStart = FilePos;
872 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
873 --LineStart;
874 return FilePos-LineStart+1;
875}
876
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000877// isInvalid - Return the result of calling loc.isInvalid(), and
878// if Invalid is not null, set its value to same.
879static bool isInvalid(SourceLocation Loc, bool *Invalid) {
880 bool MyInvalid = Loc.isInvalid();
881 if (Invalid)
882 *Invalid = MyInvalid;
883 return MyInvalid;
884}
885
Douglas Gregor50f6af72010-03-16 05:20:39 +0000886unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
887 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000888 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000889 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000890 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000891}
892
Douglas Gregor50f6af72010-03-16 05:20:39 +0000893unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
894 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000895 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000896 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000897 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000898}
899
Chandler Carruth5ef04ee2011-02-23 00:47:48 +0000900unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
901 bool *Invalid) const {
902 if (isInvalid(Loc, Invalid)) return 0;
903 return getPresumedLoc(Loc).getColumn();
904}
905
Chandler Carruth14bd9652010-10-23 08:44:57 +0000906static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnere127a0d2010-04-20 20:35:58 +0000907ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
908 llvm::BumpPtrAllocator &Alloc,
909 const SourceManager &SM, bool &Invalid);
910static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
911 llvm::BumpPtrAllocator &Alloc,
912 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000913 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000914 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
915 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000916 if (Invalid)
917 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000919 // Find the file offsets of all of the *physical* source lines. This does
920 // not look at trigraphs, escaped newlines, or anything else tricky.
Benjamin Kramere8554482011-07-06 16:43:46 +0000921 llvm::SmallVector<unsigned, 256> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000923 // Line #1 starts at char 0.
924 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000926 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
927 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
928 unsigned Offs = 0;
929 while (1) {
930 // Skip over the contents of the line.
931 // TODO: Vectorize this? This is very performance sensitive for programs
932 // with lots of diagnostics and in -E mode.
933 const unsigned char *NextBuf = (const unsigned char *)Buf;
934 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
935 ++NextBuf;
936 Offs += NextBuf-Buf;
937 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000939 if (Buf[0] == '\n' || Buf[0] == '\r') {
940 // If this is \n\r or \r\n, skip both characters.
941 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
942 ++Offs, ++Buf;
943 ++Offs, ++Buf;
944 LineOffsets.push_back(Offs);
945 } else {
946 // Otherwise, this is a null. If end of file, exit.
947 if (Buf == End) break;
948 // Otherwise, skip the null.
949 ++Offs, ++Buf;
950 }
951 }
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000953 // Copy the offsets into the FileInfo structure.
954 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000955 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000956 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
957}
Reid Spencer5f016e22007-07-11 17:01:13 +0000958
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000959/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000960/// for the position indicated. This requires building and caching a table of
961/// line offsets for the MemoryBuffer, so this is not cheap: use only when
962/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000963unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
964 bool *Invalid) const {
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +0000965 if (FID.isInvalid()) {
966 if (Invalid)
967 *Invalid = true;
968 return 1;
969 }
970
Chris Lattner2b2453a2009-01-17 06:22:33 +0000971 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000972 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000973 Content = LastLineNoContentCache;
Douglas Gregore23ac652011-04-20 00:21:03 +0000974 else {
975 bool MyInvalid = false;
976 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
977 if (MyInvalid || !Entry.isFile()) {
978 if (Invalid)
979 *Invalid = true;
980 return 1;
981 }
982
983 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
984 }
985
Reid Spencer5f016e22007-07-11 17:01:13 +0000986 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000987 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000988 if (Content->SourceLineCache == 0) {
989 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +0000990 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000991 if (Invalid)
992 *Invalid = MyInvalid;
993 if (MyInvalid)
994 return 1;
995 } else if (Invalid)
996 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000997
998 // Okay, we know we have a line number table. Do a binary search to find the
999 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001000 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001001 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001002 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Chris Lattner30fc9332009-02-04 01:06:56 +00001004 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001005
Daniel Dunbar4106d692009-05-18 17:30:52 +00001006 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +00001007 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +00001008 //
1009 // If it is worth being optimized, then in my opinion it could be more
1010 // performant, simpler, and more obviously correct by just "galloping" outward
1011 // from the queried file position. In fact, this could be incorporated into a
1012 // generic algorithm such as lower_bound_with_hint.
1013 //
1014 // If someone gives me a test case where this matters, and I will do it! - DWD
1015
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001016 // If the previous query was to the same file, we know both the file pos from
1017 // that query and the line number returned. This allows us to narrow the
1018 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +00001019 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001020 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001021 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001022 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001024 // The query is likely to be nearby the previous one. Here we check to
1025 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1026 // where big comment blocks and vertical whitespace eat up lines but
1027 // contribute no tokens.
1028 if (SourceLineCache+5 < SourceLineCacheEnd) {
1029 if (SourceLineCache[5] > QueriedFilePos)
1030 SourceLineCacheEnd = SourceLineCache+5;
1031 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1032 if (SourceLineCache[10] > QueriedFilePos)
1033 SourceLineCacheEnd = SourceLineCache+10;
1034 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1035 if (SourceLineCache[20] > QueriedFilePos)
1036 SourceLineCacheEnd = SourceLineCache+20;
1037 }
1038 }
1039 }
1040 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001041 if (LastLineNoResult < Content->NumLines)
1042 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001043 }
1044 }
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001046 // If the spread is large, do a "radix" test as our initial guess, based on
1047 // the assumption that lines average to approximately the same length.
1048 // NOTE: This is currently disabled, as it does not appear to be profitable in
1049 // initial measurements.
1050 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +00001051 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001053 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001054 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001056 // Check for -10 and +10 lines.
1057 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
1058 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
1059
1060 // If the computed lower bound is less than the query location, move it in.
1061 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
1062 SourceLineCacheStart[LowerBound] < QueriedFilePos)
1063 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001065 // If the computed upper bound is greater than the query location, move it.
1066 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
1067 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1068 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1069 }
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001071 unsigned *Pos
1072 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001073 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Chris Lattner30fc9332009-02-04 01:06:56 +00001075 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001076 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001077 LastLineNoFilePos = QueriedFilePos;
1078 LastLineNoResult = LineNo;
1079 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +00001080}
1081
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001082unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1083 bool *Invalid) const {
1084 if (isInvalid(Loc, Invalid)) return 0;
1085 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1086 return getLineNumber(LocInfo.first, LocInfo.second);
1087}
Douglas Gregor50f6af72010-03-16 05:20:39 +00001088unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
1089 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001090 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner30fc9332009-02-04 01:06:56 +00001091 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
1092 return getLineNumber(LocInfo.first, LocInfo.second);
1093}
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001094unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor50f6af72010-03-16 05:20:39 +00001095 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001096 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001097 return getPresumedLoc(Loc).getLine();
Chris Lattner30fc9332009-02-04 01:06:56 +00001098}
1099
Chris Lattner6b306672009-02-04 05:33:01 +00001100/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +00001101/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +00001102/// header, or an "implicit extern C" system header.
1103///
1104/// This state can be modified with flags on GNU linemarker directives like:
1105/// # 4 "foo.h" 3
1106/// which changes all source locations in the current file after that to be
1107/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001108SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001109SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1110 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
1111 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +00001112 bool Invalid = false;
1113 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1114 if (Invalid || !SEntry.isFile())
1115 return C_User;
1116
1117 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner6b306672009-02-04 05:33:01 +00001118
1119 // If there are no #line directives in this file, just return the whole-file
1120 // state.
1121 if (!FI.hasLineDirectives())
1122 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Chris Lattner6b306672009-02-04 05:33:01 +00001124 assert(LineTable && "Can't have linetable entries without a LineTable!");
1125 // See if there is a #line directive before the location.
1126 const LineEntry *Entry =
1127 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Chris Lattner6b306672009-02-04 05:33:01 +00001129 // If this is before the first line marker, use the file characteristic.
1130 if (!Entry)
1131 return FI.getFileCharacteristic();
1132
1133 return Entry->FileKind;
1134}
1135
Chris Lattnerbff5c512009-02-17 08:39:06 +00001136/// Return the filename or buffer identifier of the buffer the location is in.
1137/// Note that this name does not respect #line directives. Use getPresumedLoc
1138/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001139const char *SourceManager::getBufferName(SourceLocation Loc,
1140 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001141 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Douglas Gregor50f6af72010-03-16 05:20:39 +00001143 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001144}
1145
Chris Lattner30fc9332009-02-04 01:06:56 +00001146
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001147/// getPresumedLoc - This method returns the "presumed" location of a
1148/// SourceLocation specifies. A "presumed location" can be modified by #line
1149/// or GNU line marker directives. This provides a view on the data that a
1150/// user should see in diagnostics, for example.
1151///
1152/// Note that a presumed location is always given as the instantiation point
1153/// of an instantiation location, not at the spelling location.
1154PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1155 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001157 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001158 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Douglas Gregore23ac652011-04-20 00:21:03 +00001160 bool Invalid = false;
1161 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1162 if (Invalid || !Entry.isFile())
1163 return PresumedLoc();
1164
1165 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001166 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Chris Lattner3cd949c2009-02-04 01:55:42 +00001168 // To get the source name, first consult the FileEntry (if one exists)
1169 // before the MemBuffer as this will avoid unnecessarily paging in the
1170 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001171 const char *Filename;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001172 if (C->OrigEntry)
1173 Filename = C->OrigEntry->getName();
Chris Lattnere127a0d2010-04-20 20:35:58 +00001174 else
1175 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregore23ac652011-04-20 00:21:03 +00001176
Douglas Gregorc417fa02010-11-02 00:39:22 +00001177 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1178 if (Invalid)
1179 return PresumedLoc();
1180 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1181 if (Invalid)
1182 return PresumedLoc();
1183
Chris Lattner3cd949c2009-02-04 01:55:42 +00001184 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Chris Lattner3cd949c2009-02-04 01:55:42 +00001186 // If we have #line directives in this file, update and overwrite the physical
1187 // location info if appropriate.
1188 if (FI.hasLineDirectives()) {
1189 assert(LineTable && "Can't have linetable entries without a LineTable!");
1190 // See if there is a #line directive before this. If so, get it.
1191 if (const LineEntry *Entry =
1192 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001193 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001194 if (Entry->FilenameID != -1)
1195 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001196
1197 // Use the line number specified by the LineEntry. This line number may
1198 // be multiple lines down from the line entry. Add the difference in
1199 // physical line numbers from the query point and the line marker to the
1200 // total.
1201 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1202 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001204 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Chris Lattner137b6a62009-02-04 06:25:26 +00001206 // Handle virtual #include manipulation.
1207 if (Entry->IncludeOffset) {
1208 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1209 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1210 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001211 }
1212 }
1213
1214 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001215}
1216
Argyrios Kyrtzidis469244a2011-05-28 03:56:11 +00001217/// \brief Returns true if the given MacroID location points at the first
1218/// token of the macro instantiation.
1219bool SourceManager::isAtStartOfMacroInstantiation(SourceLocation loc) const {
1220 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
1221
Argyrios Kyrtzidised37ab82011-06-24 17:28:26 +00001222 std::pair<FileID, unsigned> infoLoc = getDecomposedLoc(loc);
1223 if (infoLoc.second > 0)
1224 return false; // Does not point at the start of token.
1225
1226 unsigned FID = infoLoc.first.ID;
Argyrios Kyrtzidis469244a2011-05-28 03:56:11 +00001227 assert(FID > 1);
1228 std::pair<SourceLocation, SourceLocation>
1229 instRange = getImmediateInstantiationRange(loc);
1230
1231 bool invalid = false;
1232 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID-1, &invalid);
1233 if (invalid)
1234 return false;
1235
1236 // If the FileID immediately before it is a file then this is the first token
1237 // in the macro.
1238 if (Entry.isFile())
1239 return true;
1240
1241 // If the FileID immediately before it (which is a macro token) is the
1242 // immediate instantiated macro, check this macro token's location.
1243 if (getFileID(instRange.second).ID == FID-1)
1244 return isAtStartOfMacroInstantiation(instRange.first);
1245
1246 // If the FileID immediately before it (which is a macro token) came from a
1247 // different instantiation, then this is the first token in the macro.
1248 if (getInstantiationLoc(Entry.getInstantiation().getInstantiationLocStart())
1249 != getInstantiationLoc(loc))
1250 return true;
1251
1252 // It is inside the macro or the last token in the macro.
1253 return false;
1254}
1255
1256/// \brief Returns true if the given MacroID location points at the last
1257/// token of the macro instantiation.
1258bool SourceManager::isAtEndOfMacroInstantiation(SourceLocation loc) const {
1259 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
1260
1261 unsigned FID = getFileID(loc).ID;
1262 assert(FID > 1);
1263 std::pair<SourceLocation, SourceLocation>
1264 instRange = getInstantiationRange(loc);
1265
1266 // If there's no FileID after it, it is the last token in the macro.
1267 if (FID+1 == sloc_entry_size())
1268 return true;
1269
1270 bool invalid = false;
1271 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID+1, &invalid);
1272 if (invalid)
1273 return false;
1274
1275 // If the FileID immediately after it is a file or a macro token which
1276 // came from a different instantiation, then this is the last token in the
1277 // macro.
1278 if (Entry.isFile())
1279 return true;
1280 if (getInstantiationLoc(Entry.getInstantiation().getInstantiationLocStart())
1281 != instRange.first)
1282 return true;
1283
1284 // It is inside the macro or the first token in the macro.
1285 return false;
1286}
1287
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001288//===----------------------------------------------------------------------===//
1289// Other miscellaneous methods.
1290//===----------------------------------------------------------------------===//
1291
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001292/// \brief Retrieve the inode for the given file entry, if possible.
1293///
1294/// This routine involves a system call, and therefore should only be used
1295/// in non-performance-critical code.
1296static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1297 if (!File)
1298 return llvm::Optional<ino_t>();
1299
1300 struct stat StatBuf;
1301 if (::stat(File->getName(), &StatBuf))
1302 return llvm::Optional<ino_t>();
1303
1304 return StatBuf.st_ino;
1305}
1306
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001307/// \brief Get the source location for the given file:line:col triplet.
1308///
1309/// If the source file is included multiple times, the source location will
1310/// be based upon the first inclusion.
1311SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001312 unsigned Line, unsigned Col) {
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001313 assert(SourceFile && "Null source file!");
1314 assert(Line && Col && "Line and column should start from 1!");
1315
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001316 // Find the first file ID that corresponds to the given file.
1317 FileID FirstFID;
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001319 // First, check the main file ID, since it is common to look for a
1320 // location in the main file.
1321 llvm::Optional<ino_t> SourceFileInode;
1322 llvm::Optional<llvm::StringRef> SourceFileName;
1323 if (!MainFileID.isInvalid()) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001324 bool Invalid = false;
1325 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1326 if (Invalid)
1327 return SourceLocation();
1328
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001329 if (MainSLoc.isFile()) {
1330 const ContentCache *MainContentCache
1331 = MainSLoc.getFile().getContentCache();
Douglas Gregorb7a18412011-02-11 18:08:15 +00001332 if (!MainContentCache) {
1333 // Can't do anything
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001334 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001335 FirstFID = MainFileID;
Douglas Gregorb7a18412011-02-11 18:08:15 +00001336 } else {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001337 // Fall back: check whether we have the same base name and inode
1338 // as the main file.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001339 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001340 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1341 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1342 SourceFileInode = getActualFileInode(SourceFile);
Douglas Gregor37c02bf2011-02-16 19:09:24 +00001343 if (SourceFileInode) {
1344 if (llvm::Optional<ino_t> MainFileInode
1345 = getActualFileInode(MainFile)) {
1346 if (*SourceFileInode == *MainFileInode) {
1347 FirstFID = MainFileID;
1348 SourceFile = MainFile;
1349 }
1350 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001351 }
1352 }
1353 }
1354 }
1355 }
1356
1357 if (FirstFID.isInvalid()) {
1358 // The location we're looking for isn't in the main file; look
1359 // through all of the source locations.
1360 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001361 bool Invalid = false;
1362 const SLocEntry &SLoc = getSLocEntry(I, &Invalid);
1363 if (Invalid)
1364 return SourceLocation();
1365
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001366 if (SLoc.isFile() &&
1367 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001368 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001369 FirstFID = FileID::get(I);
1370 break;
1371 }
1372 }
1373 }
1374
1375 // If we haven't found what we want yet, try again, but this time stat()
1376 // each of the files in case the files have changed since we originally
1377 // parsed the file.
1378 if (FirstFID.isInvalid() &&
1379 (SourceFileName ||
1380 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1381 (SourceFileInode ||
1382 (SourceFileInode = getActualFileInode(SourceFile)))) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001383 bool Invalid = false;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001384 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001385 const SLocEntry &SLoc = getSLocEntry(I, &Invalid);
1386 if (Invalid)
1387 return SourceLocation();
1388
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001389 if (SLoc.isFile()) {
1390 const ContentCache *FileContentCache
1391 = SLoc.getFile().getContentCache();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001392 const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001393 if (Entry &&
Douglas Gregorb7a18412011-02-11 18:08:15 +00001394 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1395 if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1396 if (*SourceFileInode == *EntryInode) {
1397 FirstFID = FileID::get(I);
1398 SourceFile = Entry;
1399 break;
1400 }
1401 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001402 }
1403 }
1404 }
1405 }
1406
1407 if (FirstFID.isInvalid())
1408 return SourceLocation();
1409
1410 if (Line == 1 && Col == 1)
1411 return getLocForStartOfFile(FirstFID);
1412
1413 ContentCache *Content
1414 = const_cast<ContentCache *>(getOrCreateContentCache(SourceFile));
1415 if (!Content)
1416 return SourceLocation();
1417
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001418 // If this is the first use of line information for this buffer, compute the
1419 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001420 if (Content->SourceLineCache == 0) {
1421 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001422 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001423 if (MyInvalid)
1424 return SourceLocation();
1425 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001426
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001427 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001428 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001429 if (Size > 0)
1430 --Size;
1431 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1432 }
1433
1434 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnere127a0d2010-04-20 20:35:58 +00001435 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1436 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001437 unsigned i = 0;
1438
1439 // Check that the given column is valid.
1440 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1441 ++i;
1442 if (i < Col-1)
1443 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1444
Douglas Gregor4a160e12009-12-02 05:34:39 +00001445 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001446}
1447
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001448/// Given a decomposed source location, move it up the include/instantiation
1449/// stack to the parent source location. If this is possible, return the
1450/// decomposed version of the parent in Loc and return false. If Loc is the
1451/// top-level entry, return true and don't modify it.
1452static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1453 const SourceManager &SM) {
1454 SourceLocation UpperLoc;
1455 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
1456 if (Entry.isInstantiation())
1457 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1458 else
1459 UpperLoc = Entry.getFile().getIncludeLoc();
1460
1461 if (UpperLoc.isInvalid())
1462 return true; // We reached the top.
1463
1464 Loc = SM.getDecomposedLoc(UpperLoc);
1465 return false;
1466}
1467
1468
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001469/// \brief Determines the order of 2 source locations in the translation unit.
1470///
1471/// \returns true if LHS source location comes before RHS, false otherwise.
1472bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1473 SourceLocation RHS) const {
1474 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1475 if (LHS == RHS)
1476 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Argyrios Kyrtzidisee933e12010-12-24 02:53:53 +00001478 // If both locations are macro instantiations, the order of their offsets
1479 // reflect the order that the tokens, pointed to by these locations, were
1480 // instantiated (during parsing each token that is instantiated by a macro,
1481 // expands the SLocEntries).
1482 if (LHS.isMacroID() && RHS.isMacroID())
1483 return LHS.getOffset() < RHS.getOffset();
1484
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001485 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1486 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001488 // If the source locations are in the same file, just compare offsets.
1489 if (LOffs.first == ROffs.first)
1490 return LOffs.second < ROffs.second;
1491
1492 // If we are comparing a source location with multiple locations in the same
1493 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00001494 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1495 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001497 // Okay, we missed in the cache, start updating the cache for this query.
1498 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001500 // "Traverse" the include/instantiation stacks of both locations and try to
Chris Lattner48296ba2010-05-07 05:51:13 +00001501 // find a common "ancestor". FileIDs build a tree-like structure that
1502 // reflects the #include hierarchy, and this algorithm needs to find the
1503 // nearest common ancestor between the two locations. For example, if you
1504 // have a.c that includes b.h and c.h, and are comparing a location in b.h to
1505 // a location in c.h, we need to find that their nearest common ancestor is
1506 // a.c, and compare the locations of the two #includes to find their relative
1507 // ordering.
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001508 //
Chris Lattner48296ba2010-05-07 05:51:13 +00001509 // SourceManager assigns FileIDs in order of parsing. This means that an
1510 // includee always has a larger FileID than an includer. While you might
1511 // think that we could just compare the FileID's here, that doesn't work to
1512 // compare a point at the end of a.c with a point within c.h. Though c.h has
1513 // a larger FileID, we have to compare the include point of c.h to the
1514 // location in a.c.
1515 //
1516 // Despite not being able to directly compare FileID's, we can tell that a
1517 // larger FileID is necessarily more deeply nested than a lower one and use
1518 // this information to walk up the tree to the nearest common ancestor.
1519 do {
1520 // If LOffs is larger than ROffs, then LOffs must be more deeply nested than
1521 // ROffs, walk up the #include chain.
1522 if (LOffs.first.ID > ROffs.first.ID) {
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001523 if (MoveUpIncludeHierarchy(LOffs, *this))
Chris Lattner48296ba2010-05-07 05:51:13 +00001524 break; // We reached the top.
1525
Chris Lattner48296ba2010-05-07 05:51:13 +00001526 } else {
1527 // Otherwise, ROffs is larger than LOffs, so ROffs must be more deeply
1528 // nested than LOffs, walk up the #include chain.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001529 if (MoveUpIncludeHierarchy(ROffs, *this))
Chris Lattner48296ba2010-05-07 05:51:13 +00001530 break; // We reached the top.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001531 }
Chris Lattner48296ba2010-05-07 05:51:13 +00001532 } while (LOffs.first != ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Chris Lattner48296ba2010-05-07 05:51:13 +00001534 // If we exited because we found a nearest common ancestor, compare the
1535 // locations within the common file and cache them.
1536 if (LOffs.first == ROffs.first) {
1537 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1538 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001539 }
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001541 // There is no common ancestor, most probably because one location is in the
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001542 // predefines buffer or an AST file.
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001543 // FIXME: We should rearrange the external interface so this simply never
1544 // happens; it can't conceptually happen. Also see PR5662.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001545 IsBeforeInTUCache.setQueryFIDs(FileID(), FileID()); // Don't try caching.
1546
1547 // Zip both entries up to the top level record.
1548 while (!MoveUpIncludeHierarchy(LOffs, *this)) /*empty*/;
1549 while (!MoveUpIncludeHierarchy(ROffs, *this)) /*empty*/;
Chris Lattner48296ba2010-05-07 05:51:13 +00001550
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001551 // If exactly one location is a memory buffer, assume it precedes the other.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001552
1553 // Strip off macro instantation locations, going up to the top-level File
1554 // SLocEntry.
1555 bool LIsMB = getFileEntryForID(LOffs.first) == 0;
1556 bool RIsMB = getFileEntryForID(ROffs.first) == 0;
Chris Lattner48296ba2010-05-07 05:51:13 +00001557 if (LIsMB != RIsMB)
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001558 return LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001560 // Otherwise, just assume FileIDs were created in order.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001561 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001562}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001563
Reid Spencer5f016e22007-07-11 17:01:13 +00001564/// PrintStats - Print statistics to stderr.
1565///
1566void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001567 llvm::errs() << "\n*** Source Manager Stats:\n";
1568 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1569 << " mem buffers mapped.\n";
Argyrios Kyrtzidisd410e742011-07-07 03:40:24 +00001570 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated ("
1571 << SLocEntryTable.capacity()*sizeof(SrcMgr::SLocEntry)
1572 << " bytes of capacity), "
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001573 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 unsigned NumLineNumsComputed = 0;
1576 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001577 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1578 NumLineNumsComputed += I->second->SourceLineCache != 0;
1579 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 }
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001582 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1583 << NumLineNumsComputed << " files with line #'s computed.\n";
1584 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1585 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001586}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001587
1588ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenekf61b8312011-04-28 20:36:42 +00001589
1590/// Return the amount of memory used by memory buffers, breaking down
1591/// by heap-backed versus mmap'ed memory.
1592SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
1593 size_t malloc_bytes = 0;
1594 size_t mmap_bytes = 0;
1595
1596 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
1597 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
1598 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
1599 case llvm::MemoryBuffer::MemoryBuffer_MMap:
1600 mmap_bytes += sized_mapped;
1601 break;
1602 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
1603 malloc_bytes += sized_mapped;
1604 break;
1605 }
1606
1607 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
1608}
1609