blob: 72c0c08e6aa84213cb3be3061ed452b520bb7220 [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
49/// getSize - Returns the size of the content encapsulated by this ContentCache.
50/// This can be the size of the source file or the size of an arbitrary
51/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +000052/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000053unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000054 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000055 : (unsigned) ContentsEntry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000056}
57
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000058void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
59 bool DoNotFree) {
Douglas Gregorc8151082010-03-16 22:53:51 +000060 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000061
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000062 if (shouldFreeBuffer())
63 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000064 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000065 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000066}
67
Douglas Gregor36c35ba2010-03-16 00:35:39 +000068const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner5c5db4e2010-04-20 20:49:23 +000069 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000070 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000071 bool *Invalid) const {
Chris Lattnerb088cd32010-11-23 08:50:03 +000072 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000073 // computed it, just return what we have.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000074 if (Buffer.getPointer() || ContentsEntry == 0) {
Chris Lattnerb088cd32010-11-23 08:50:03 +000075 if (Invalid)
76 *Invalid = isBufferInvalid();
Chris Lattner38caec42010-04-20 18:14:03 +000077
Chris Lattnerb088cd32010-11-23 08:50:03 +000078 return Buffer.getPointer();
79 }
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000080
Chris Lattnerb088cd32010-11-23 08:50:03 +000081 std::string ErrorStr;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000082 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
Chris Lattnerb088cd32010-11-23 08:50:03 +000083
84 // If we were unable to open the file, then we are in an inconsistent
85 // situation where the content cache referenced a file which no longer
86 // exists. Most likely, we were using a stat cache with an invalid entry but
87 // the file could also have been removed during processing. Since we can't
88 // really deal with this situation, just create an empty buffer.
89 //
90 // FIXME: This is definitely not ideal, but our immediate clients can't
91 // currently handle returning a null entry here. Ideally we should detect
92 // that we are in an inconsistent situation and error out as quickly as
93 // possible.
94 if (!Buffer.getPointer()) {
95 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000096 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattnerb088cd32010-11-23 08:50:03 +000097 "<invalid>"));
98 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000099 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000100 Ptr[i] = FillStr[i % FillStr.size()];
101
102 if (Diag.isDiagnosticInFlight())
103 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000104 ContentsEntry->getName(), ErrorStr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000105 else
106 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000107 << ContentsEntry->getName() << ErrorStr;
Chris Lattnerb088cd32010-11-23 08:50:03 +0000108
109 Buffer.setInt(Buffer.getInt() | InvalidFlag);
110
111 if (Invalid) *Invalid = true;
112 return Buffer.getPointer();
113 }
114
115 // Check that the file's size is the same as in the file entry (which may
116 // have come from a stat cache).
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000117 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000118 if (Diag.isDiagnosticInFlight())
119 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000120 ContentsEntry->getName());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000121 else
122 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000123 << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000124
125 Buffer.setInt(Buffer.getInt() | InvalidFlag);
126 if (Invalid) *Invalid = true;
127 return Buffer.getPointer();
128 }
Eric Christopher156119d2011-04-09 00:01:04 +0000129
Chris Lattnerb088cd32010-11-23 08:50:03 +0000130 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher156119d2011-04-09 00:01:04 +0000131 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattnerb088cd32010-11-23 08:50:03 +0000132 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
133 llvm::StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher156119d2011-04-09 00:01:04 +0000134 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000135 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
136 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
137 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
138 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
139 .StartsWith("\x2B\x2F\x76", "UTF-7")
140 .StartsWith("\xF7\x64\x4C", "UTF-1")
141 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
142 .StartsWith("\x0E\xFE\xFF", "SDSU")
143 .StartsWith("\xFB\xEE\x28", "BOCU-1")
144 .StartsWith("\x84\x31\x95\x33", "GB-18030")
145 .Default(0);
146
Eric Christopher156119d2011-04-09 00:01:04 +0000147 if (InvalidBOM) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000148 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher156119d2011-04-09 00:01:04 +0000149 << InvalidBOM << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000150 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000151 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000152
Douglas Gregorc8151082010-03-16 22:53:51 +0000153 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000154 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000155
156 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000157}
158
Chris Lattner5b9a5042009-01-26 07:57:50 +0000159unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
160 // Look up the filename in the string table, returning the pre-existing value
161 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000162 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000163 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
164 if (Entry.getValue() != ~0U)
165 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Chris Lattner5b9a5042009-01-26 07:57:50 +0000167 // Otherwise, assign this the next available ID.
168 Entry.setValue(FilenamesByID.size());
169 FilenamesByID.push_back(&Entry);
170 return FilenamesByID.size()-1;
171}
172
Chris Lattnerac50e342009-02-03 22:13:05 +0000173/// AddLineNote - Add a line note to the line table that indicates that there
174/// is a #line at the specified FID/Offset location which changes the presumed
175/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000176void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000177 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000178 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattner23b5dc62009-02-04 00:40:31 +0000180 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
181 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Chris Lattner9d79eba2009-02-04 05:21:58 +0000183 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000184 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattner9d79eba2009-02-04 05:21:58 +0000186 if (!Entries.empty()) {
187 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
188 // that we are still in "foo.h".
189 if (FilenameID == -1)
190 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Chris Lattner137b6a62009-02-04 06:25:26 +0000192 // If we are after a line marker that switched us to system header mode, or
193 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000194 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000195 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000196 }
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattner137b6a62009-02-04 06:25:26 +0000198 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
199 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000200}
201
Chris Lattner9d79eba2009-02-04 05:21:58 +0000202/// AddLineNote This is the same as the previous version of AddLineNote, but is
203/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
204/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
205/// this is a file exit. FileKind specifies whether this is a system header or
206/// extern C system header.
207void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
208 unsigned LineNo, int FilenameID,
209 unsigned EntryExit,
210 SrcMgr::CharacteristicKind FileKind) {
211 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Chris Lattner9d79eba2009-02-04 05:21:58 +0000213 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Chris Lattner9d79eba2009-02-04 05:21:58 +0000215 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
216 "Adding line entries out of order!");
217
Chris Lattner137b6a62009-02-04 06:25:26 +0000218 unsigned IncludeOffset = 0;
219 if (EntryExit == 0) { // No #include stack change.
220 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
221 } else if (EntryExit == 1) {
222 IncludeOffset = Offset-1;
223 } else if (EntryExit == 2) {
224 assert(!Entries.empty() && Entries.back().IncludeOffset &&
225 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Chris Lattner137b6a62009-02-04 06:25:26 +0000227 // Get the include loc of the last entries' include loc as our include loc.
228 IncludeOffset = 0;
229 if (const LineEntry *PrevEntry =
230 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
231 IncludeOffset = PrevEntry->IncludeOffset;
232 }
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Chris Lattner137b6a62009-02-04 06:25:26 +0000234 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
235 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000236}
237
238
Chris Lattner3cd949c2009-02-04 01:55:42 +0000239/// FindNearestLineEntry - Find the line entry nearest to FID that is before
240/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000241const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000242 unsigned Offset) {
243 const std::vector<LineEntry> &Entries = LineEntries[FID];
244 assert(!Entries.empty() && "No #line entries for this FID after all!");
245
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000246 // It is very common for the query to be after the last #line, check this
247 // first.
248 if (Entries.back().FileOffset <= Offset)
249 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000250
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000251 // Do a binary search to find the maximal element that is still before Offset.
252 std::vector<LineEntry>::const_iterator I =
253 std::upper_bound(Entries.begin(), Entries.end(), Offset);
254 if (I == Entries.begin()) return 0;
255 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000256}
Chris Lattnerac50e342009-02-03 22:13:05 +0000257
Douglas Gregorbd945002009-04-13 16:31:14 +0000258/// \brief Add a new line entry that has already been encoded into
259/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000260void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000261 const std::vector<LineEntry> &Entries) {
262 LineEntries[FID] = Entries;
263}
Chris Lattnerac50e342009-02-03 22:13:05 +0000264
Chris Lattner5b9a5042009-01-26 07:57:50 +0000265/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000266///
Chris Lattner5b9a5042009-01-26 07:57:50 +0000267unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
268 if (LineTable == 0)
269 LineTable = new LineTableInfo();
270 return LineTable->getLineTableFilenameID(Ptr, Len);
271}
272
273
Chris Lattner4c4ea172009-02-03 21:52:55 +0000274/// AddLineNote - Add a line note to the line table for the FileID and offset
275/// specified by Loc. If FilenameID is -1, it is considered to be
276/// unspecified.
277void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
278 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000279 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Douglas Gregore23ac652011-04-20 00:21:03 +0000281 bool Invalid = false;
282 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
283 if (!Entry.isFile() || Invalid)
284 return;
285
286 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattnerac50e342009-02-03 22:13:05 +0000287
288 // Remember that this file has #line directives now if it doesn't already.
289 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Chris Lattnerac50e342009-02-03 22:13:05 +0000291 if (LineTable == 0)
292 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000293 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000294}
295
Chris Lattner9d79eba2009-02-04 05:21:58 +0000296/// AddLineNote - Add a GNU line marker to the line table.
297void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
298 int FilenameID, bool IsFileEntry,
299 bool IsFileExit, bool IsSystemHeader,
300 bool IsExternCHeader) {
301 // If there is no filename and no flags, this is treated just like a #line,
302 // which does not change the flags of the previous line marker.
303 if (FilenameID == -1) {
304 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
305 "Can't set flags without setting the filename!");
306 return AddLineNote(Loc, LineNo, FilenameID);
307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattner9d79eba2009-02-04 05:21:58 +0000309 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +0000310
311 bool Invalid = false;
312 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
313 if (!Entry.isFile() || Invalid)
314 return;
315
316 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Chris Lattner9d79eba2009-02-04 05:21:58 +0000318 // Remember that this file has #line directives now if it doesn't already.
319 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattner9d79eba2009-02-04 05:21:58 +0000321 if (LineTable == 0)
322 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chris Lattner9d79eba2009-02-04 05:21:58 +0000324 SrcMgr::CharacteristicKind FileKind;
325 if (IsExternCHeader)
326 FileKind = SrcMgr::C_ExternCSystem;
327 else if (IsSystemHeader)
328 FileKind = SrcMgr::C_System;
329 else
330 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattner9d79eba2009-02-04 05:21:58 +0000332 unsigned EntryExit = 0;
333 if (IsFileEntry)
334 EntryExit = 1;
335 else if (IsFileExit)
336 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Chris Lattner9d79eba2009-02-04 05:21:58 +0000338 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
339 EntryExit, FileKind);
340}
341
Douglas Gregorbd945002009-04-13 16:31:14 +0000342LineTableInfo &SourceManager::getLineTable() {
343 if (LineTable == 0)
344 LineTable = new LineTableInfo();
345 return *LineTable;
346}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000347
Chris Lattner23b5dc62009-02-04 00:40:31 +0000348//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000349// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000350//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000351
Chris Lattner39b49bc2010-11-23 08:35:12 +0000352SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000353 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000354 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
Douglas Gregore23ac652011-04-20 00:21:03 +0000355 NumBinaryProbes(0), FakeBufferForRecovery(0) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000356 clearIDTables();
357 Diag.setSourceManager(this);
358}
359
Chris Lattner5b9a5042009-01-26 07:57:50 +0000360SourceManager::~SourceManager() {
361 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000363 // Delete FileEntry objects corresponding to content caches. Since the actual
364 // content cache objects are bump pointer allocated, we just have to run the
365 // dtors, but we call the deallocate method for completeness.
366 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
367 MemBufferInfos[i]->~ContentCache();
368 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
369 }
370 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
371 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
372 I->second->~ContentCache();
373 ContentCacheAlloc.Deallocate(I->second);
374 }
Douglas Gregore23ac652011-04-20 00:21:03 +0000375
376 delete FakeBufferForRecovery;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000377}
378
379void SourceManager::clearIDTables() {
380 MainFileID = FileID();
381 SLocEntryTable.clear();
382 LastLineNoFileIDQuery = FileID();
383 LastLineNoContentCache = 0;
384 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Chris Lattner5b9a5042009-01-26 07:57:50 +0000386 if (LineTable)
387 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Chris Lattner5b9a5042009-01-26 07:57:50 +0000389 // Use up FileID #0 as an invalid instantiation.
390 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000391 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000392}
393
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000394/// getOrCreateContentCache - Create or return a cached ContentCache for the
395/// specified file.
396const ContentCache *
397SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000401 ContentCache *&Entry = FileInfos[FileEnt];
402 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Chris Lattner00282d62009-02-03 07:41:46 +0000404 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
405 // so that FileInfo can use the low 3 bits of the pointer for its own
406 // nefarious purposes.
407 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
408 EntryAlign = std::max(8U, EntryAlign);
409 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000410
411 // If the file contents are overridden with contents from another file,
412 // pass that file to ContentCache.
413 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
414 overI = OverriddenFiles.find(FileEnt);
415 if (overI == OverriddenFiles.end())
416 new (Entry) ContentCache(FileEnt);
417 else
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000418 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
419 : overI->second,
420 overI->second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000421
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000422 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000423}
424
425
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000426/// createMemBufferContentCache - Create a new ContentCache for the specified
427/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000428const ContentCache*
429SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000430 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
431 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
432 // the pointer for its own nefarious purposes.
433 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
434 EntryAlign = std::max(8U, EntryAlign);
435 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000436 new (Entry) ContentCache();
437 MemBufferInfos.push_back(Entry);
438 Entry->setBuffer(Buffer);
439 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000440}
441
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000442void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
443 unsigned NumSLocEntries,
444 unsigned NextOffset) {
445 ExternalSLocEntries = Source;
446 this->NextOffset = NextOffset;
Sebastian Redlb86238d2010-07-28 21:07:02 +0000447 unsigned CurPrealloc = SLocEntryLoaded.size();
448 // If we've ever preallocated, we must not count the dummy entry.
449 if (CurPrealloc) --CurPrealloc;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000450 SLocEntryLoaded.resize(NumSLocEntries + 1);
451 SLocEntryLoaded[0] = true;
Sebastian Redlb86238d2010-07-28 21:07:02 +0000452 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries - CurPrealloc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000453}
454
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000455void SourceManager::ClearPreallocatedSLocEntries() {
456 unsigned I = 0;
457 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
458 if (!SLocEntryLoaded[I])
459 break;
460
461 // We've already loaded all preallocated source location entries.
462 if (I == SLocEntryLoaded.size())
463 return;
464
465 // Remove everything from location I onward.
466 SLocEntryTable.resize(I);
467 SLocEntryLoaded.clear();
468 ExternalSLocEntries = 0;
469}
470
Douglas Gregore23ac652011-04-20 00:21:03 +0000471/// \brief As part of recovering from missing or changed content, produce a
472/// fake, non-empty buffer.
473const llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
474 if (!FakeBufferForRecovery)
475 FakeBufferForRecovery
476 = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
477
478 return FakeBufferForRecovery;
479}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000480
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000481//===----------------------------------------------------------------------===//
482// Methods to create new FileID's and instantiations.
483//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000484
Dan Gohman3f86b782010-08-26 21:27:06 +0000485/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000486/// include position. This works regardless of whether the ContentCache
487/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000488FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000489 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000490 SrcMgr::CharacteristicKind FileCharacter,
491 unsigned PreallocatedID,
492 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000493 if (PreallocatedID) {
494 // If we're filling in a preallocated ID, just load in the file
495 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000496 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000497 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000498 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000499 "Source location entry already loaded");
500 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000501 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000502 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
503 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000504 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor5de65722010-03-19 06:12:06 +0000505 return FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000506 }
507
Mike Stump1eb44332009-09-09 15:08:12 +0000508 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000509 FileInfo::get(IncludePos, File,
510 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000511 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000512 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
513 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000515 // Set LastFileIDLookup to the newly created file. The next getFileID call is
516 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000517 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000518 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000519}
520
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000521/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000522/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000523/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000524SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000525 SourceLocation ILocStart,
526 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000527 unsigned TokLength,
528 unsigned PreallocatedID,
529 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000530 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000531 if (PreallocatedID) {
532 // If we're filling in a preallocated ID, just load in the
533 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000534 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000535 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000536 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000537 "Source location entry already loaded");
538 assert(Offset && "Preallocate source location cannot have zero offset");
539 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
540 SLocEntryLoaded[PreallocatedID] = true;
541 return SourceLocation::getMacroLoc(Offset);
542 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000543 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000544 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
545 NextOffset += TokLength+1;
546 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000547}
548
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000549const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000550SourceManager::getMemoryBufferForFile(const FileEntry *File,
551 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000552 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000553 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000554 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000555}
556
Dan Gohman0d06e992010-10-26 20:47:28 +0000557void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000558 const llvm::MemoryBuffer *Buffer,
559 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000560 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000561 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000562
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000563 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor29684422009-12-02 06:49:09 +0000564}
565
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000566void SourceManager::overrideFileContents(const FileEntry *SourceFile,
567 const FileEntry *NewFile) {
568 assert(SourceFile->getSize() == NewFile->getSize() &&
569 "Different sizes, use the FileManager to create a virtual file with "
570 "the correct size");
571 assert(FileInfos.count(SourceFile) == 0 &&
572 "This function should be called at the initialization stage, before "
573 "any parsing occurs.");
574 OverriddenFiles[SourceFile] = NewFile;
575}
576
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000577llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000578 bool MyInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +0000579 const SLocEntry &SLoc = getSLocEntry(FID.ID, &MyInvalid);
580 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor3de84242011-01-31 22:42:36 +0000581 if (Invalid)
582 *Invalid = true;
583 return "<<<<<INVALID SOURCE LOCATION>>>>>";
584 }
585
586 const llvm::MemoryBuffer *Buf
587 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
588 &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000589 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000590 *Invalid = MyInvalid;
591
592 if (MyInvalid)
Douglas Gregor3de84242011-01-31 22:42:36 +0000593 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000594
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000595 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000596}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000597
Chris Lattner23b5dc62009-02-04 00:40:31 +0000598//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000599// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000600//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000601
602/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
603/// method that is used for all SourceManager queries that start with a
604/// SourceLocation object. It is responsible for finding the entry in
605/// SLocEntryTable which contains the specified location.
606///
607FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregore23ac652011-04-20 00:21:03 +0000608 if (!SLocOffset)
609 return FileID::get(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000611 // After the first and second level caches, I see two common sorts of
612 // behavior: 1) a lot of searched FileID's are "near" the cached file location
613 // or are "near" the cached instantiation location. 2) others are just
614 // completely random and may be a very long way away.
615 //
616 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
617 // then we fall back to a less cache efficient, but more scalable, binary
618 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000620 // See if this is near the file point - worst case we start scanning from the
621 // most newly created FileID.
622 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000624 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
625 // Neither loc prunes our search.
626 I = SLocEntryTable.end();
627 } else {
628 // Perhaps it is near the file point.
629 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
630 }
631
632 // Find the FileID that contains this. "I" is an iterator that points to a
633 // FileID whose offset is known to be larger than SLocOffset.
634 unsigned NumProbes = 0;
635 while (1) {
636 --I;
Douglas Gregore23ac652011-04-20 00:21:03 +0000637 if (ExternalSLocEntries) {
638 bool Invalid = false;
639 getSLocEntry(FileID::get(I - SLocEntryTable.begin()), &Invalid);
640 if (Invalid)
641 return FileID::get(0);
642 }
643
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000644 if (I->getOffset() <= SLocOffset) {
645#if 0
646 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
647 I-SLocEntryTable.begin(),
648 I->isInstantiation() ? "inst" : "file",
649 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
650#endif
651 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000652
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000653 // If this isn't an instantiation, remember it. We have good locality
654 // across FileID lookups.
655 if (!I->isInstantiation())
656 LastFileIDLookup = Res;
657 NumLinearScans += NumProbes+1;
658 return Res;
659 }
660 if (++NumProbes == 8)
661 break;
662 }
Mike Stump1eb44332009-09-09 15:08:12 +0000663
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000664 // Convert "I" back into an index. We know that it is an entry whose index is
665 // larger than the offset we are looking for.
666 unsigned GreaterIndex = I-SLocEntryTable.begin();
667 // LessIndex - This is the lower bound of the range that we're searching.
668 // We know that the offset corresponding to the FileID is is less than
669 // SLocOffset.
670 unsigned LessIndex = 0;
671 NumProbes = 0;
672 while (1) {
Douglas Gregore23ac652011-04-20 00:21:03 +0000673 bool Invalid = false;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000674 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregore23ac652011-04-20 00:21:03 +0000675 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex), &Invalid)
676 .getOffset();
677 if (Invalid)
678 return FileID::get(0);
679
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000680 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000681
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000682 // If the offset of the midpoint is too large, chop the high side of the
683 // range to the midpoint.
684 if (MidOffset > SLocOffset) {
685 GreaterIndex = MiddleIndex;
686 continue;
687 }
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000689 // If the middle index contains the value, succeed and return.
690 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
691#if 0
692 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
693 I-SLocEntryTable.begin(),
694 I->isInstantiation() ? "inst" : "file",
695 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
696#endif
697 FileID Res = FileID::get(MiddleIndex);
698
699 // If this isn't an instantiation, remember it. We have good locality
700 // across FileID lookups.
701 if (!I->isInstantiation())
702 LastFileIDLookup = Res;
703 NumBinaryProbes += NumProbes;
704 return Res;
705 }
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000707 // Otherwise, move the low-side up to the middle index.
708 LessIndex = MiddleIndex;
709 }
710}
711
Chris Lattneraddb7972009-01-26 20:04:19 +0000712SourceLocation SourceManager::
713getInstantiationLocSlowCase(SourceLocation Loc) const {
714 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000715 // Note: If Loc indicates an offset into a token that came from a macro
716 // expansion (e.g. the 5th character of the token) we do not want to add
717 // this offset when going to the instantiation location. The instatiation
718 // location is the macro invocation, which the offset has nothing to do
719 // with. This is unlike when we get the spelling loc, because the offset
720 // directly correspond to the token whose spelling we're inspecting.
721 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000722 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000723 } while (!Loc.isFileID());
724
725 return Loc;
726}
727
728SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
729 do {
730 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
731 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
732 Loc = Loc.getFileLocWithOffset(LocInfo.second);
733 } while (!Loc.isFileID());
734 return Loc;
735}
736
737
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000738std::pair<FileID, unsigned>
739SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
740 unsigned Offset) const {
741 // If this is an instantiation record, walk through all the instantiation
742 // points.
743 FileID FID;
744 SourceLocation Loc;
745 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000746 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000748 FID = getFileID(Loc);
749 E = &getSLocEntry(FID);
750 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000751 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000753 return std::make_pair(FID, Offset);
754}
755
756std::pair<FileID, unsigned>
757SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
758 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000759 // If this is an instantiation record, walk through all the instantiation
760 // points.
761 FileID FID;
762 SourceLocation Loc;
763 do {
764 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000766 FID = getFileID(Loc);
767 E = &getSLocEntry(FID);
768 Offset += Loc.getOffset()-E->getOffset();
769 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000771 return std::make_pair(FID, Offset);
772}
773
Chris Lattner387616e2009-02-17 08:04:48 +0000774/// getImmediateSpellingLoc - Given a SourceLocation object, return the
775/// spelling location referenced by the ID. This is the first level down
776/// towards the place where the characters that make up the lexed token can be
777/// found. This should not generally be used by clients.
778SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
779 if (Loc.isFileID()) return Loc;
780 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
781 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
782 return Loc.getFileLocWithOffset(LocInfo.second);
783}
784
785
Chris Lattnere7fb4842009-02-15 20:52:18 +0000786/// getImmediateInstantiationRange - Loc is required to be an instantiation
787/// location. Return the start/end of the instantiation information.
788std::pair<SourceLocation,SourceLocation>
789SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
790 assert(Loc.isMacroID() && "Not an instantiation loc!");
791 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
792 return II.getInstantiationLocRange();
793}
794
Chris Lattner66781332009-02-15 21:26:50 +0000795/// getInstantiationRange - Given a SourceLocation object, return the
796/// range of tokens covered by the instantiation in the ultimate file.
797std::pair<SourceLocation,SourceLocation>
798SourceManager::getInstantiationRange(SourceLocation Loc) const {
799 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Chris Lattner66781332009-02-15 21:26:50 +0000801 std::pair<SourceLocation,SourceLocation> Res =
802 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Chris Lattner66781332009-02-15 21:26:50 +0000804 // Fully resolve the start and end locations to their ultimate instantiation
805 // points.
806 while (!Res.first.isFileID())
807 Res.first = getImmediateInstantiationRange(Res.first).first;
808 while (!Res.second.isFileID())
809 Res.second = getImmediateInstantiationRange(Res.second).second;
810 return Res;
811}
812
Chris Lattnere7fb4842009-02-15 20:52:18 +0000813
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000814
815//===----------------------------------------------------------------------===//
816// Queries about the code at a SourceLocation.
817//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000818
819/// getCharacterData - Return a pointer to the start of the specified location
820/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000821const char *SourceManager::getCharacterData(SourceLocation SL,
822 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000823 // Note that this is a hot function in the getSpelling() path, which is
824 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000825 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Ted Kremenekc16c2082009-01-06 01:55:26 +0000827 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000828 bool CharDataInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +0000829 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
830 if (CharDataInvalid || !Entry.isFile()) {
831 if (Invalid)
832 *Invalid = true;
833
834 return "<<<<INVALID BUFFER>>>>";
835 }
Douglas Gregor50f6af72010-03-16 05:20:39 +0000836 const llvm::MemoryBuffer *Buffer
Douglas Gregore23ac652011-04-20 00:21:03 +0000837 = Entry.getFile().getContentCache()
838 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000839 if (Invalid)
840 *Invalid = CharDataInvalid;
841 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000842}
843
Reid Spencer5f016e22007-07-11 17:01:13 +0000844
Chris Lattner9dc1f532007-07-20 16:37:10 +0000845/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000846/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000847unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
848 bool *Invalid) const {
849 bool MyInvalid = false;
850 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
851 if (Invalid)
852 *Invalid = MyInvalid;
853
854 if (MyInvalid)
855 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 unsigned LineStart = FilePos;
858 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
859 --LineStart;
860 return FilePos-LineStart+1;
861}
862
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000863// isInvalid - Return the result of calling loc.isInvalid(), and
864// if Invalid is not null, set its value to same.
865static bool isInvalid(SourceLocation Loc, bool *Invalid) {
866 bool MyInvalid = Loc.isInvalid();
867 if (Invalid)
868 *Invalid = MyInvalid;
869 return MyInvalid;
870}
871
Douglas Gregor50f6af72010-03-16 05:20:39 +0000872unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
873 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000874 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000875 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000876 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000877}
878
Douglas Gregor50f6af72010-03-16 05:20:39 +0000879unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
880 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000881 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000882 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000883 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000884}
885
Chandler Carruth5ef04ee2011-02-23 00:47:48 +0000886unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
887 bool *Invalid) const {
888 if (isInvalid(Loc, Invalid)) return 0;
889 return getPresumedLoc(Loc).getColumn();
890}
891
Chandler Carruth14bd9652010-10-23 08:44:57 +0000892static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnere127a0d2010-04-20 20:35:58 +0000893ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
894 llvm::BumpPtrAllocator &Alloc,
895 const SourceManager &SM, bool &Invalid);
896static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
897 llvm::BumpPtrAllocator &Alloc,
898 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000899 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000900 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
901 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000902 if (Invalid)
903 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000905 // Find the file offsets of all of the *physical* source lines. This does
906 // not look at trigraphs, escaped newlines, or anything else tricky.
907 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000909 // Line #1 starts at char 0.
910 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000912 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
913 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
914 unsigned Offs = 0;
915 while (1) {
916 // Skip over the contents of the line.
917 // TODO: Vectorize this? This is very performance sensitive for programs
918 // with lots of diagnostics and in -E mode.
919 const unsigned char *NextBuf = (const unsigned char *)Buf;
920 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
921 ++NextBuf;
922 Offs += NextBuf-Buf;
923 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000925 if (Buf[0] == '\n' || Buf[0] == '\r') {
926 // If this is \n\r or \r\n, skip both characters.
927 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
928 ++Offs, ++Buf;
929 ++Offs, ++Buf;
930 LineOffsets.push_back(Offs);
931 } else {
932 // Otherwise, this is a null. If end of file, exit.
933 if (Buf == End) break;
934 // Otherwise, skip the null.
935 ++Offs, ++Buf;
936 }
937 }
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000939 // Copy the offsets into the FileInfo structure.
940 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000941 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000942 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
943}
Reid Spencer5f016e22007-07-11 17:01:13 +0000944
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000945/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000946/// for the position indicated. This requires building and caching a table of
947/// line offsets for the MemoryBuffer, so this is not cheap: use only when
948/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000949unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
950 bool *Invalid) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000951 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000952 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000953 Content = LastLineNoContentCache;
Douglas Gregore23ac652011-04-20 00:21:03 +0000954 else {
955 bool MyInvalid = false;
956 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
957 if (MyInvalid || !Entry.isFile()) {
958 if (Invalid)
959 *Invalid = true;
960 return 1;
961 }
962
963 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
964 }
965
Reid Spencer5f016e22007-07-11 17:01:13 +0000966 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000967 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000968 if (Content->SourceLineCache == 0) {
969 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +0000970 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000971 if (Invalid)
972 *Invalid = MyInvalid;
973 if (MyInvalid)
974 return 1;
975 } else if (Invalid)
976 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000977
978 // Okay, we know we have a line number table. Do a binary search to find the
979 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000980 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000981 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000982 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Chris Lattner30fc9332009-02-04 01:06:56 +0000984 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000985
Daniel Dunbar4106d692009-05-18 17:30:52 +0000986 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000987 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000988 //
989 // If it is worth being optimized, then in my opinion it could be more
990 // performant, simpler, and more obviously correct by just "galloping" outward
991 // from the queried file position. In fact, this could be incorporated into a
992 // generic algorithm such as lower_bound_with_hint.
993 //
994 // If someone gives me a test case where this matters, and I will do it! - DWD
995
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000996 // If the previous query was to the same file, we know both the file pos from
997 // that query and the line number returned. This allows us to narrow the
998 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000999 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001000 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001001 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001002 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001004 // The query is likely to be nearby the previous one. Here we check to
1005 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1006 // where big comment blocks and vertical whitespace eat up lines but
1007 // contribute no tokens.
1008 if (SourceLineCache+5 < SourceLineCacheEnd) {
1009 if (SourceLineCache[5] > QueriedFilePos)
1010 SourceLineCacheEnd = SourceLineCache+5;
1011 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1012 if (SourceLineCache[10] > QueriedFilePos)
1013 SourceLineCacheEnd = SourceLineCache+10;
1014 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1015 if (SourceLineCache[20] > QueriedFilePos)
1016 SourceLineCacheEnd = SourceLineCache+20;
1017 }
1018 }
1019 }
1020 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001021 if (LastLineNoResult < Content->NumLines)
1022 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001023 }
1024 }
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001026 // If the spread is large, do a "radix" test as our initial guess, based on
1027 // the assumption that lines average to approximately the same length.
1028 // NOTE: This is currently disabled, as it does not appear to be profitable in
1029 // initial measurements.
1030 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +00001031 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001033 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001034 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001036 // Check for -10 and +10 lines.
1037 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
1038 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
1039
1040 // If the computed lower bound is less than the query location, move it in.
1041 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
1042 SourceLineCacheStart[LowerBound] < QueriedFilePos)
1043 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001045 // If the computed upper bound is greater than the query location, move it.
1046 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
1047 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1048 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1049 }
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001051 unsigned *Pos
1052 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001053 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Chris Lattner30fc9332009-02-04 01:06:56 +00001055 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001056 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001057 LastLineNoFilePos = QueriedFilePos;
1058 LastLineNoResult = LineNo;
1059 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +00001060}
1061
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001062unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1063 bool *Invalid) const {
1064 if (isInvalid(Loc, Invalid)) return 0;
1065 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1066 return getLineNumber(LocInfo.first, LocInfo.second);
1067}
Douglas Gregor50f6af72010-03-16 05:20:39 +00001068unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
1069 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001070 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner30fc9332009-02-04 01:06:56 +00001071 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
1072 return getLineNumber(LocInfo.first, LocInfo.second);
1073}
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001074unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor50f6af72010-03-16 05:20:39 +00001075 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001076 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001077 return getPresumedLoc(Loc).getLine();
Chris Lattner30fc9332009-02-04 01:06:56 +00001078}
1079
Chris Lattner6b306672009-02-04 05:33:01 +00001080/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +00001081/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +00001082/// header, or an "implicit extern C" system header.
1083///
1084/// This state can be modified with flags on GNU linemarker directives like:
1085/// # 4 "foo.h" 3
1086/// which changes all source locations in the current file after that to be
1087/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001088SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001089SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1090 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
1091 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +00001092 bool Invalid = false;
1093 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1094 if (Invalid || !SEntry.isFile())
1095 return C_User;
1096
1097 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner6b306672009-02-04 05:33:01 +00001098
1099 // If there are no #line directives in this file, just return the whole-file
1100 // state.
1101 if (!FI.hasLineDirectives())
1102 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Chris Lattner6b306672009-02-04 05:33:01 +00001104 assert(LineTable && "Can't have linetable entries without a LineTable!");
1105 // See if there is a #line directive before the location.
1106 const LineEntry *Entry =
1107 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Chris Lattner6b306672009-02-04 05:33:01 +00001109 // If this is before the first line marker, use the file characteristic.
1110 if (!Entry)
1111 return FI.getFileCharacteristic();
1112
1113 return Entry->FileKind;
1114}
1115
Chris Lattnerbff5c512009-02-17 08:39:06 +00001116/// Return the filename or buffer identifier of the buffer the location is in.
1117/// Note that this name does not respect #line directives. Use getPresumedLoc
1118/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001119const char *SourceManager::getBufferName(SourceLocation Loc,
1120 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001121 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Douglas Gregor50f6af72010-03-16 05:20:39 +00001123 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001124}
1125
Chris Lattner30fc9332009-02-04 01:06:56 +00001126
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001127/// getPresumedLoc - This method returns the "presumed" location of a
1128/// SourceLocation specifies. A "presumed location" can be modified by #line
1129/// or GNU line marker directives. This provides a view on the data that a
1130/// user should see in diagnostics, for example.
1131///
1132/// Note that a presumed location is always given as the instantiation point
1133/// of an instantiation location, not at the spelling location.
1134PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1135 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001137 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001138 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Douglas Gregore23ac652011-04-20 00:21:03 +00001140 bool Invalid = false;
1141 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1142 if (Invalid || !Entry.isFile())
1143 return PresumedLoc();
1144
1145 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001146 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Chris Lattner3cd949c2009-02-04 01:55:42 +00001148 // To get the source name, first consult the FileEntry (if one exists)
1149 // before the MemBuffer as this will avoid unnecessarily paging in the
1150 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001151 const char *Filename;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001152 if (C->OrigEntry)
1153 Filename = C->OrigEntry->getName();
Chris Lattnere127a0d2010-04-20 20:35:58 +00001154 else
1155 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregore23ac652011-04-20 00:21:03 +00001156
Douglas Gregorc417fa02010-11-02 00:39:22 +00001157 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1158 if (Invalid)
1159 return PresumedLoc();
1160 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1161 if (Invalid)
1162 return PresumedLoc();
1163
Chris Lattner3cd949c2009-02-04 01:55:42 +00001164 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Chris Lattner3cd949c2009-02-04 01:55:42 +00001166 // If we have #line directives in this file, update and overwrite the physical
1167 // location info if appropriate.
1168 if (FI.hasLineDirectives()) {
1169 assert(LineTable && "Can't have linetable entries without a LineTable!");
1170 // See if there is a #line directive before this. If so, get it.
1171 if (const LineEntry *Entry =
1172 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001173 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001174 if (Entry->FilenameID != -1)
1175 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001176
1177 // Use the line number specified by the LineEntry. This line number may
1178 // be multiple lines down from the line entry. Add the difference in
1179 // physical line numbers from the query point and the line marker to the
1180 // total.
1181 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1182 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001184 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Chris Lattner137b6a62009-02-04 06:25:26 +00001186 // Handle virtual #include manipulation.
1187 if (Entry->IncludeOffset) {
1188 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1189 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1190 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001191 }
1192 }
1193
1194 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001195}
1196
1197//===----------------------------------------------------------------------===//
1198// Other miscellaneous methods.
1199//===----------------------------------------------------------------------===//
1200
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001201/// \brief Retrieve the inode for the given file entry, if possible.
1202///
1203/// This routine involves a system call, and therefore should only be used
1204/// in non-performance-critical code.
1205static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1206 if (!File)
1207 return llvm::Optional<ino_t>();
1208
1209 struct stat StatBuf;
1210 if (::stat(File->getName(), &StatBuf))
1211 return llvm::Optional<ino_t>();
1212
1213 return StatBuf.st_ino;
1214}
1215
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001216/// \brief Get the source location for the given file:line:col triplet.
1217///
1218/// If the source file is included multiple times, the source location will
1219/// be based upon the first inclusion.
1220SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001221 unsigned Line, unsigned Col) {
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001222 assert(SourceFile && "Null source file!");
1223 assert(Line && Col && "Line and column should start from 1!");
1224
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001225 // Find the first file ID that corresponds to the given file.
1226 FileID FirstFID;
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001228 // First, check the main file ID, since it is common to look for a
1229 // location in the main file.
1230 llvm::Optional<ino_t> SourceFileInode;
1231 llvm::Optional<llvm::StringRef> SourceFileName;
1232 if (!MainFileID.isInvalid()) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001233 bool Invalid = false;
1234 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1235 if (Invalid)
1236 return SourceLocation();
1237
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001238 if (MainSLoc.isFile()) {
1239 const ContentCache *MainContentCache
1240 = MainSLoc.getFile().getContentCache();
Douglas Gregorb7a18412011-02-11 18:08:15 +00001241 if (!MainContentCache) {
1242 // Can't do anything
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001243 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001244 FirstFID = MainFileID;
Douglas Gregorb7a18412011-02-11 18:08:15 +00001245 } else {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001246 // Fall back: check whether we have the same base name and inode
1247 // as the main file.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001248 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001249 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1250 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1251 SourceFileInode = getActualFileInode(SourceFile);
Douglas Gregor37c02bf2011-02-16 19:09:24 +00001252 if (SourceFileInode) {
1253 if (llvm::Optional<ino_t> MainFileInode
1254 = getActualFileInode(MainFile)) {
1255 if (*SourceFileInode == *MainFileInode) {
1256 FirstFID = MainFileID;
1257 SourceFile = MainFile;
1258 }
1259 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001260 }
1261 }
1262 }
1263 }
1264 }
1265
1266 if (FirstFID.isInvalid()) {
1267 // The location we're looking for isn't in the main file; look
1268 // through all of the source locations.
1269 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001270 bool Invalid = false;
1271 const SLocEntry &SLoc = getSLocEntry(I, &Invalid);
1272 if (Invalid)
1273 return SourceLocation();
1274
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001275 if (SLoc.isFile() &&
1276 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001277 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001278 FirstFID = FileID::get(I);
1279 break;
1280 }
1281 }
1282 }
1283
1284 // If we haven't found what we want yet, try again, but this time stat()
1285 // each of the files in case the files have changed since we originally
1286 // parsed the file.
1287 if (FirstFID.isInvalid() &&
1288 (SourceFileName ||
1289 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1290 (SourceFileInode ||
1291 (SourceFileInode = getActualFileInode(SourceFile)))) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001292 bool Invalid = false;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001293 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001294 const SLocEntry &SLoc = getSLocEntry(I, &Invalid);
1295 if (Invalid)
1296 return SourceLocation();
1297
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001298 if (SLoc.isFile()) {
1299 const ContentCache *FileContentCache
1300 = SLoc.getFile().getContentCache();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001301 const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001302 if (Entry &&
Douglas Gregorb7a18412011-02-11 18:08:15 +00001303 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1304 if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1305 if (*SourceFileInode == *EntryInode) {
1306 FirstFID = FileID::get(I);
1307 SourceFile = Entry;
1308 break;
1309 }
1310 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001311 }
1312 }
1313 }
1314 }
1315
1316 if (FirstFID.isInvalid())
1317 return SourceLocation();
1318
1319 if (Line == 1 && Col == 1)
1320 return getLocForStartOfFile(FirstFID);
1321
1322 ContentCache *Content
1323 = const_cast<ContentCache *>(getOrCreateContentCache(SourceFile));
1324 if (!Content)
1325 return SourceLocation();
1326
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001327 // If this is the first use of line information for this buffer, compute the
1328 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001329 if (Content->SourceLineCache == 0) {
1330 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001331 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001332 if (MyInvalid)
1333 return SourceLocation();
1334 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001335
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001336 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001337 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001338 if (Size > 0)
1339 --Size;
1340 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1341 }
1342
1343 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnere127a0d2010-04-20 20:35:58 +00001344 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1345 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001346 unsigned i = 0;
1347
1348 // Check that the given column is valid.
1349 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1350 ++i;
1351 if (i < Col-1)
1352 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1353
Douglas Gregor4a160e12009-12-02 05:34:39 +00001354 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001355}
1356
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001357/// Given a decomposed source location, move it up the include/instantiation
1358/// stack to the parent source location. If this is possible, return the
1359/// decomposed version of the parent in Loc and return false. If Loc is the
1360/// top-level entry, return true and don't modify it.
1361static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1362 const SourceManager &SM) {
1363 SourceLocation UpperLoc;
1364 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
1365 if (Entry.isInstantiation())
1366 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1367 else
1368 UpperLoc = Entry.getFile().getIncludeLoc();
1369
1370 if (UpperLoc.isInvalid())
1371 return true; // We reached the top.
1372
1373 Loc = SM.getDecomposedLoc(UpperLoc);
1374 return false;
1375}
1376
1377
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001378/// \brief Determines the order of 2 source locations in the translation unit.
1379///
1380/// \returns true if LHS source location comes before RHS, false otherwise.
1381bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1382 SourceLocation RHS) const {
1383 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1384 if (LHS == RHS)
1385 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Argyrios Kyrtzidisee933e12010-12-24 02:53:53 +00001387 // If both locations are macro instantiations, the order of their offsets
1388 // reflect the order that the tokens, pointed to by these locations, were
1389 // instantiated (during parsing each token that is instantiated by a macro,
1390 // expands the SLocEntries).
1391 if (LHS.isMacroID() && RHS.isMacroID())
1392 return LHS.getOffset() < RHS.getOffset();
1393
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001394 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1395 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001397 // If the source locations are in the same file, just compare offsets.
1398 if (LOffs.first == ROffs.first)
1399 return LOffs.second < ROffs.second;
1400
1401 // If we are comparing a source location with multiple locations in the same
1402 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00001403 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1404 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001406 // Okay, we missed in the cache, start updating the cache for this query.
1407 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001409 // "Traverse" the include/instantiation stacks of both locations and try to
Chris Lattner48296ba2010-05-07 05:51:13 +00001410 // find a common "ancestor". FileIDs build a tree-like structure that
1411 // reflects the #include hierarchy, and this algorithm needs to find the
1412 // nearest common ancestor between the two locations. For example, if you
1413 // have a.c that includes b.h and c.h, and are comparing a location in b.h to
1414 // a location in c.h, we need to find that their nearest common ancestor is
1415 // a.c, and compare the locations of the two #includes to find their relative
1416 // ordering.
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001417 //
Chris Lattner48296ba2010-05-07 05:51:13 +00001418 // SourceManager assigns FileIDs in order of parsing. This means that an
1419 // includee always has a larger FileID than an includer. While you might
1420 // think that we could just compare the FileID's here, that doesn't work to
1421 // compare a point at the end of a.c with a point within c.h. Though c.h has
1422 // a larger FileID, we have to compare the include point of c.h to the
1423 // location in a.c.
1424 //
1425 // Despite not being able to directly compare FileID's, we can tell that a
1426 // larger FileID is necessarily more deeply nested than a lower one and use
1427 // this information to walk up the tree to the nearest common ancestor.
1428 do {
1429 // If LOffs is larger than ROffs, then LOffs must be more deeply nested than
1430 // ROffs, walk up the #include chain.
1431 if (LOffs.first.ID > ROffs.first.ID) {
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001432 if (MoveUpIncludeHierarchy(LOffs, *this))
Chris Lattner48296ba2010-05-07 05:51:13 +00001433 break; // We reached the top.
1434
Chris Lattner48296ba2010-05-07 05:51:13 +00001435 } else {
1436 // Otherwise, ROffs is larger than LOffs, so ROffs must be more deeply
1437 // nested than LOffs, walk up the #include chain.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001438 if (MoveUpIncludeHierarchy(ROffs, *this))
Chris Lattner48296ba2010-05-07 05:51:13 +00001439 break; // We reached the top.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001440 }
Chris Lattner48296ba2010-05-07 05:51:13 +00001441 } while (LOffs.first != ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Chris Lattner48296ba2010-05-07 05:51:13 +00001443 // If we exited because we found a nearest common ancestor, compare the
1444 // locations within the common file and cache them.
1445 if (LOffs.first == ROffs.first) {
1446 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1447 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001448 }
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001450 // There is no common ancestor, most probably because one location is in the
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001451 // predefines buffer or an AST file.
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001452 // FIXME: We should rearrange the external interface so this simply never
1453 // happens; it can't conceptually happen. Also see PR5662.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001454 IsBeforeInTUCache.setQueryFIDs(FileID(), FileID()); // Don't try caching.
1455
1456 // Zip both entries up to the top level record.
1457 while (!MoveUpIncludeHierarchy(LOffs, *this)) /*empty*/;
1458 while (!MoveUpIncludeHierarchy(ROffs, *this)) /*empty*/;
Chris Lattner48296ba2010-05-07 05:51:13 +00001459
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001460 // If exactly one location is a memory buffer, assume it precedes the other.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001461
1462 // Strip off macro instantation locations, going up to the top-level File
1463 // SLocEntry.
1464 bool LIsMB = getFileEntryForID(LOffs.first) == 0;
1465 bool RIsMB = getFileEntryForID(ROffs.first) == 0;
Chris Lattner48296ba2010-05-07 05:51:13 +00001466 if (LIsMB != RIsMB)
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001467 return LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001469 // Otherwise, just assume FileIDs were created in order.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001470 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001471}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001472
Reid Spencer5f016e22007-07-11 17:01:13 +00001473/// PrintStats - Print statistics to stderr.
1474///
1475void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001476 llvm::errs() << "\n*** Source Manager Stats:\n";
1477 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1478 << " mem buffers mapped.\n";
1479 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1480 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 unsigned NumLineNumsComputed = 0;
1483 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001484 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1485 NumLineNumsComputed += I->second->SourceLineCache != 0;
1486 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 }
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001489 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1490 << NumLineNumsComputed << " files with line #'s computed.\n";
1491 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1492 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001493}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001494
1495ExternalSLocEntrySource::~ExternalSLocEntrySource() { }