File: | include/llvm/ADT/IntrusiveRefCntPtr.h |
Warning: | line 157, column 38 Potential leak of memory pointed to by field 'Obj' |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- SourceManager.cpp - Track and cache source files -------------------===// | |||
2 | // | |||
3 | // The LLVM Compiler Infrastructure | |||
4 | // | |||
5 | // This file is distributed under the University of Illinois Open Source | |||
6 | // License. See LICENSE.TXT for details. | |||
7 | // | |||
8 | //===----------------------------------------------------------------------===// | |||
9 | // | |||
10 | // This file implements the SourceManager interface. | |||
11 | // | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "clang/Basic/SourceManager.h" | |||
15 | #include "clang/Basic/Diagnostic.h" | |||
16 | #include "clang/Basic/FileManager.h" | |||
17 | #include "clang/Basic/LLVM.h" | |||
18 | #include "clang/Basic/SourceLocation.h" | |||
19 | #include "clang/Basic/SourceManagerInternals.h" | |||
20 | #include "llvm/ADT/DenseMap.h" | |||
21 | #include "llvm/ADT/Optional.h" | |||
22 | #include "llvm/ADT/None.h" | |||
23 | #include "llvm/ADT/STLExtras.h" | |||
24 | #include "llvm/ADT/SmallVector.h" | |||
25 | #include "llvm/ADT/StringSwitch.h" | |||
26 | #include "llvm/ADT/StringRef.h" | |||
27 | #include "llvm/Support/Allocator.h" | |||
28 | #include "llvm/Support/Capacity.h" | |||
29 | #include "llvm/Support/Compiler.h" | |||
30 | #include "llvm/Support/ErrorHandling.h" | |||
31 | #include "llvm/Support/FileSystem.h" | |||
32 | #include "llvm/Support/MathExtras.h" | |||
33 | #include "llvm/Support/MemoryBuffer.h" | |||
34 | #include "llvm/Support/Path.h" | |||
35 | #include "llvm/Support/raw_ostream.h" | |||
36 | #include <algorithm> | |||
37 | #include <cassert> | |||
38 | #include <cstddef> | |||
39 | #include <cstdint> | |||
40 | #include <memory> | |||
41 | #include <tuple> | |||
42 | #include <utility> | |||
43 | #include <vector> | |||
44 | ||||
45 | using namespace clang; | |||
46 | using namespace SrcMgr; | |||
47 | using llvm::MemoryBuffer; | |||
48 | ||||
49 | //===----------------------------------------------------------------------===// | |||
50 | // SourceManager Helper Classes | |||
51 | //===----------------------------------------------------------------------===// | |||
52 | ||||
53 | ContentCache::~ContentCache() { | |||
54 | if (shouldFreeBuffer()) | |||
55 | delete Buffer.getPointer(); | |||
56 | } | |||
57 | ||||
58 | /// getSizeBytesMapped - Returns the number of bytes actually mapped for this | |||
59 | /// ContentCache. This can be 0 if the MemBuffer was not actually expanded. | |||
60 | unsigned ContentCache::getSizeBytesMapped() const { | |||
61 | return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0; | |||
62 | } | |||
63 | ||||
64 | /// Returns the kind of memory used to back the memory buffer for | |||
65 | /// this content cache. This is used for performance analysis. | |||
66 | llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const { | |||
67 | assert(Buffer.getPointer())(static_cast <bool> (Buffer.getPointer()) ? void (0) : __assert_fail ("Buffer.getPointer()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 67, __extension__ __PRETTY_FUNCTION__)); | |||
68 | ||||
69 | // Should be unreachable, but keep for sanity. | |||
70 | if (!Buffer.getPointer()) | |||
71 | return llvm::MemoryBuffer::MemoryBuffer_Malloc; | |||
72 | ||||
73 | llvm::MemoryBuffer *buf = Buffer.getPointer(); | |||
74 | return buf->getBufferKind(); | |||
75 | } | |||
76 | ||||
77 | /// getSize - Returns the size of the content encapsulated by this ContentCache. | |||
78 | /// This can be the size of the source file or the size of an arbitrary | |||
79 | /// scratch buffer. If the ContentCache encapsulates a source file, that | |||
80 | /// file is not lazily brought in from disk to satisfy this query. | |||
81 | unsigned ContentCache::getSize() const { | |||
82 | return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize() | |||
83 | : (unsigned) ContentsEntry->getSize(); | |||
84 | } | |||
85 | ||||
86 | void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) { | |||
87 | if (B && B == Buffer.getPointer()) { | |||
88 | assert(0 && "Replacing with the same buffer")(static_cast <bool> (0 && "Replacing with the same buffer" ) ? void (0) : __assert_fail ("0 && \"Replacing with the same buffer\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 88, __extension__ __PRETTY_FUNCTION__)); | |||
89 | Buffer.setInt(DoNotFree? DoNotFreeFlag : 0); | |||
90 | return; | |||
91 | } | |||
92 | ||||
93 | if (shouldFreeBuffer()) | |||
94 | delete Buffer.getPointer(); | |||
95 | Buffer.setPointer(B); | |||
96 | Buffer.setInt((B && DoNotFree) ? DoNotFreeFlag : 0); | |||
97 | } | |||
98 | ||||
99 | llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag, | |||
100 | const SourceManager &SM, | |||
101 | SourceLocation Loc, | |||
102 | bool *Invalid) const { | |||
103 | // Lazily create the Buffer for ContentCaches that wrap files. If we already | |||
104 | // computed it, just return what we have. | |||
105 | if (Buffer.getPointer() || !ContentsEntry) { | |||
106 | if (Invalid) | |||
107 | *Invalid = isBufferInvalid(); | |||
108 | ||||
109 | return Buffer.getPointer(); | |||
110 | } | |||
111 | ||||
112 | bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile; | |||
113 | auto BufferOrError = | |||
114 | SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile); | |||
115 | ||||
116 | // If we were unable to open the file, then we are in an inconsistent | |||
117 | // situation where the content cache referenced a file which no longer | |||
118 | // exists. Most likely, we were using a stat cache with an invalid entry but | |||
119 | // the file could also have been removed during processing. Since we can't | |||
120 | // really deal with this situation, just create an empty buffer. | |||
121 | // | |||
122 | // FIXME: This is definitely not ideal, but our immediate clients can't | |||
123 | // currently handle returning a null entry here. Ideally we should detect | |||
124 | // that we are in an inconsistent situation and error out as quickly as | |||
125 | // possible. | |||
126 | if (!BufferOrError) { | |||
127 | StringRef FillStr("<<<MISSING SOURCE FILE>>>\n"); | |||
128 | auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer( | |||
129 | ContentsEntry->getSize(), "<invalid>"); | |||
130 | char *Ptr = BackupBuffer->getBufferStart(); | |||
131 | for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i) | |||
132 | Ptr[i] = FillStr[i % FillStr.size()]; | |||
133 | Buffer.setPointer(BackupBuffer.release()); | |||
134 | ||||
135 | if (Diag.isDiagnosticInFlight()) | |||
136 | Diag.SetDelayedDiagnostic(diag::err_cannot_open_file, | |||
137 | ContentsEntry->getName(), | |||
138 | BufferOrError.getError().message()); | |||
139 | else | |||
140 | Diag.Report(Loc, diag::err_cannot_open_file) | |||
141 | << ContentsEntry->getName() << BufferOrError.getError().message(); | |||
142 | ||||
143 | Buffer.setInt(Buffer.getInt() | InvalidFlag); | |||
144 | ||||
145 | if (Invalid) *Invalid = true; | |||
146 | return Buffer.getPointer(); | |||
147 | } | |||
148 | ||||
149 | Buffer.setPointer(BufferOrError->release()); | |||
150 | ||||
151 | // Check that the file's size is the same as in the file entry (which may | |||
152 | // have come from a stat cache). | |||
153 | if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) { | |||
154 | if (Diag.isDiagnosticInFlight()) | |||
155 | Diag.SetDelayedDiagnostic(diag::err_file_modified, | |||
156 | ContentsEntry->getName()); | |||
157 | else | |||
158 | Diag.Report(Loc, diag::err_file_modified) | |||
159 | << ContentsEntry->getName(); | |||
160 | ||||
161 | Buffer.setInt(Buffer.getInt() | InvalidFlag); | |||
162 | if (Invalid) *Invalid = true; | |||
163 | return Buffer.getPointer(); | |||
164 | } | |||
165 | ||||
166 | // If the buffer is valid, check to see if it has a UTF Byte Order Mark | |||
167 | // (BOM). We only support UTF-8 with and without a BOM right now. See | |||
168 | // http://en.wikipedia.org/wiki/Byte_order_mark for more information. | |||
169 | StringRef BufStr = Buffer.getPointer()->getBuffer(); | |||
170 | const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr) | |||
171 | .StartsWith("\xFE\xFF", "UTF-16 (BE)") | |||
172 | .StartsWith("\xFF\xFE", "UTF-16 (LE)") | |||
173 | .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"), | |||
174 | "UTF-32 (BE)") | |||
175 | .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"), | |||
176 | "UTF-32 (LE)") | |||
177 | .StartsWith("\x2B\x2F\x76", "UTF-7") | |||
178 | .StartsWith("\xF7\x64\x4C", "UTF-1") | |||
179 | .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC") | |||
180 | .StartsWith("\x0E\xFE\xFF", "SDSU") | |||
181 | .StartsWith("\xFB\xEE\x28", "BOCU-1") | |||
182 | .StartsWith("\x84\x31\x95\x33", "GB-18030") | |||
183 | .Default(nullptr); | |||
184 | ||||
185 | if (InvalidBOM) { | |||
186 | Diag.Report(Loc, diag::err_unsupported_bom) | |||
187 | << InvalidBOM << ContentsEntry->getName(); | |||
188 | Buffer.setInt(Buffer.getInt() | InvalidFlag); | |||
189 | } | |||
190 | ||||
191 | if (Invalid) | |||
192 | *Invalid = isBufferInvalid(); | |||
193 | ||||
194 | return Buffer.getPointer(); | |||
195 | } | |||
196 | ||||
197 | unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) { | |||
198 | auto IterBool = | |||
199 | FilenameIDs.insert(std::make_pair(Name, FilenamesByID.size())); | |||
200 | if (IterBool.second) | |||
201 | FilenamesByID.push_back(&*IterBool.first); | |||
202 | return IterBool.first->second; | |||
203 | } | |||
204 | ||||
205 | /// Add a line note to the line table that indicates that there is a \#line or | |||
206 | /// GNU line marker at the specified FID/Offset location which changes the | |||
207 | /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't | |||
208 | /// change the presumed \#include stack. If it is 1, this is a file entry, if | |||
209 | /// it is 2 then this is a file exit. FileKind specifies whether this is a | |||
210 | /// system header or extern C system header. | |||
211 | void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo, | |||
212 | int FilenameID, unsigned EntryExit, | |||
213 | SrcMgr::CharacteristicKind FileKind) { | |||
214 | std::vector<LineEntry> &Entries = LineEntries[FID]; | |||
215 | ||||
216 | // An unspecified FilenameID means use the last filename if available, or the | |||
217 | // main source file otherwise. | |||
218 | if (FilenameID == -1 && !Entries.empty()) | |||
219 | FilenameID = Entries.back().FilenameID; | |||
220 | ||||
221 | assert((Entries.empty() || Entries.back().FileOffset < Offset) &&(static_cast <bool> ((Entries.empty() || Entries.back() .FileOffset < Offset) && "Adding line entries out of order!" ) ? void (0) : __assert_fail ("(Entries.empty() || Entries.back().FileOffset < Offset) && \"Adding line entries out of order!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 222, __extension__ __PRETTY_FUNCTION__)) | |||
222 | "Adding line entries out of order!")(static_cast <bool> ((Entries.empty() || Entries.back() .FileOffset < Offset) && "Adding line entries out of order!" ) ? void (0) : __assert_fail ("(Entries.empty() || Entries.back().FileOffset < Offset) && \"Adding line entries out of order!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 222, __extension__ __PRETTY_FUNCTION__)); | |||
223 | ||||
224 | unsigned IncludeOffset = 0; | |||
225 | if (EntryExit == 0) { // No #include stack change. | |||
226 | IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset; | |||
227 | } else if (EntryExit == 1) { | |||
228 | IncludeOffset = Offset-1; | |||
229 | } else if (EntryExit == 2) { | |||
230 | assert(!Entries.empty() && Entries.back().IncludeOffset &&(static_cast <bool> (!Entries.empty() && Entries .back().IncludeOffset && "PPDirectives should have caught case when popping empty include stack" ) ? void (0) : __assert_fail ("!Entries.empty() && Entries.back().IncludeOffset && \"PPDirectives should have caught case when popping empty include stack\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 231, __extension__ __PRETTY_FUNCTION__)) | |||
231 | "PPDirectives should have caught case when popping empty include stack")(static_cast <bool> (!Entries.empty() && Entries .back().IncludeOffset && "PPDirectives should have caught case when popping empty include stack" ) ? void (0) : __assert_fail ("!Entries.empty() && Entries.back().IncludeOffset && \"PPDirectives should have caught case when popping empty include stack\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 231, __extension__ __PRETTY_FUNCTION__)); | |||
232 | ||||
233 | // Get the include loc of the last entries' include loc as our include loc. | |||
234 | IncludeOffset = 0; | |||
235 | if (const LineEntry *PrevEntry = | |||
236 | FindNearestLineEntry(FID, Entries.back().IncludeOffset)) | |||
237 | IncludeOffset = PrevEntry->IncludeOffset; | |||
238 | } | |||
239 | ||||
240 | Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind, | |||
241 | IncludeOffset)); | |||
242 | } | |||
243 | ||||
244 | /// FindNearestLineEntry - Find the line entry nearest to FID that is before | |||
245 | /// it. If there is no line entry before Offset in FID, return null. | |||
246 | const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID, | |||
247 | unsigned Offset) { | |||
248 | const std::vector<LineEntry> &Entries = LineEntries[FID]; | |||
249 | assert(!Entries.empty() && "No #line entries for this FID after all!")(static_cast <bool> (!Entries.empty() && "No #line entries for this FID after all!" ) ? void (0) : __assert_fail ("!Entries.empty() && \"No #line entries for this FID after all!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 249, __extension__ __PRETTY_FUNCTION__)); | |||
250 | ||||
251 | // It is very common for the query to be after the last #line, check this | |||
252 | // first. | |||
253 | if (Entries.back().FileOffset <= Offset) | |||
254 | return &Entries.back(); | |||
255 | ||||
256 | // Do a binary search to find the maximal element that is still before Offset. | |||
257 | std::vector<LineEntry>::const_iterator I = | |||
258 | std::upper_bound(Entries.begin(), Entries.end(), Offset); | |||
259 | if (I == Entries.begin()) return nullptr; | |||
260 | return &*--I; | |||
261 | } | |||
262 | ||||
263 | /// Add a new line entry that has already been encoded into | |||
264 | /// the internal representation of the line table. | |||
265 | void LineTableInfo::AddEntry(FileID FID, | |||
266 | const std::vector<LineEntry> &Entries) { | |||
267 | LineEntries[FID] = Entries; | |||
268 | } | |||
269 | ||||
270 | /// getLineTableFilenameID - Return the uniqued ID for the specified filename. | |||
271 | unsigned SourceManager::getLineTableFilenameID(StringRef Name) { | |||
272 | return getLineTable().getLineTableFilenameID(Name); | |||
273 | } | |||
274 | ||||
275 | /// AddLineNote - Add a line note to the line table for the FileID and offset | |||
276 | /// specified by Loc. If FilenameID is -1, it is considered to be | |||
277 | /// unspecified. | |||
278 | void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, | |||
279 | int FilenameID, bool IsFileEntry, | |||
280 | bool IsFileExit, | |||
281 | SrcMgr::CharacteristicKind FileKind) { | |||
282 | std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); | |||
283 | ||||
284 | bool Invalid = false; | |||
285 | const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); | |||
286 | if (!Entry.isFile() || Invalid) | |||
287 | return; | |||
288 | ||||
289 | const SrcMgr::FileInfo &FileInfo = Entry.getFile(); | |||
290 | ||||
291 | // Remember that this file has #line directives now if it doesn't already. | |||
292 | const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives(); | |||
293 | ||||
294 | (void) getLineTable(); | |||
295 | ||||
296 | unsigned EntryExit = 0; | |||
297 | if (IsFileEntry) | |||
298 | EntryExit = 1; | |||
299 | else if (IsFileExit) | |||
300 | EntryExit = 2; | |||
301 | ||||
302 | LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID, | |||
303 | EntryExit, FileKind); | |||
304 | } | |||
305 | ||||
306 | LineTableInfo &SourceManager::getLineTable() { | |||
307 | if (!LineTable) | |||
308 | LineTable = new LineTableInfo(); | |||
309 | return *LineTable; | |||
310 | } | |||
311 | ||||
312 | //===----------------------------------------------------------------------===// | |||
313 | // Private 'Create' methods. | |||
314 | //===----------------------------------------------------------------------===// | |||
315 | ||||
316 | SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr, | |||
317 | bool UserFilesAreVolatile) | |||
318 | : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) { | |||
319 | clearIDTables(); | |||
320 | Diag.setSourceManager(this); | |||
321 | } | |||
322 | ||||
323 | SourceManager::~SourceManager() { | |||
324 | delete LineTable; | |||
325 | ||||
326 | // Delete FileEntry objects corresponding to content caches. Since the actual | |||
327 | // content cache objects are bump pointer allocated, we just have to run the | |||
328 | // dtors, but we call the deallocate method for completeness. | |||
329 | for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) { | |||
330 | if (MemBufferInfos[i]) { | |||
331 | MemBufferInfos[i]->~ContentCache(); | |||
332 | ContentCacheAlloc.Deallocate(MemBufferInfos[i]); | |||
333 | } | |||
334 | } | |||
335 | for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator | |||
336 | I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) { | |||
337 | if (I->second) { | |||
338 | I->second->~ContentCache(); | |||
339 | ContentCacheAlloc.Deallocate(I->second); | |||
340 | } | |||
341 | } | |||
342 | } | |||
343 | ||||
344 | void SourceManager::clearIDTables() { | |||
345 | MainFileID = FileID(); | |||
346 | LocalSLocEntryTable.clear(); | |||
347 | LoadedSLocEntryTable.clear(); | |||
348 | SLocEntryLoaded.clear(); | |||
349 | LastLineNoFileIDQuery = FileID(); | |||
350 | LastLineNoContentCache = nullptr; | |||
351 | LastFileIDLookup = FileID(); | |||
352 | ||||
353 | if (LineTable) | |||
354 | LineTable->clear(); | |||
355 | ||||
356 | // Use up FileID #0 as an invalid expansion. | |||
357 | NextLocalOffset = 0; | |||
358 | CurrentLoadedOffset = MaxLoadedOffset; | |||
359 | createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1); | |||
360 | } | |||
361 | ||||
362 | void SourceManager::initializeForReplay(const SourceManager &Old) { | |||
363 | assert(MainFileID.isInvalid() && "expected uninitialized SourceManager")(static_cast <bool> (MainFileID.isInvalid() && "expected uninitialized SourceManager" ) ? void (0) : __assert_fail ("MainFileID.isInvalid() && \"expected uninitialized SourceManager\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 363, __extension__ __PRETTY_FUNCTION__)); | |||
364 | ||||
365 | auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * { | |||
366 | auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache; | |||
367 | Clone->OrigEntry = Cache->OrigEntry; | |||
368 | Clone->ContentsEntry = Cache->ContentsEntry; | |||
369 | Clone->BufferOverridden = Cache->BufferOverridden; | |||
370 | Clone->IsSystemFile = Cache->IsSystemFile; | |||
371 | Clone->IsTransient = Cache->IsTransient; | |||
372 | Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true); | |||
373 | return Clone; | |||
374 | }; | |||
375 | ||||
376 | // Ensure all SLocEntries are loaded from the external source. | |||
377 | for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I) | |||
378 | if (!Old.SLocEntryLoaded[I]) | |||
379 | Old.loadSLocEntry(I, nullptr); | |||
380 | ||||
381 | // Inherit any content cache data from the old source manager. | |||
382 | for (auto &FileInfo : Old.FileInfos) { | |||
383 | SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first]; | |||
384 | if (Slot) | |||
385 | continue; | |||
386 | Slot = CloneContentCache(FileInfo.second); | |||
387 | } | |||
388 | } | |||
389 | ||||
390 | /// getOrCreateContentCache - Create or return a cached ContentCache for the | |||
391 | /// specified file. | |||
392 | const ContentCache * | |||
393 | SourceManager::getOrCreateContentCache(const FileEntry *FileEnt, | |||
394 | bool isSystemFile) { | |||
395 | assert(FileEnt && "Didn't specify a file entry to use?")(static_cast <bool> (FileEnt && "Didn't specify a file entry to use?" ) ? void (0) : __assert_fail ("FileEnt && \"Didn't specify a file entry to use?\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 395, __extension__ __PRETTY_FUNCTION__)); | |||
396 | ||||
397 | // Do we already have information about this file? | |||
398 | ContentCache *&Entry = FileInfos[FileEnt]; | |||
399 | if (Entry) return Entry; | |||
400 | ||||
401 | // Nope, create a new Cache entry. | |||
402 | Entry = ContentCacheAlloc.Allocate<ContentCache>(); | |||
403 | ||||
404 | if (OverriddenFilesInfo) { | |||
405 | // If the file contents are overridden with contents from another file, | |||
406 | // pass that file to ContentCache. | |||
407 | llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator | |||
408 | overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt); | |||
409 | if (overI == OverriddenFilesInfo->OverriddenFiles.end()) | |||
410 | new (Entry) ContentCache(FileEnt); | |||
411 | else | |||
412 | new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt | |||
413 | : overI->second, | |||
414 | overI->second); | |||
415 | } else { | |||
416 | new (Entry) ContentCache(FileEnt); | |||
417 | } | |||
418 | ||||
419 | Entry->IsSystemFile = isSystemFile; | |||
420 | Entry->IsTransient = FilesAreTransient; | |||
421 | ||||
422 | return Entry; | |||
423 | } | |||
424 | ||||
425 | /// Create a new ContentCache for the specified memory buffer. | |||
426 | /// This does no caching. | |||
427 | const ContentCache * | |||
428 | SourceManager::createMemBufferContentCache(llvm::MemoryBuffer *Buffer, | |||
429 | bool DoNotFree) { | |||
430 | // Add a new ContentCache to the MemBufferInfos list and return it. | |||
431 | ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(); | |||
432 | new (Entry) ContentCache(); | |||
433 | MemBufferInfos.push_back(Entry); | |||
434 | Entry->replaceBuffer(Buffer, DoNotFree); | |||
435 | return Entry; | |||
436 | } | |||
437 | ||||
438 | const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index, | |||
439 | bool *Invalid) const { | |||
440 | assert(!SLocEntryLoaded[Index])(static_cast <bool> (!SLocEntryLoaded[Index]) ? void (0 ) : __assert_fail ("!SLocEntryLoaded[Index]", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 440, __extension__ __PRETTY_FUNCTION__)); | |||
441 | if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) { | |||
442 | if (Invalid) | |||
443 | *Invalid = true; | |||
444 | // If the file of the SLocEntry changed we could still have loaded it. | |||
445 | if (!SLocEntryLoaded[Index]) { | |||
446 | // Try to recover; create a SLocEntry so the rest of clang can handle it. | |||
447 | LoadedSLocEntryTable[Index] = SLocEntry::get(0, | |||
448 | FileInfo::get(SourceLocation(), | |||
449 | getFakeContentCacheForRecovery(), | |||
450 | SrcMgr::C_User)); | |||
451 | } | |||
452 | } | |||
453 | ||||
454 | return LoadedSLocEntryTable[Index]; | |||
455 | } | |||
456 | ||||
457 | std::pair<int, unsigned> | |||
458 | SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries, | |||
459 | unsigned TotalSize) { | |||
460 | assert(ExternalSLocEntries && "Don't have an external sloc source")(static_cast <bool> (ExternalSLocEntries && "Don't have an external sloc source" ) ? void (0) : __assert_fail ("ExternalSLocEntries && \"Don't have an external sloc source\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 460, __extension__ __PRETTY_FUNCTION__)); | |||
461 | // Make sure we're not about to run out of source locations. | |||
462 | if (CurrentLoadedOffset - TotalSize < NextLocalOffset) | |||
463 | return std::make_pair(0, 0); | |||
464 | LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries); | |||
465 | SLocEntryLoaded.resize(LoadedSLocEntryTable.size()); | |||
466 | CurrentLoadedOffset -= TotalSize; | |||
467 | int ID = LoadedSLocEntryTable.size(); | |||
468 | return std::make_pair(-ID - 1, CurrentLoadedOffset); | |||
469 | } | |||
470 | ||||
471 | /// As part of recovering from missing or changed content, produce a | |||
472 | /// fake, non-empty buffer. | |||
473 | llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const { | |||
474 | if (!FakeBufferForRecovery) | |||
475 | FakeBufferForRecovery = | |||
476 | llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>"); | |||
477 | ||||
478 | return FakeBufferForRecovery.get(); | |||
479 | } | |||
480 | ||||
481 | /// As part of recovering from missing or changed content, produce a | |||
482 | /// fake content cache. | |||
483 | const SrcMgr::ContentCache * | |||
484 | SourceManager::getFakeContentCacheForRecovery() const { | |||
485 | if (!FakeContentCacheForRecovery) { | |||
486 | FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>(); | |||
487 | FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(), | |||
488 | /*DoNotFree=*/true); | |||
489 | } | |||
490 | return FakeContentCacheForRecovery.get(); | |||
491 | } | |||
492 | ||||
493 | /// Returns the previous in-order FileID or an invalid FileID if there | |||
494 | /// is no previous one. | |||
495 | FileID SourceManager::getPreviousFileID(FileID FID) const { | |||
496 | if (FID.isInvalid()) | |||
497 | return FileID(); | |||
498 | ||||
499 | int ID = FID.ID; | |||
500 | if (ID == -1) | |||
501 | return FileID(); | |||
502 | ||||
503 | if (ID > 0) { | |||
504 | if (ID-1 == 0) | |||
505 | return FileID(); | |||
506 | } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) { | |||
507 | return FileID(); | |||
508 | } | |||
509 | ||||
510 | return FileID::get(ID-1); | |||
511 | } | |||
512 | ||||
513 | /// Returns the next in-order FileID or an invalid FileID if there is | |||
514 | /// no next one. | |||
515 | FileID SourceManager::getNextFileID(FileID FID) const { | |||
516 | if (FID.isInvalid()) | |||
517 | return FileID(); | |||
518 | ||||
519 | int ID = FID.ID; | |||
520 | if (ID > 0) { | |||
521 | if (unsigned(ID+1) >= local_sloc_entry_size()) | |||
522 | return FileID(); | |||
523 | } else if (ID+1 >= -1) { | |||
524 | return FileID(); | |||
525 | } | |||
526 | ||||
527 | return FileID::get(ID+1); | |||
528 | } | |||
529 | ||||
530 | //===----------------------------------------------------------------------===// | |||
531 | // Methods to create new FileID's and macro expansions. | |||
532 | //===----------------------------------------------------------------------===// | |||
533 | ||||
534 | /// createFileID - Create a new FileID for the specified ContentCache and | |||
535 | /// include position. This works regardless of whether the ContentCache | |||
536 | /// corresponds to a file or some other input source. | |||
537 | FileID SourceManager::createFileID(const ContentCache *File, | |||
538 | SourceLocation IncludePos, | |||
539 | SrcMgr::CharacteristicKind FileCharacter, | |||
540 | int LoadedID, unsigned LoadedOffset) { | |||
541 | if (LoadedID < 0) { | |||
542 | assert(LoadedID != -1 && "Loading sentinel FileID")(static_cast <bool> (LoadedID != -1 && "Loading sentinel FileID" ) ? void (0) : __assert_fail ("LoadedID != -1 && \"Loading sentinel FileID\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 542, __extension__ __PRETTY_FUNCTION__)); | |||
543 | unsigned Index = unsigned(-LoadedID) - 2; | |||
544 | assert(Index < LoadedSLocEntryTable.size() && "FileID out of range")(static_cast <bool> (Index < LoadedSLocEntryTable.size () && "FileID out of range") ? void (0) : __assert_fail ("Index < LoadedSLocEntryTable.size() && \"FileID out of range\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 544, __extension__ __PRETTY_FUNCTION__)); | |||
545 | assert(!SLocEntryLoaded[Index] && "FileID already loaded")(static_cast <bool> (!SLocEntryLoaded[Index] && "FileID already loaded") ? void (0) : __assert_fail ("!SLocEntryLoaded[Index] && \"FileID already loaded\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 545, __extension__ __PRETTY_FUNCTION__)); | |||
546 | LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, | |||
547 | FileInfo::get(IncludePos, File, FileCharacter)); | |||
548 | SLocEntryLoaded[Index] = true; | |||
549 | return FileID::get(LoadedID); | |||
550 | } | |||
551 | LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, | |||
552 | FileInfo::get(IncludePos, File, | |||
553 | FileCharacter))); | |||
554 | unsigned FileSize = File->getSize(); | |||
555 | assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&(static_cast <bool> (NextLocalOffset + FileSize + 1 > NextLocalOffset && NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset && "Ran out of source locations!" ) ? void (0) : __assert_fail ("NextLocalOffset + FileSize + 1 > NextLocalOffset && NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset && \"Ran out of source locations!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 557, __extension__ __PRETTY_FUNCTION__)) | |||
556 | NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&(static_cast <bool> (NextLocalOffset + FileSize + 1 > NextLocalOffset && NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset && "Ran out of source locations!" ) ? void (0) : __assert_fail ("NextLocalOffset + FileSize + 1 > NextLocalOffset && NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset && \"Ran out of source locations!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 557, __extension__ __PRETTY_FUNCTION__)) | |||
557 | "Ran out of source locations!")(static_cast <bool> (NextLocalOffset + FileSize + 1 > NextLocalOffset && NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset && "Ran out of source locations!" ) ? void (0) : __assert_fail ("NextLocalOffset + FileSize + 1 > NextLocalOffset && NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset && \"Ran out of source locations!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 557, __extension__ __PRETTY_FUNCTION__)); | |||
558 | // We do a +1 here because we want a SourceLocation that means "the end of the | |||
559 | // file", e.g. for the "no newline at the end of the file" diagnostic. | |||
560 | NextLocalOffset += FileSize + 1; | |||
561 | ||||
562 | // Set LastFileIDLookup to the newly created file. The next getFileID call is | |||
563 | // almost guaranteed to be from that file. | |||
564 | FileID FID = FileID::get(LocalSLocEntryTable.size()-1); | |||
565 | return LastFileIDLookup = FID; | |||
566 | } | |||
567 | ||||
568 | SourceLocation | |||
569 | SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc, | |||
570 | SourceLocation ExpansionLoc, | |||
571 | unsigned TokLength) { | |||
572 | ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc, | |||
573 | ExpansionLoc); | |||
574 | return createExpansionLocImpl(Info, TokLength); | |||
575 | } | |||
576 | ||||
577 | SourceLocation | |||
578 | SourceManager::createExpansionLoc(SourceLocation SpellingLoc, | |||
579 | SourceLocation ExpansionLocStart, | |||
580 | SourceLocation ExpansionLocEnd, | |||
581 | unsigned TokLength, | |||
582 | bool ExpansionIsTokenRange, | |||
583 | int LoadedID, | |||
584 | unsigned LoadedOffset) { | |||
585 | ExpansionInfo Info = ExpansionInfo::create( | |||
586 | SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange); | |||
587 | return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset); | |||
588 | } | |||
589 | ||||
590 | SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling, | |||
591 | SourceLocation TokenStart, | |||
592 | SourceLocation TokenEnd) { | |||
593 | assert(getFileID(TokenStart) == getFileID(TokenEnd) &&(static_cast <bool> (getFileID(TokenStart) == getFileID (TokenEnd) && "token spans multiple files") ? void (0 ) : __assert_fail ("getFileID(TokenStart) == getFileID(TokenEnd) && \"token spans multiple files\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 594, __extension__ __PRETTY_FUNCTION__)) | |||
594 | "token spans multiple files")(static_cast <bool> (getFileID(TokenStart) == getFileID (TokenEnd) && "token spans multiple files") ? void (0 ) : __assert_fail ("getFileID(TokenStart) == getFileID(TokenEnd) && \"token spans multiple files\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 594, __extension__ __PRETTY_FUNCTION__)); | |||
595 | return createExpansionLocImpl( | |||
596 | ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd), | |||
597 | TokenEnd.getOffset() - TokenStart.getOffset()); | |||
598 | } | |||
599 | ||||
600 | SourceLocation | |||
601 | SourceManager::createExpansionLocImpl(const ExpansionInfo &Info, | |||
602 | unsigned TokLength, | |||
603 | int LoadedID, | |||
604 | unsigned LoadedOffset) { | |||
605 | if (LoadedID < 0) { | |||
606 | assert(LoadedID != -1 && "Loading sentinel FileID")(static_cast <bool> (LoadedID != -1 && "Loading sentinel FileID" ) ? void (0) : __assert_fail ("LoadedID != -1 && \"Loading sentinel FileID\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 606, __extension__ __PRETTY_FUNCTION__)); | |||
607 | unsigned Index = unsigned(-LoadedID) - 2; | |||
608 | assert(Index < LoadedSLocEntryTable.size() && "FileID out of range")(static_cast <bool> (Index < LoadedSLocEntryTable.size () && "FileID out of range") ? void (0) : __assert_fail ("Index < LoadedSLocEntryTable.size() && \"FileID out of range\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 608, __extension__ __PRETTY_FUNCTION__)); | |||
609 | assert(!SLocEntryLoaded[Index] && "FileID already loaded")(static_cast <bool> (!SLocEntryLoaded[Index] && "FileID already loaded") ? void (0) : __assert_fail ("!SLocEntryLoaded[Index] && \"FileID already loaded\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 609, __extension__ __PRETTY_FUNCTION__)); | |||
610 | LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info); | |||
611 | SLocEntryLoaded[Index] = true; | |||
612 | return SourceLocation::getMacroLoc(LoadedOffset); | |||
613 | } | |||
614 | LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info)); | |||
615 | assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&(static_cast <bool> (NextLocalOffset + TokLength + 1 > NextLocalOffset && NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset && "Ran out of source locations!" ) ? void (0) : __assert_fail ("NextLocalOffset + TokLength + 1 > NextLocalOffset && NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset && \"Ran out of source locations!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 617, __extension__ __PRETTY_FUNCTION__)) | |||
616 | NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&(static_cast <bool> (NextLocalOffset + TokLength + 1 > NextLocalOffset && NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset && "Ran out of source locations!" ) ? void (0) : __assert_fail ("NextLocalOffset + TokLength + 1 > NextLocalOffset && NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset && \"Ran out of source locations!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 617, __extension__ __PRETTY_FUNCTION__)) | |||
617 | "Ran out of source locations!")(static_cast <bool> (NextLocalOffset + TokLength + 1 > NextLocalOffset && NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset && "Ran out of source locations!" ) ? void (0) : __assert_fail ("NextLocalOffset + TokLength + 1 > NextLocalOffset && NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset && \"Ran out of source locations!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 617, __extension__ __PRETTY_FUNCTION__)); | |||
618 | // See createFileID for that +1. | |||
619 | NextLocalOffset += TokLength + 1; | |||
620 | return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1)); | |||
621 | } | |||
622 | ||||
623 | llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File, | |||
624 | bool *Invalid) { | |||
625 | const SrcMgr::ContentCache *IR = getOrCreateContentCache(File); | |||
626 | assert(IR && "getOrCreateContentCache() cannot return NULL")(static_cast <bool> (IR && "getOrCreateContentCache() cannot return NULL" ) ? void (0) : __assert_fail ("IR && \"getOrCreateContentCache() cannot return NULL\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 626, __extension__ __PRETTY_FUNCTION__)); | |||
627 | return IR->getBuffer(Diag, *this, SourceLocation(), Invalid); | |||
628 | } | |||
629 | ||||
630 | void SourceManager::overrideFileContents(const FileEntry *SourceFile, | |||
631 | llvm::MemoryBuffer *Buffer, | |||
632 | bool DoNotFree) { | |||
633 | const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile); | |||
634 | assert(IR && "getOrCreateContentCache() cannot return NULL")(static_cast <bool> (IR && "getOrCreateContentCache() cannot return NULL" ) ? void (0) : __assert_fail ("IR && \"getOrCreateContentCache() cannot return NULL\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 634, __extension__ __PRETTY_FUNCTION__)); | |||
635 | ||||
636 | const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree); | |||
637 | const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true; | |||
638 | ||||
639 | getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile); | |||
640 | } | |||
641 | ||||
642 | void SourceManager::overrideFileContents(const FileEntry *SourceFile, | |||
643 | const FileEntry *NewFile) { | |||
644 | assert(SourceFile->getSize() == NewFile->getSize() &&(static_cast <bool> (SourceFile->getSize() == NewFile ->getSize() && "Different sizes, use the FileManager to create a virtual file with " "the correct size") ? void (0) : __assert_fail ("SourceFile->getSize() == NewFile->getSize() && \"Different sizes, use the FileManager to create a virtual file with \" \"the correct size\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 646, __extension__ __PRETTY_FUNCTION__)) | |||
645 | "Different sizes, use the FileManager to create a virtual file with "(static_cast <bool> (SourceFile->getSize() == NewFile ->getSize() && "Different sizes, use the FileManager to create a virtual file with " "the correct size") ? void (0) : __assert_fail ("SourceFile->getSize() == NewFile->getSize() && \"Different sizes, use the FileManager to create a virtual file with \" \"the correct size\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 646, __extension__ __PRETTY_FUNCTION__)) | |||
646 | "the correct size")(static_cast <bool> (SourceFile->getSize() == NewFile ->getSize() && "Different sizes, use the FileManager to create a virtual file with " "the correct size") ? void (0) : __assert_fail ("SourceFile->getSize() == NewFile->getSize() && \"Different sizes, use the FileManager to create a virtual file with \" \"the correct size\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 646, __extension__ __PRETTY_FUNCTION__)); | |||
647 | assert(FileInfos.count(SourceFile) == 0 &&(static_cast <bool> (FileInfos.count(SourceFile) == 0 && "This function should be called at the initialization stage, before " "any parsing occurs.") ? void (0) : __assert_fail ("FileInfos.count(SourceFile) == 0 && \"This function should be called at the initialization stage, before \" \"any parsing occurs.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 649, __extension__ __PRETTY_FUNCTION__)) | |||
648 | "This function should be called at the initialization stage, before "(static_cast <bool> (FileInfos.count(SourceFile) == 0 && "This function should be called at the initialization stage, before " "any parsing occurs.") ? void (0) : __assert_fail ("FileInfos.count(SourceFile) == 0 && \"This function should be called at the initialization stage, before \" \"any parsing occurs.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 649, __extension__ __PRETTY_FUNCTION__)) | |||
649 | "any parsing occurs.")(static_cast <bool> (FileInfos.count(SourceFile) == 0 && "This function should be called at the initialization stage, before " "any parsing occurs.") ? void (0) : __assert_fail ("FileInfos.count(SourceFile) == 0 && \"This function should be called at the initialization stage, before \" \"any parsing occurs.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 649, __extension__ __PRETTY_FUNCTION__)); | |||
650 | getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile; | |||
651 | } | |||
652 | ||||
653 | void SourceManager::disableFileContentsOverride(const FileEntry *File) { | |||
654 | if (!isFileOverridden(File)) | |||
655 | return; | |||
656 | ||||
657 | const SrcMgr::ContentCache *IR = getOrCreateContentCache(File); | |||
658 | const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr); | |||
659 | const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry; | |||
660 | ||||
661 | assert(OverriddenFilesInfo)(static_cast <bool> (OverriddenFilesInfo) ? void (0) : __assert_fail ("OverriddenFilesInfo", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 661, __extension__ __PRETTY_FUNCTION__)); | |||
662 | OverriddenFilesInfo->OverriddenFiles.erase(File); | |||
663 | OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File); | |||
664 | } | |||
665 | ||||
666 | void SourceManager::setFileIsTransient(const FileEntry *File) { | |||
667 | const SrcMgr::ContentCache *CC = getOrCreateContentCache(File); | |||
668 | const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true; | |||
669 | } | |||
670 | ||||
671 | StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const { | |||
672 | bool MyInvalid = false; | |||
673 | const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid); | |||
674 | if (!SLoc.isFile() || MyInvalid) { | |||
675 | if (Invalid) | |||
676 | *Invalid = true; | |||
677 | return "<<<<<INVALID SOURCE LOCATION>>>>>"; | |||
678 | } | |||
679 | ||||
680 | llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer( | |||
681 | Diag, *this, SourceLocation(), &MyInvalid); | |||
682 | if (Invalid) | |||
683 | *Invalid = MyInvalid; | |||
684 | ||||
685 | if (MyInvalid) | |||
686 | return "<<<<<INVALID SOURCE LOCATION>>>>>"; | |||
687 | ||||
688 | return Buf->getBuffer(); | |||
689 | } | |||
690 | ||||
691 | //===----------------------------------------------------------------------===// | |||
692 | // SourceLocation manipulation methods. | |||
693 | //===----------------------------------------------------------------------===// | |||
694 | ||||
695 | /// Return the FileID for a SourceLocation. | |||
696 | /// | |||
697 | /// This is the cache-miss path of getFileID. Not as hot as that function, but | |||
698 | /// still very important. It is responsible for finding the entry in the | |||
699 | /// SLocEntry tables that contains the specified location. | |||
700 | FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const { | |||
701 | if (!SLocOffset) | |||
702 | return FileID::get(0); | |||
703 | ||||
704 | // Now it is time to search for the correct file. See where the SLocOffset | |||
705 | // sits in the global view and consult local or loaded buffers for it. | |||
706 | if (SLocOffset < NextLocalOffset) | |||
707 | return getFileIDLocal(SLocOffset); | |||
708 | return getFileIDLoaded(SLocOffset); | |||
709 | } | |||
710 | ||||
711 | /// Return the FileID for a SourceLocation with a low offset. | |||
712 | /// | |||
713 | /// This function knows that the SourceLocation is in a local buffer, not a | |||
714 | /// loaded one. | |||
715 | FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const { | |||
716 | assert(SLocOffset < NextLocalOffset && "Bad function choice")(static_cast <bool> (SLocOffset < NextLocalOffset && "Bad function choice") ? void (0) : __assert_fail ("SLocOffset < NextLocalOffset && \"Bad function choice\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 716, __extension__ __PRETTY_FUNCTION__)); | |||
717 | ||||
718 | // After the first and second level caches, I see two common sorts of | |||
719 | // behavior: 1) a lot of searched FileID's are "near" the cached file | |||
720 | // location or are "near" the cached expansion location. 2) others are just | |||
721 | // completely random and may be a very long way away. | |||
722 | // | |||
723 | // To handle this, we do a linear search for up to 8 steps to catch #1 quickly | |||
724 | // then we fall back to a less cache efficient, but more scalable, binary | |||
725 | // search to find the location. | |||
726 | ||||
727 | // See if this is near the file point - worst case we start scanning from the | |||
728 | // most newly created FileID. | |||
729 | const SrcMgr::SLocEntry *I; | |||
730 | ||||
731 | if (LastFileIDLookup.ID < 0 || | |||
732 | LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) { | |||
733 | // Neither loc prunes our search. | |||
734 | I = LocalSLocEntryTable.end(); | |||
735 | } else { | |||
736 | // Perhaps it is near the file point. | |||
737 | I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID; | |||
738 | } | |||
739 | ||||
740 | // Find the FileID that contains this. "I" is an iterator that points to a | |||
741 | // FileID whose offset is known to be larger than SLocOffset. | |||
742 | unsigned NumProbes = 0; | |||
743 | while (true) { | |||
744 | --I; | |||
745 | if (I->getOffset() <= SLocOffset) { | |||
746 | FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin())); | |||
747 | ||||
748 | // If this isn't an expansion, remember it. We have good locality across | |||
749 | // FileID lookups. | |||
750 | if (!I->isExpansion()) | |||
751 | LastFileIDLookup = Res; | |||
752 | NumLinearScans += NumProbes+1; | |||
753 | return Res; | |||
754 | } | |||
755 | if (++NumProbes == 8) | |||
756 | break; | |||
757 | } | |||
758 | ||||
759 | // Convert "I" back into an index. We know that it is an entry whose index is | |||
760 | // larger than the offset we are looking for. | |||
761 | unsigned GreaterIndex = I - LocalSLocEntryTable.begin(); | |||
762 | // LessIndex - This is the lower bound of the range that we're searching. | |||
763 | // We know that the offset corresponding to the FileID is is less than | |||
764 | // SLocOffset. | |||
765 | unsigned LessIndex = 0; | |||
766 | NumProbes = 0; | |||
767 | while (true) { | |||
768 | bool Invalid = false; | |||
769 | unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex; | |||
770 | unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset(); | |||
771 | if (Invalid) | |||
772 | return FileID::get(0); | |||
773 | ||||
774 | ++NumProbes; | |||
775 | ||||
776 | // If the offset of the midpoint is too large, chop the high side of the | |||
777 | // range to the midpoint. | |||
778 | if (MidOffset > SLocOffset) { | |||
779 | GreaterIndex = MiddleIndex; | |||
780 | continue; | |||
781 | } | |||
782 | ||||
783 | // If the middle index contains the value, succeed and return. | |||
784 | // FIXME: This could be made faster by using a function that's aware of | |||
785 | // being in the local area. | |||
786 | if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) { | |||
787 | FileID Res = FileID::get(MiddleIndex); | |||
788 | ||||
789 | // If this isn't a macro expansion, remember it. We have good locality | |||
790 | // across FileID lookups. | |||
791 | if (!LocalSLocEntryTable[MiddleIndex].isExpansion()) | |||
792 | LastFileIDLookup = Res; | |||
793 | NumBinaryProbes += NumProbes; | |||
794 | return Res; | |||
795 | } | |||
796 | ||||
797 | // Otherwise, move the low-side up to the middle index. | |||
798 | LessIndex = MiddleIndex; | |||
799 | } | |||
800 | } | |||
801 | ||||
802 | /// Return the FileID for a SourceLocation with a high offset. | |||
803 | /// | |||
804 | /// This function knows that the SourceLocation is in a loaded buffer, not a | |||
805 | /// local one. | |||
806 | FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const { | |||
807 | // Sanity checking, otherwise a bug may lead to hanging in release build. | |||
808 | if (SLocOffset < CurrentLoadedOffset) { | |||
809 | assert(0 && "Invalid SLocOffset or bad function choice")(static_cast <bool> (0 && "Invalid SLocOffset or bad function choice" ) ? void (0) : __assert_fail ("0 && \"Invalid SLocOffset or bad function choice\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 809, __extension__ __PRETTY_FUNCTION__)); | |||
810 | return FileID(); | |||
811 | } | |||
812 | ||||
813 | // Essentially the same as the local case, but the loaded array is sorted | |||
814 | // in the other direction. | |||
815 | ||||
816 | // First do a linear scan from the last lookup position, if possible. | |||
817 | unsigned I; | |||
818 | int LastID = LastFileIDLookup.ID; | |||
819 | if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset) | |||
820 | I = 0; | |||
821 | else | |||
822 | I = (-LastID - 2) + 1; | |||
823 | ||||
824 | unsigned NumProbes; | |||
825 | for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) { | |||
826 | // Make sure the entry is loaded! | |||
827 | const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I); | |||
828 | if (E.getOffset() <= SLocOffset) { | |||
829 | FileID Res = FileID::get(-int(I) - 2); | |||
830 | ||||
831 | if (!E.isExpansion()) | |||
832 | LastFileIDLookup = Res; | |||
833 | NumLinearScans += NumProbes + 1; | |||
834 | return Res; | |||
835 | } | |||
836 | } | |||
837 | ||||
838 | // Linear scan failed. Do the binary search. Note the reverse sorting of the | |||
839 | // table: GreaterIndex is the one where the offset is greater, which is | |||
840 | // actually a lower index! | |||
841 | unsigned GreaterIndex = I; | |||
842 | unsigned LessIndex = LoadedSLocEntryTable.size(); | |||
843 | NumProbes = 0; | |||
844 | while (true) { | |||
845 | ++NumProbes; | |||
846 | unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex; | |||
847 | const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex); | |||
848 | if (E.getOffset() == 0) | |||
849 | return FileID(); // invalid entry. | |||
850 | ||||
851 | ++NumProbes; | |||
852 | ||||
853 | if (E.getOffset() > SLocOffset) { | |||
854 | // Sanity checking, otherwise a bug may lead to hanging in release build. | |||
855 | if (GreaterIndex == MiddleIndex) { | |||
856 | assert(0 && "binary search missed the entry")(static_cast <bool> (0 && "binary search missed the entry" ) ? void (0) : __assert_fail ("0 && \"binary search missed the entry\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 856, __extension__ __PRETTY_FUNCTION__)); | |||
857 | return FileID(); | |||
858 | } | |||
859 | GreaterIndex = MiddleIndex; | |||
860 | continue; | |||
861 | } | |||
862 | ||||
863 | if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) { | |||
864 | FileID Res = FileID::get(-int(MiddleIndex) - 2); | |||
865 | if (!E.isExpansion()) | |||
866 | LastFileIDLookup = Res; | |||
867 | NumBinaryProbes += NumProbes; | |||
868 | return Res; | |||
869 | } | |||
870 | ||||
871 | // Sanity checking, otherwise a bug may lead to hanging in release build. | |||
872 | if (LessIndex == MiddleIndex) { | |||
873 | assert(0 && "binary search missed the entry")(static_cast <bool> (0 && "binary search missed the entry" ) ? void (0) : __assert_fail ("0 && \"binary search missed the entry\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 873, __extension__ __PRETTY_FUNCTION__)); | |||
874 | return FileID(); | |||
875 | } | |||
876 | LessIndex = MiddleIndex; | |||
877 | } | |||
878 | } | |||
879 | ||||
880 | SourceLocation SourceManager:: | |||
881 | getExpansionLocSlowCase(SourceLocation Loc) const { | |||
882 | do { | |||
883 | // Note: If Loc indicates an offset into a token that came from a macro | |||
884 | // expansion (e.g. the 5th character of the token) we do not want to add | |||
885 | // this offset when going to the expansion location. The expansion | |||
886 | // location is the macro invocation, which the offset has nothing to do | |||
887 | // with. This is unlike when we get the spelling loc, because the offset | |||
888 | // directly correspond to the token whose spelling we're inspecting. | |||
889 | Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart(); | |||
890 | } while (!Loc.isFileID()); | |||
891 | ||||
892 | return Loc; | |||
893 | } | |||
894 | ||||
895 | SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const { | |||
896 | do { | |||
897 | std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc); | |||
898 | Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc(); | |||
899 | Loc = Loc.getLocWithOffset(LocInfo.second); | |||
900 | } while (!Loc.isFileID()); | |||
901 | return Loc; | |||
902 | } | |||
903 | ||||
904 | SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const { | |||
905 | do { | |||
906 | if (isMacroArgExpansion(Loc)) | |||
907 | Loc = getImmediateSpellingLoc(Loc); | |||
908 | else | |||
909 | Loc = getImmediateExpansionRange(Loc).getBegin(); | |||
910 | } while (!Loc.isFileID()); | |||
911 | return Loc; | |||
912 | } | |||
913 | ||||
914 | ||||
915 | std::pair<FileID, unsigned> | |||
916 | SourceManager::getDecomposedExpansionLocSlowCase( | |||
917 | const SrcMgr::SLocEntry *E) const { | |||
918 | // If this is an expansion record, walk through all the expansion points. | |||
919 | FileID FID; | |||
920 | SourceLocation Loc; | |||
921 | unsigned Offset; | |||
922 | do { | |||
923 | Loc = E->getExpansion().getExpansionLocStart(); | |||
924 | ||||
925 | FID = getFileID(Loc); | |||
926 | E = &getSLocEntry(FID); | |||
927 | Offset = Loc.getOffset()-E->getOffset(); | |||
928 | } while (!Loc.isFileID()); | |||
929 | ||||
930 | return std::make_pair(FID, Offset); | |||
931 | } | |||
932 | ||||
933 | std::pair<FileID, unsigned> | |||
934 | SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E, | |||
935 | unsigned Offset) const { | |||
936 | // If this is an expansion record, walk through all the expansion points. | |||
937 | FileID FID; | |||
938 | SourceLocation Loc; | |||
939 | do { | |||
940 | Loc = E->getExpansion().getSpellingLoc(); | |||
941 | Loc = Loc.getLocWithOffset(Offset); | |||
942 | ||||
943 | FID = getFileID(Loc); | |||
944 | E = &getSLocEntry(FID); | |||
945 | Offset = Loc.getOffset()-E->getOffset(); | |||
946 | } while (!Loc.isFileID()); | |||
947 | ||||
948 | return std::make_pair(FID, Offset); | |||
949 | } | |||
950 | ||||
951 | /// getImmediateSpellingLoc - Given a SourceLocation object, return the | |||
952 | /// spelling location referenced by the ID. This is the first level down | |||
953 | /// towards the place where the characters that make up the lexed token can be | |||
954 | /// found. This should not generally be used by clients. | |||
955 | SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{ | |||
956 | if (Loc.isFileID()) return Loc; | |||
957 | std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc); | |||
958 | Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc(); | |||
959 | return Loc.getLocWithOffset(LocInfo.second); | |||
960 | } | |||
961 | ||||
962 | /// getImmediateExpansionRange - Loc is required to be an expansion location. | |||
963 | /// Return the start/end of the expansion information. | |||
964 | CharSourceRange | |||
965 | SourceManager::getImmediateExpansionRange(SourceLocation Loc) const { | |||
966 | assert(Loc.isMacroID() && "Not a macro expansion loc!")(static_cast <bool> (Loc.isMacroID() && "Not a macro expansion loc!" ) ? void (0) : __assert_fail ("Loc.isMacroID() && \"Not a macro expansion loc!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 966, __extension__ __PRETTY_FUNCTION__)); | |||
967 | const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion(); | |||
968 | return Expansion.getExpansionLocRange(); | |||
969 | } | |||
970 | ||||
971 | SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const { | |||
972 | while (isMacroArgExpansion(Loc)) | |||
973 | Loc = getImmediateSpellingLoc(Loc); | |||
974 | return Loc; | |||
975 | } | |||
976 | ||||
977 | /// getExpansionRange - Given a SourceLocation object, return the range of | |||
978 | /// tokens covered by the expansion in the ultimate file. | |||
979 | CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const { | |||
980 | if (Loc.isFileID()) | |||
981 | return CharSourceRange(SourceRange(Loc, Loc), true); | |||
982 | ||||
983 | CharSourceRange Res = getImmediateExpansionRange(Loc); | |||
984 | ||||
985 | // Fully resolve the start and end locations to their ultimate expansion | |||
986 | // points. | |||
987 | while (!Res.getBegin().isFileID()) | |||
988 | Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin()); | |||
989 | while (!Res.getEnd().isFileID()) { | |||
990 | CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd()); | |||
991 | Res.setEnd(EndRange.getEnd()); | |||
992 | Res.setTokenRange(EndRange.isTokenRange()); | |||
993 | } | |||
994 | return Res; | |||
995 | } | |||
996 | ||||
997 | bool SourceManager::isMacroArgExpansion(SourceLocation Loc, | |||
998 | SourceLocation *StartLoc) const { | |||
999 | if (!Loc.isMacroID()) return false; | |||
1000 | ||||
1001 | FileID FID = getFileID(Loc); | |||
1002 | const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion(); | |||
1003 | if (!Expansion.isMacroArgExpansion()) return false; | |||
1004 | ||||
1005 | if (StartLoc) | |||
1006 | *StartLoc = Expansion.getExpansionLocStart(); | |||
1007 | return true; | |||
1008 | } | |||
1009 | ||||
1010 | bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const { | |||
1011 | if (!Loc.isMacroID()) return false; | |||
1012 | ||||
1013 | FileID FID = getFileID(Loc); | |||
1014 | const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion(); | |||
1015 | return Expansion.isMacroBodyExpansion(); | |||
1016 | } | |||
1017 | ||||
1018 | bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc, | |||
1019 | SourceLocation *MacroBegin) const { | |||
1020 | assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc")(static_cast <bool> (Loc.isValid() && Loc.isMacroID () && "Expected a valid macro loc") ? void (0) : __assert_fail ("Loc.isValid() && Loc.isMacroID() && \"Expected a valid macro loc\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 1020, __extension__ __PRETTY_FUNCTION__)); | |||
1021 | ||||
1022 | std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc); | |||
1023 | if (DecompLoc.second > 0) | |||
1024 | return false; // Does not point at the start of expansion range. | |||
1025 | ||||
1026 | bool Invalid = false; | |||
1027 | const SrcMgr::ExpansionInfo &ExpInfo = | |||
1028 | getSLocEntry(DecompLoc.first, &Invalid).getExpansion(); | |||
1029 | if (Invalid) | |||
1030 | return false; | |||
1031 | SourceLocation ExpLoc = ExpInfo.getExpansionLocStart(); | |||
1032 | ||||
1033 | if (ExpInfo.isMacroArgExpansion()) { | |||
1034 | // For macro argument expansions, check if the previous FileID is part of | |||
1035 | // the same argument expansion, in which case this Loc is not at the | |||
1036 | // beginning of the expansion. | |||
1037 | FileID PrevFID = getPreviousFileID(DecompLoc.first); | |||
1038 | if (!PrevFID.isInvalid()) { | |||
1039 | const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid); | |||
1040 | if (Invalid) | |||
1041 | return false; | |||
1042 | if (PrevEntry.isExpansion() && | |||
1043 | PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc) | |||
1044 | return false; | |||
1045 | } | |||
1046 | } | |||
1047 | ||||
1048 | if (MacroBegin) | |||
1049 | *MacroBegin = ExpLoc; | |||
1050 | return true; | |||
1051 | } | |||
1052 | ||||
1053 | bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc, | |||
1054 | SourceLocation *MacroEnd) const { | |||
1055 | assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc")(static_cast <bool> (Loc.isValid() && Loc.isMacroID () && "Expected a valid macro loc") ? void (0) : __assert_fail ("Loc.isValid() && Loc.isMacroID() && \"Expected a valid macro loc\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 1055, __extension__ __PRETTY_FUNCTION__)); | |||
1056 | ||||
1057 | FileID FID = getFileID(Loc); | |||
1058 | SourceLocation NextLoc = Loc.getLocWithOffset(1); | |||
1059 | if (isInFileID(NextLoc, FID)) | |||
1060 | return false; // Does not point at the end of expansion range. | |||
1061 | ||||
1062 | bool Invalid = false; | |||
1063 | const SrcMgr::ExpansionInfo &ExpInfo = | |||
1064 | getSLocEntry(FID, &Invalid).getExpansion(); | |||
1065 | if (Invalid) | |||
1066 | return false; | |||
1067 | ||||
1068 | if (ExpInfo.isMacroArgExpansion()) { | |||
1069 | // For macro argument expansions, check if the next FileID is part of the | |||
1070 | // same argument expansion, in which case this Loc is not at the end of the | |||
1071 | // expansion. | |||
1072 | FileID NextFID = getNextFileID(FID); | |||
1073 | if (!NextFID.isInvalid()) { | |||
1074 | const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid); | |||
1075 | if (Invalid) | |||
1076 | return false; | |||
1077 | if (NextEntry.isExpansion() && | |||
1078 | NextEntry.getExpansion().getExpansionLocStart() == | |||
1079 | ExpInfo.getExpansionLocStart()) | |||
1080 | return false; | |||
1081 | } | |||
1082 | } | |||
1083 | ||||
1084 | if (MacroEnd) | |||
1085 | *MacroEnd = ExpInfo.getExpansionLocEnd(); | |||
1086 | return true; | |||
1087 | } | |||
1088 | ||||
1089 | //===----------------------------------------------------------------------===// | |||
1090 | // Queries about the code at a SourceLocation. | |||
1091 | //===----------------------------------------------------------------------===// | |||
1092 | ||||
1093 | /// getCharacterData - Return a pointer to the start of the specified location | |||
1094 | /// in the appropriate MemoryBuffer. | |||
1095 | const char *SourceManager::getCharacterData(SourceLocation SL, | |||
1096 | bool *Invalid) const { | |||
1097 | // Note that this is a hot function in the getSpelling() path, which is | |||
1098 | // heavily used by -E mode. | |||
1099 | std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL); | |||
1100 | ||||
1101 | // Note that calling 'getBuffer()' may lazily page in a source file. | |||
1102 | bool CharDataInvalid = false; | |||
1103 | const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid); | |||
1104 | if (CharDataInvalid || !Entry.isFile()) { | |||
1105 | if (Invalid) | |||
1106 | *Invalid = true; | |||
1107 | ||||
1108 | return "<<<<INVALID BUFFER>>>>"; | |||
1109 | } | |||
1110 | llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer( | |||
1111 | Diag, *this, SourceLocation(), &CharDataInvalid); | |||
1112 | if (Invalid) | |||
1113 | *Invalid = CharDataInvalid; | |||
1114 | return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second); | |||
1115 | } | |||
1116 | ||||
1117 | /// getColumnNumber - Return the column # for the specified file position. | |||
1118 | /// this is significantly cheaper to compute than the line number. | |||
1119 | unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos, | |||
1120 | bool *Invalid) const { | |||
1121 | bool MyInvalid = false; | |||
1122 | llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid); | |||
1123 | if (Invalid) | |||
1124 | *Invalid = MyInvalid; | |||
1125 | ||||
1126 | if (MyInvalid) | |||
1127 | return 1; | |||
1128 | ||||
1129 | // It is okay to request a position just past the end of the buffer. | |||
1130 | if (FilePos > MemBuf->getBufferSize()) { | |||
1131 | if (Invalid) | |||
1132 | *Invalid = true; | |||
1133 | return 1; | |||
1134 | } | |||
1135 | ||||
1136 | const char *Buf = MemBuf->getBufferStart(); | |||
1137 | // See if we just calculated the line number for this FilePos and can use | |||
1138 | // that to lookup the start of the line instead of searching for it. | |||
1139 | if (LastLineNoFileIDQuery == FID && | |||
1140 | LastLineNoContentCache->SourceLineCache != nullptr && | |||
1141 | LastLineNoResult < LastLineNoContentCache->NumLines) { | |||
1142 | unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache; | |||
1143 | unsigned LineStart = SourceLineCache[LastLineNoResult - 1]; | |||
1144 | unsigned LineEnd = SourceLineCache[LastLineNoResult]; | |||
1145 | if (FilePos >= LineStart && FilePos < LineEnd) { | |||
1146 | // LineEnd is the LineStart of the next line. | |||
1147 | // A line ends with separator LF or CR+LF on Windows. | |||
1148 | // FilePos might point to the last separator, | |||
1149 | // but we need a column number at most 1 + the last column. | |||
1150 | if (FilePos + 1 == LineEnd && FilePos > LineStart) { | |||
1151 | if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n') | |||
1152 | --FilePos; | |||
1153 | } | |||
1154 | return FilePos - LineStart + 1; | |||
1155 | } | |||
1156 | } | |||
1157 | ||||
1158 | unsigned LineStart = FilePos; | |||
1159 | while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r') | |||
1160 | --LineStart; | |||
1161 | return FilePos-LineStart+1; | |||
1162 | } | |||
1163 | ||||
1164 | // isInvalid - Return the result of calling loc.isInvalid(), and | |||
1165 | // if Invalid is not null, set its value to same. | |||
1166 | template<typename LocType> | |||
1167 | static bool isInvalid(LocType Loc, bool *Invalid) { | |||
1168 | bool MyInvalid = Loc.isInvalid(); | |||
1169 | if (Invalid) | |||
1170 | *Invalid = MyInvalid; | |||
1171 | return MyInvalid; | |||
1172 | } | |||
1173 | ||||
1174 | unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc, | |||
1175 | bool *Invalid) const { | |||
1176 | if (isInvalid(Loc, Invalid)) return 0; | |||
1177 | std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); | |||
1178 | return getColumnNumber(LocInfo.first, LocInfo.second, Invalid); | |||
1179 | } | |||
1180 | ||||
1181 | unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc, | |||
1182 | bool *Invalid) const { | |||
1183 | if (isInvalid(Loc, Invalid)) return 0; | |||
1184 | std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); | |||
1185 | return getColumnNumber(LocInfo.first, LocInfo.second, Invalid); | |||
1186 | } | |||
1187 | ||||
1188 | unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc, | |||
1189 | bool *Invalid) const { | |||
1190 | PresumedLoc PLoc = getPresumedLoc(Loc); | |||
1191 | if (isInvalid(PLoc, Invalid)) return 0; | |||
1192 | return PLoc.getColumn(); | |||
1193 | } | |||
1194 | ||||
1195 | #ifdef __SSE2__1 | |||
1196 | #include <emmintrin.h> | |||
1197 | #endif | |||
1198 | ||||
1199 | static LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) void | |||
1200 | ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI, | |||
1201 | llvm::BumpPtrAllocator &Alloc, | |||
1202 | const SourceManager &SM, bool &Invalid); | |||
1203 | static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI, | |||
1204 | llvm::BumpPtrAllocator &Alloc, | |||
1205 | const SourceManager &SM, bool &Invalid) { | |||
1206 | // Note that calling 'getBuffer()' may lazily page in the file. | |||
1207 | MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid); | |||
1208 | if (Invalid) | |||
1209 | return; | |||
1210 | ||||
1211 | // Find the file offsets of all of the *physical* source lines. This does | |||
1212 | // not look at trigraphs, escaped newlines, or anything else tricky. | |||
1213 | SmallVector<unsigned, 256> LineOffsets; | |||
1214 | ||||
1215 | // Line #1 starts at char 0. | |||
1216 | LineOffsets.push_back(0); | |||
1217 | ||||
1218 | const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart(); | |||
1219 | const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd(); | |||
1220 | unsigned Offs = 0; | |||
1221 | while (true) { | |||
1222 | // Skip over the contents of the line. | |||
1223 | const unsigned char *NextBuf = (const unsigned char *)Buf; | |||
1224 | ||||
1225 | #ifdef __SSE2__1 | |||
1226 | // Try to skip to the next newline using SSE instructions. This is very | |||
1227 | // performance sensitive for programs with lots of diagnostics and in -E | |||
1228 | // mode. | |||
1229 | __m128i CRs = _mm_set1_epi8('\r'); | |||
1230 | __m128i LFs = _mm_set1_epi8('\n'); | |||
1231 | ||||
1232 | // First fix up the alignment to 16 bytes. | |||
1233 | while (((uintptr_t)NextBuf & 0xF) != 0) { | |||
1234 | if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0') | |||
1235 | goto FoundSpecialChar; | |||
1236 | ++NextBuf; | |||
1237 | } | |||
1238 | ||||
1239 | // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'. | |||
1240 | while (NextBuf+16 <= End) { | |||
1241 | const __m128i Chunk = *(const __m128i*)NextBuf; | |||
1242 | __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs), | |||
1243 | _mm_cmpeq_epi8(Chunk, LFs)); | |||
1244 | unsigned Mask = _mm_movemask_epi8(Cmp); | |||
1245 | ||||
1246 | // If we found a newline, adjust the pointer and jump to the handling code. | |||
1247 | if (Mask != 0) { | |||
1248 | NextBuf += llvm::countTrailingZeros(Mask); | |||
1249 | goto FoundSpecialChar; | |||
1250 | } | |||
1251 | NextBuf += 16; | |||
1252 | } | |||
1253 | #endif | |||
1254 | ||||
1255 | while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0') | |||
1256 | ++NextBuf; | |||
1257 | ||||
1258 | #ifdef __SSE2__1 | |||
1259 | FoundSpecialChar: | |||
1260 | #endif | |||
1261 | Offs += NextBuf-Buf; | |||
1262 | Buf = NextBuf; | |||
1263 | ||||
1264 | if (Buf[0] == '\n' || Buf[0] == '\r') { | |||
1265 | // If this is \n\r or \r\n, skip both characters. | |||
1266 | if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) { | |||
1267 | ++Offs; | |||
1268 | ++Buf; | |||
1269 | } | |||
1270 | ++Offs; | |||
1271 | ++Buf; | |||
1272 | LineOffsets.push_back(Offs); | |||
1273 | } else { | |||
1274 | // Otherwise, this is a null. If end of file, exit. | |||
1275 | if (Buf == End) break; | |||
1276 | // Otherwise, skip the null. | |||
1277 | ++Offs; | |||
1278 | ++Buf; | |||
1279 | } | |||
1280 | } | |||
1281 | ||||
1282 | // Copy the offsets into the FileInfo structure. | |||
1283 | FI->NumLines = LineOffsets.size(); | |||
1284 | FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size()); | |||
1285 | std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache); | |||
1286 | } | |||
1287 | ||||
1288 | /// getLineNumber - Given a SourceLocation, return the spelling line number | |||
1289 | /// for the position indicated. This requires building and caching a table of | |||
1290 | /// line offsets for the MemoryBuffer, so this is not cheap: use only when | |||
1291 | /// about to emit a diagnostic. | |||
1292 | unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, | |||
1293 | bool *Invalid) const { | |||
1294 | if (FID.isInvalid()) { | |||
1295 | if (Invalid) | |||
1296 | *Invalid = true; | |||
1297 | return 1; | |||
1298 | } | |||
1299 | ||||
1300 | ContentCache *Content; | |||
1301 | if (LastLineNoFileIDQuery == FID) | |||
1302 | Content = LastLineNoContentCache; | |||
1303 | else { | |||
1304 | bool MyInvalid = false; | |||
1305 | const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid); | |||
1306 | if (MyInvalid || !Entry.isFile()) { | |||
1307 | if (Invalid) | |||
1308 | *Invalid = true; | |||
1309 | return 1; | |||
1310 | } | |||
1311 | ||||
1312 | Content = const_cast<ContentCache*>(Entry.getFile().getContentCache()); | |||
1313 | } | |||
1314 | ||||
1315 | // If this is the first use of line information for this buffer, compute the | |||
1316 | /// SourceLineCache for it on demand. | |||
1317 | if (!Content->SourceLineCache) { | |||
1318 | bool MyInvalid = false; | |||
1319 | ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid); | |||
1320 | if (Invalid) | |||
1321 | *Invalid = MyInvalid; | |||
1322 | if (MyInvalid) | |||
1323 | return 1; | |||
1324 | } else if (Invalid) | |||
1325 | *Invalid = false; | |||
1326 | ||||
1327 | // Okay, we know we have a line number table. Do a binary search to find the | |||
1328 | // line number that this character position lands on. | |||
1329 | unsigned *SourceLineCache = Content->SourceLineCache; | |||
1330 | unsigned *SourceLineCacheStart = SourceLineCache; | |||
1331 | unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines; | |||
1332 | ||||
1333 | unsigned QueriedFilePos = FilePos+1; | |||
1334 | ||||
1335 | // FIXME: I would like to be convinced that this code is worth being as | |||
1336 | // complicated as it is, binary search isn't that slow. | |||
1337 | // | |||
1338 | // If it is worth being optimized, then in my opinion it could be more | |||
1339 | // performant, simpler, and more obviously correct by just "galloping" outward | |||
1340 | // from the queried file position. In fact, this could be incorporated into a | |||
1341 | // generic algorithm such as lower_bound_with_hint. | |||
1342 | // | |||
1343 | // If someone gives me a test case where this matters, and I will do it! - DWD | |||
1344 | ||||
1345 | // If the previous query was to the same file, we know both the file pos from | |||
1346 | // that query and the line number returned. This allows us to narrow the | |||
1347 | // search space from the entire file to something near the match. | |||
1348 | if (LastLineNoFileIDQuery == FID) { | |||
1349 | if (QueriedFilePos >= LastLineNoFilePos) { | |||
1350 | // FIXME: Potential overflow? | |||
1351 | SourceLineCache = SourceLineCache+LastLineNoResult-1; | |||
1352 | ||||
1353 | // The query is likely to be nearby the previous one. Here we check to | |||
1354 | // see if it is within 5, 10 or 20 lines. It can be far away in cases | |||
1355 | // where big comment blocks and vertical whitespace eat up lines but | |||
1356 | // contribute no tokens. | |||
1357 | if (SourceLineCache+5 < SourceLineCacheEnd) { | |||
1358 | if (SourceLineCache[5] > QueriedFilePos) | |||
1359 | SourceLineCacheEnd = SourceLineCache+5; | |||
1360 | else if (SourceLineCache+10 < SourceLineCacheEnd) { | |||
1361 | if (SourceLineCache[10] > QueriedFilePos) | |||
1362 | SourceLineCacheEnd = SourceLineCache+10; | |||
1363 | else if (SourceLineCache+20 < SourceLineCacheEnd) { | |||
1364 | if (SourceLineCache[20] > QueriedFilePos) | |||
1365 | SourceLineCacheEnd = SourceLineCache+20; | |||
1366 | } | |||
1367 | } | |||
1368 | } | |||
1369 | } else { | |||
1370 | if (LastLineNoResult < Content->NumLines) | |||
1371 | SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1; | |||
1372 | } | |||
1373 | } | |||
1374 | ||||
1375 | unsigned *Pos | |||
1376 | = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos); | |||
1377 | unsigned LineNo = Pos-SourceLineCacheStart; | |||
1378 | ||||
1379 | LastLineNoFileIDQuery = FID; | |||
1380 | LastLineNoContentCache = Content; | |||
1381 | LastLineNoFilePos = QueriedFilePos; | |||
1382 | LastLineNoResult = LineNo; | |||
1383 | return LineNo; | |||
1384 | } | |||
1385 | ||||
1386 | unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc, | |||
1387 | bool *Invalid) const { | |||
1388 | if (isInvalid(Loc, Invalid)) return 0; | |||
1389 | std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); | |||
1390 | return getLineNumber(LocInfo.first, LocInfo.second); | |||
1391 | } | |||
1392 | unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc, | |||
1393 | bool *Invalid) const { | |||
1394 | if (isInvalid(Loc, Invalid)) return 0; | |||
1395 | std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); | |||
1396 | return getLineNumber(LocInfo.first, LocInfo.second); | |||
1397 | } | |||
1398 | unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc, | |||
1399 | bool *Invalid) const { | |||
1400 | PresumedLoc PLoc = getPresumedLoc(Loc); | |||
1401 | if (isInvalid(PLoc, Invalid)) return 0; | |||
1402 | return PLoc.getLine(); | |||
1403 | } | |||
1404 | ||||
1405 | /// getFileCharacteristic - return the file characteristic of the specified | |||
1406 | /// source location, indicating whether this is a normal file, a system | |||
1407 | /// header, or an "implicit extern C" system header. | |||
1408 | /// | |||
1409 | /// This state can be modified with flags on GNU linemarker directives like: | |||
1410 | /// # 4 "foo.h" 3 | |||
1411 | /// which changes all source locations in the current file after that to be | |||
1412 | /// considered to be from a system header. | |||
1413 | SrcMgr::CharacteristicKind | |||
1414 | SourceManager::getFileCharacteristic(SourceLocation Loc) const { | |||
1415 | assert(Loc.isValid() && "Can't get file characteristic of invalid loc!")(static_cast <bool> (Loc.isValid() && "Can't get file characteristic of invalid loc!" ) ? void (0) : __assert_fail ("Loc.isValid() && \"Can't get file characteristic of invalid loc!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 1415, __extension__ __PRETTY_FUNCTION__)); | |||
1416 | std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); | |||
1417 | bool Invalid = false; | |||
1418 | const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid); | |||
1419 | if (Invalid || !SEntry.isFile()) | |||
1420 | return C_User; | |||
1421 | ||||
1422 | const SrcMgr::FileInfo &FI = SEntry.getFile(); | |||
1423 | ||||
1424 | // If there are no #line directives in this file, just return the whole-file | |||
1425 | // state. | |||
1426 | if (!FI.hasLineDirectives()) | |||
1427 | return FI.getFileCharacteristic(); | |||
1428 | ||||
1429 | assert(LineTable && "Can't have linetable entries without a LineTable!")(static_cast <bool> (LineTable && "Can't have linetable entries without a LineTable!" ) ? void (0) : __assert_fail ("LineTable && \"Can't have linetable entries without a LineTable!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 1429, __extension__ __PRETTY_FUNCTION__)); | |||
1430 | // See if there is a #line directive before the location. | |||
1431 | const LineEntry *Entry = | |||
1432 | LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second); | |||
1433 | ||||
1434 | // If this is before the first line marker, use the file characteristic. | |||
1435 | if (!Entry) | |||
1436 | return FI.getFileCharacteristic(); | |||
1437 | ||||
1438 | return Entry->FileKind; | |||
1439 | } | |||
1440 | ||||
1441 | /// Return the filename or buffer identifier of the buffer the location is in. | |||
1442 | /// Note that this name does not respect \#line directives. Use getPresumedLoc | |||
1443 | /// for normal clients. | |||
1444 | StringRef SourceManager::getBufferName(SourceLocation Loc, | |||
1445 | bool *Invalid) const { | |||
1446 | if (isInvalid(Loc, Invalid)) return "<invalid loc>"; | |||
1447 | ||||
1448 | return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier(); | |||
1449 | } | |||
1450 | ||||
1451 | /// getPresumedLoc - This method returns the "presumed" location of a | |||
1452 | /// SourceLocation specifies. A "presumed location" can be modified by \#line | |||
1453 | /// or GNU line marker directives. This provides a view on the data that a | |||
1454 | /// user should see in diagnostics, for example. | |||
1455 | /// | |||
1456 | /// Note that a presumed location is always given as the expansion point of an | |||
1457 | /// expansion location, not at the spelling location. | |||
1458 | PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc, | |||
1459 | bool UseLineDirectives) const { | |||
1460 | if (Loc.isInvalid()) return PresumedLoc(); | |||
1461 | ||||
1462 | // Presumed locations are always for expansion points. | |||
1463 | std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); | |||
1464 | ||||
1465 | bool Invalid = false; | |||
1466 | const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); | |||
1467 | if (Invalid || !Entry.isFile()) | |||
1468 | return PresumedLoc(); | |||
1469 | ||||
1470 | const SrcMgr::FileInfo &FI = Entry.getFile(); | |||
1471 | const SrcMgr::ContentCache *C = FI.getContentCache(); | |||
1472 | ||||
1473 | // To get the source name, first consult the FileEntry (if one exists) | |||
1474 | // before the MemBuffer as this will avoid unnecessarily paging in the | |||
1475 | // MemBuffer. | |||
1476 | StringRef Filename; | |||
1477 | if (C->OrigEntry) | |||
1478 | Filename = C->OrigEntry->getName(); | |||
1479 | else | |||
1480 | Filename = C->getBuffer(Diag, *this)->getBufferIdentifier(); | |||
1481 | ||||
1482 | unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid); | |||
1483 | if (Invalid) | |||
1484 | return PresumedLoc(); | |||
1485 | unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid); | |||
1486 | if (Invalid) | |||
1487 | return PresumedLoc(); | |||
1488 | ||||
1489 | SourceLocation IncludeLoc = FI.getIncludeLoc(); | |||
1490 | ||||
1491 | // If we have #line directives in this file, update and overwrite the physical | |||
1492 | // location info if appropriate. | |||
1493 | if (UseLineDirectives && FI.hasLineDirectives()) { | |||
1494 | assert(LineTable && "Can't have linetable entries without a LineTable!")(static_cast <bool> (LineTable && "Can't have linetable entries without a LineTable!" ) ? void (0) : __assert_fail ("LineTable && \"Can't have linetable entries without a LineTable!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 1494, __extension__ __PRETTY_FUNCTION__)); | |||
1495 | // See if there is a #line directive before this. If so, get it. | |||
1496 | if (const LineEntry *Entry = | |||
1497 | LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) { | |||
1498 | // If the LineEntry indicates a filename, use it. | |||
1499 | if (Entry->FilenameID != -1) | |||
1500 | Filename = LineTable->getFilename(Entry->FilenameID); | |||
1501 | ||||
1502 | // Use the line number specified by the LineEntry. This line number may | |||
1503 | // be multiple lines down from the line entry. Add the difference in | |||
1504 | // physical line numbers from the query point and the line marker to the | |||
1505 | // total. | |||
1506 | unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset); | |||
1507 | LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1); | |||
1508 | ||||
1509 | // Note that column numbers are not molested by line markers. | |||
1510 | ||||
1511 | // Handle virtual #include manipulation. | |||
1512 | if (Entry->IncludeOffset) { | |||
1513 | IncludeLoc = getLocForStartOfFile(LocInfo.first); | |||
1514 | IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset); | |||
1515 | } | |||
1516 | } | |||
1517 | } | |||
1518 | ||||
1519 | return PresumedLoc(Filename.data(), LineNo, ColNo, IncludeLoc); | |||
1520 | } | |||
1521 | ||||
1522 | /// Returns whether the PresumedLoc for a given SourceLocation is | |||
1523 | /// in the main file. | |||
1524 | /// | |||
1525 | /// This computes the "presumed" location for a SourceLocation, then checks | |||
1526 | /// whether it came from a file other than the main file. This is different | |||
1527 | /// from isWrittenInMainFile() because it takes line marker directives into | |||
1528 | /// account. | |||
1529 | bool SourceManager::isInMainFile(SourceLocation Loc) const { | |||
1530 | if (Loc.isInvalid()) return false; | |||
1531 | ||||
1532 | // Presumed locations are always for expansion points. | |||
1533 | std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); | |||
1534 | ||||
1535 | bool Invalid = false; | |||
1536 | const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); | |||
1537 | if (Invalid || !Entry.isFile()) | |||
1538 | return false; | |||
1539 | ||||
1540 | const SrcMgr::FileInfo &FI = Entry.getFile(); | |||
1541 | ||||
1542 | // Check if there is a line directive for this location. | |||
1543 | if (FI.hasLineDirectives()) | |||
1544 | if (const LineEntry *Entry = | |||
1545 | LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) | |||
1546 | if (Entry->IncludeOffset) | |||
1547 | return false; | |||
1548 | ||||
1549 | return FI.getIncludeLoc().isInvalid(); | |||
1550 | } | |||
1551 | ||||
1552 | /// The size of the SLocEntry that \p FID represents. | |||
1553 | unsigned SourceManager::getFileIDSize(FileID FID) const { | |||
1554 | bool Invalid = false; | |||
1555 | const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid); | |||
1556 | if (Invalid) | |||
1557 | return 0; | |||
1558 | ||||
1559 | int ID = FID.ID; | |||
1560 | unsigned NextOffset; | |||
1561 | if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size())) | |||
1562 | NextOffset = getNextLocalOffset(); | |||
1563 | else if (ID+1 == -1) | |||
1564 | NextOffset = MaxLoadedOffset; | |||
1565 | else | |||
1566 | NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset(); | |||
1567 | ||||
1568 | return NextOffset - Entry.getOffset() - 1; | |||
1569 | } | |||
1570 | ||||
1571 | //===----------------------------------------------------------------------===// | |||
1572 | // Other miscellaneous methods. | |||
1573 | //===----------------------------------------------------------------------===// | |||
1574 | ||||
1575 | /// Retrieve the inode for the given file entry, if possible. | |||
1576 | /// | |||
1577 | /// This routine involves a system call, and therefore should only be used | |||
1578 | /// in non-performance-critical code. | |||
1579 | static Optional<llvm::sys::fs::UniqueID> | |||
1580 | getActualFileUID(const FileEntry *File) { | |||
1581 | if (!File) | |||
1582 | return None; | |||
1583 | ||||
1584 | llvm::sys::fs::UniqueID ID; | |||
1585 | if (llvm::sys::fs::getUniqueID(File->getName(), ID)) | |||
1586 | return None; | |||
1587 | ||||
1588 | return ID; | |||
1589 | } | |||
1590 | ||||
1591 | /// Get the source location for the given file:line:col triplet. | |||
1592 | /// | |||
1593 | /// If the source file is included multiple times, the source location will | |||
1594 | /// be based upon an arbitrary inclusion. | |||
1595 | SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile, | |||
1596 | unsigned Line, | |||
1597 | unsigned Col) const { | |||
1598 | assert(SourceFile && "Null source file!")(static_cast <bool> (SourceFile && "Null source file!" ) ? void (0) : __assert_fail ("SourceFile && \"Null source file!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 1598, __extension__ __PRETTY_FUNCTION__)); | |||
1599 | assert(Line && Col && "Line and column should start from 1!")(static_cast <bool> (Line && Col && "Line and column should start from 1!" ) ? void (0) : __assert_fail ("Line && Col && \"Line and column should start from 1!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 1599, __extension__ __PRETTY_FUNCTION__)); | |||
1600 | ||||
1601 | FileID FirstFID = translateFile(SourceFile); | |||
1602 | return translateLineCol(FirstFID, Line, Col); | |||
1603 | } | |||
1604 | ||||
1605 | /// Get the FileID for the given file. | |||
1606 | /// | |||
1607 | /// If the source file is included multiple times, the FileID will be the | |||
1608 | /// first inclusion. | |||
1609 | FileID SourceManager::translateFile(const FileEntry *SourceFile) const { | |||
1610 | assert(SourceFile && "Null source file!")(static_cast <bool> (SourceFile && "Null source file!" ) ? void (0) : __assert_fail ("SourceFile && \"Null source file!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 1610, __extension__ __PRETTY_FUNCTION__)); | |||
1611 | ||||
1612 | // Find the first file ID that corresponds to the given file. | |||
1613 | FileID FirstFID; | |||
1614 | ||||
1615 | // First, check the main file ID, since it is common to look for a | |||
1616 | // location in the main file. | |||
1617 | Optional<llvm::sys::fs::UniqueID> SourceFileUID; | |||
1618 | Optional<StringRef> SourceFileName; | |||
1619 | if (MainFileID.isValid()) { | |||
1620 | bool Invalid = false; | |||
1621 | const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid); | |||
1622 | if (Invalid) | |||
1623 | return FileID(); | |||
1624 | ||||
1625 | if (MainSLoc.isFile()) { | |||
1626 | const ContentCache *MainContentCache | |||
1627 | = MainSLoc.getFile().getContentCache(); | |||
1628 | if (!MainContentCache) { | |||
1629 | // Can't do anything | |||
1630 | } else if (MainContentCache->OrigEntry == SourceFile) { | |||
1631 | FirstFID = MainFileID; | |||
1632 | } else { | |||
1633 | // Fall back: check whether we have the same base name and inode | |||
1634 | // as the main file. | |||
1635 | const FileEntry *MainFile = MainContentCache->OrigEntry; | |||
1636 | SourceFileName = llvm::sys::path::filename(SourceFile->getName()); | |||
1637 | if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) { | |||
1638 | SourceFileUID = getActualFileUID(SourceFile); | |||
1639 | if (SourceFileUID) { | |||
1640 | if (Optional<llvm::sys::fs::UniqueID> MainFileUID = | |||
1641 | getActualFileUID(MainFile)) { | |||
1642 | if (*SourceFileUID == *MainFileUID) { | |||
1643 | FirstFID = MainFileID; | |||
1644 | SourceFile = MainFile; | |||
1645 | } | |||
1646 | } | |||
1647 | } | |||
1648 | } | |||
1649 | } | |||
1650 | } | |||
1651 | } | |||
1652 | ||||
1653 | if (FirstFID.isInvalid()) { | |||
1654 | // The location we're looking for isn't in the main file; look | |||
1655 | // through all of the local source locations. | |||
1656 | for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) { | |||
1657 | bool Invalid = false; | |||
1658 | const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid); | |||
1659 | if (Invalid) | |||
1660 | return FileID(); | |||
1661 | ||||
1662 | if (SLoc.isFile() && | |||
1663 | SLoc.getFile().getContentCache() && | |||
1664 | SLoc.getFile().getContentCache()->OrigEntry == SourceFile) { | |||
1665 | FirstFID = FileID::get(I); | |||
1666 | break; | |||
1667 | } | |||
1668 | } | |||
1669 | // If that still didn't help, try the modules. | |||
1670 | if (FirstFID.isInvalid()) { | |||
1671 | for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) { | |||
1672 | const SLocEntry &SLoc = getLoadedSLocEntry(I); | |||
1673 | if (SLoc.isFile() && | |||
1674 | SLoc.getFile().getContentCache() && | |||
1675 | SLoc.getFile().getContentCache()->OrigEntry == SourceFile) { | |||
1676 | FirstFID = FileID::get(-int(I) - 2); | |||
1677 | break; | |||
1678 | } | |||
1679 | } | |||
1680 | } | |||
1681 | } | |||
1682 | ||||
1683 | // If we haven't found what we want yet, try again, but this time stat() | |||
1684 | // each of the files in case the files have changed since we originally | |||
1685 | // parsed the file. | |||
1686 | if (FirstFID.isInvalid() && | |||
1687 | (SourceFileName || | |||
1688 | (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) && | |||
1689 | (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) { | |||
1690 | bool Invalid = false; | |||
1691 | for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) { | |||
1692 | FileID IFileID; | |||
1693 | IFileID.ID = I; | |||
1694 | const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid); | |||
1695 | if (Invalid) | |||
1696 | return FileID(); | |||
1697 | ||||
1698 | if (SLoc.isFile()) { | |||
1699 | const ContentCache *FileContentCache | |||
1700 | = SLoc.getFile().getContentCache(); | |||
1701 | const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry | |||
1702 | : nullptr; | |||
1703 | if (Entry && | |||
1704 | *SourceFileName == llvm::sys::path::filename(Entry->getName())) { | |||
1705 | if (Optional<llvm::sys::fs::UniqueID> EntryUID = | |||
1706 | getActualFileUID(Entry)) { | |||
1707 | if (*SourceFileUID == *EntryUID) { | |||
1708 | FirstFID = FileID::get(I); | |||
1709 | SourceFile = Entry; | |||
1710 | break; | |||
1711 | } | |||
1712 | } | |||
1713 | } | |||
1714 | } | |||
1715 | } | |||
1716 | } | |||
1717 | ||||
1718 | (void) SourceFile; | |||
1719 | return FirstFID; | |||
1720 | } | |||
1721 | ||||
1722 | /// Get the source location in \arg FID for the given line:col. | |||
1723 | /// Returns null location if \arg FID is not a file SLocEntry. | |||
1724 | SourceLocation SourceManager::translateLineCol(FileID FID, | |||
1725 | unsigned Line, | |||
1726 | unsigned Col) const { | |||
1727 | // Lines are used as a one-based index into a zero-based array. This assert | |||
1728 | // checks for possible buffer underruns. | |||
1729 | assert(Line && Col && "Line and column should start from 1!")(static_cast <bool> (Line && Col && "Line and column should start from 1!" ) ? void (0) : __assert_fail ("Line && Col && \"Line and column should start from 1!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 1729, __extension__ __PRETTY_FUNCTION__)); | |||
1730 | ||||
1731 | if (FID.isInvalid()) | |||
1732 | return SourceLocation(); | |||
1733 | ||||
1734 | bool Invalid = false; | |||
1735 | const SLocEntry &Entry = getSLocEntry(FID, &Invalid); | |||
1736 | if (Invalid) | |||
1737 | return SourceLocation(); | |||
1738 | ||||
1739 | if (!Entry.isFile()) | |||
1740 | return SourceLocation(); | |||
1741 | ||||
1742 | SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset()); | |||
1743 | ||||
1744 | if (Line == 1 && Col == 1) | |||
1745 | return FileLoc; | |||
1746 | ||||
1747 | ContentCache *Content | |||
1748 | = const_cast<ContentCache *>(Entry.getFile().getContentCache()); | |||
1749 | if (!Content) | |||
1750 | return SourceLocation(); | |||
1751 | ||||
1752 | // If this is the first use of line information for this buffer, compute the | |||
1753 | // SourceLineCache for it on demand. | |||
1754 | if (!Content->SourceLineCache) { | |||
1755 | bool MyInvalid = false; | |||
1756 | ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid); | |||
1757 | if (MyInvalid) | |||
1758 | return SourceLocation(); | |||
1759 | } | |||
1760 | ||||
1761 | if (Line > Content->NumLines) { | |||
1762 | unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize(); | |||
1763 | if (Size > 0) | |||
1764 | --Size; | |||
1765 | return FileLoc.getLocWithOffset(Size); | |||
1766 | } | |||
1767 | ||||
1768 | llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this); | |||
1769 | unsigned FilePos = Content->SourceLineCache[Line - 1]; | |||
1770 | const char *Buf = Buffer->getBufferStart() + FilePos; | |||
1771 | unsigned BufLength = Buffer->getBufferSize() - FilePos; | |||
1772 | if (BufLength == 0) | |||
1773 | return FileLoc.getLocWithOffset(FilePos); | |||
1774 | ||||
1775 | unsigned i = 0; | |||
1776 | ||||
1777 | // Check that the given column is valid. | |||
1778 | while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r') | |||
1779 | ++i; | |||
1780 | return FileLoc.getLocWithOffset(FilePos + i); | |||
1781 | } | |||
1782 | ||||
1783 | /// Compute a map of macro argument chunks to their expanded source | |||
1784 | /// location. Chunks that are not part of a macro argument will map to an | |||
1785 | /// invalid source location. e.g. if a file contains one macro argument at | |||
1786 | /// offset 100 with length 10, this is how the map will be formed: | |||
1787 | /// 0 -> SourceLocation() | |||
1788 | /// 100 -> Expanded macro arg location | |||
1789 | /// 110 -> SourceLocation() | |||
1790 | void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache, | |||
1791 | FileID FID) const { | |||
1792 | assert(FID.isValid())(static_cast <bool> (FID.isValid()) ? void (0) : __assert_fail ("FID.isValid()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 1792, __extension__ __PRETTY_FUNCTION__)); | |||
1793 | ||||
1794 | // Initially no macro argument chunk is present. | |||
1795 | MacroArgsCache.insert(std::make_pair(0, SourceLocation())); | |||
1796 | ||||
1797 | int ID = FID.ID; | |||
1798 | while (true) { | |||
1799 | ++ID; | |||
1800 | // Stop if there are no more FileIDs to check. | |||
1801 | if (ID > 0) { | |||
1802 | if (unsigned(ID) >= local_sloc_entry_size()) | |||
1803 | return; | |||
1804 | } else if (ID == -1) { | |||
1805 | return; | |||
1806 | } | |||
1807 | ||||
1808 | bool Invalid = false; | |||
1809 | const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid); | |||
1810 | if (Invalid) | |||
1811 | return; | |||
1812 | if (Entry.isFile()) { | |||
1813 | SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc(); | |||
1814 | if (IncludeLoc.isInvalid()) | |||
1815 | continue; | |||
1816 | if (!isInFileID(IncludeLoc, FID)) | |||
1817 | return; // No more files/macros that may be "contained" in this file. | |||
1818 | ||||
1819 | // Skip the files/macros of the #include'd file, we only care about macros | |||
1820 | // that lexed macro arguments from our file. | |||
1821 | if (Entry.getFile().NumCreatedFIDs) | |||
1822 | ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/; | |||
1823 | continue; | |||
1824 | } | |||
1825 | ||||
1826 | const ExpansionInfo &ExpInfo = Entry.getExpansion(); | |||
1827 | ||||
1828 | if (ExpInfo.getExpansionLocStart().isFileID()) { | |||
1829 | if (!isInFileID(ExpInfo.getExpansionLocStart(), FID)) | |||
1830 | return; // No more files/macros that may be "contained" in this file. | |||
1831 | } | |||
1832 | ||||
1833 | if (!ExpInfo.isMacroArgExpansion()) | |||
1834 | continue; | |||
1835 | ||||
1836 | associateFileChunkWithMacroArgExp(MacroArgsCache, FID, | |||
1837 | ExpInfo.getSpellingLoc(), | |||
1838 | SourceLocation::getMacroLoc(Entry.getOffset()), | |||
1839 | getFileIDSize(FileID::get(ID))); | |||
1840 | } | |||
1841 | } | |||
1842 | ||||
1843 | void SourceManager::associateFileChunkWithMacroArgExp( | |||
1844 | MacroArgsMap &MacroArgsCache, | |||
1845 | FileID FID, | |||
1846 | SourceLocation SpellLoc, | |||
1847 | SourceLocation ExpansionLoc, | |||
1848 | unsigned ExpansionLength) const { | |||
1849 | if (!SpellLoc.isFileID()) { | |||
1850 | unsigned SpellBeginOffs = SpellLoc.getOffset(); | |||
1851 | unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength; | |||
1852 | ||||
1853 | // The spelling range for this macro argument expansion can span multiple | |||
1854 | // consecutive FileID entries. Go through each entry contained in the | |||
1855 | // spelling range and if one is itself a macro argument expansion, recurse | |||
1856 | // and associate the file chunk that it represents. | |||
1857 | ||||
1858 | FileID SpellFID; // Current FileID in the spelling range. | |||
1859 | unsigned SpellRelativeOffs; | |||
1860 | std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc); | |||
1861 | while (true) { | |||
1862 | const SLocEntry &Entry = getSLocEntry(SpellFID); | |||
1863 | unsigned SpellFIDBeginOffs = Entry.getOffset(); | |||
1864 | unsigned SpellFIDSize = getFileIDSize(SpellFID); | |||
1865 | unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize; | |||
1866 | const ExpansionInfo &Info = Entry.getExpansion(); | |||
1867 | if (Info.isMacroArgExpansion()) { | |||
1868 | unsigned CurrSpellLength; | |||
1869 | if (SpellFIDEndOffs < SpellEndOffs) | |||
1870 | CurrSpellLength = SpellFIDSize - SpellRelativeOffs; | |||
1871 | else | |||
1872 | CurrSpellLength = ExpansionLength; | |||
1873 | associateFileChunkWithMacroArgExp(MacroArgsCache, FID, | |||
1874 | Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs), | |||
1875 | ExpansionLoc, CurrSpellLength); | |||
1876 | } | |||
1877 | ||||
1878 | if (SpellFIDEndOffs >= SpellEndOffs) | |||
1879 | return; // we covered all FileID entries in the spelling range. | |||
1880 | ||||
1881 | // Move to the next FileID entry in the spelling range. | |||
1882 | unsigned advance = SpellFIDSize - SpellRelativeOffs + 1; | |||
1883 | ExpansionLoc = ExpansionLoc.getLocWithOffset(advance); | |||
1884 | ExpansionLength -= advance; | |||
1885 | ++SpellFID.ID; | |||
1886 | SpellRelativeOffs = 0; | |||
1887 | } | |||
1888 | } | |||
1889 | ||||
1890 | assert(SpellLoc.isFileID())(static_cast <bool> (SpellLoc.isFileID()) ? void (0) : __assert_fail ("SpellLoc.isFileID()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 1890, __extension__ __PRETTY_FUNCTION__)); | |||
1891 | ||||
1892 | unsigned BeginOffs; | |||
1893 | if (!isInFileID(SpellLoc, FID, &BeginOffs)) | |||
1894 | return; | |||
1895 | ||||
1896 | unsigned EndOffs = BeginOffs + ExpansionLength; | |||
1897 | ||||
1898 | // Add a new chunk for this macro argument. A previous macro argument chunk | |||
1899 | // may have been lexed again, so e.g. if the map is | |||
1900 | // 0 -> SourceLocation() | |||
1901 | // 100 -> Expanded loc #1 | |||
1902 | // 110 -> SourceLocation() | |||
1903 | // and we found a new macro FileID that lexed from offset 105 with length 3, | |||
1904 | // the new map will be: | |||
1905 | // 0 -> SourceLocation() | |||
1906 | // 100 -> Expanded loc #1 | |||
1907 | // 105 -> Expanded loc #2 | |||
1908 | // 108 -> Expanded loc #1 | |||
1909 | // 110 -> SourceLocation() | |||
1910 | // | |||
1911 | // Since re-lexed macro chunks will always be the same size or less of | |||
1912 | // previous chunks, we only need to find where the ending of the new macro | |||
1913 | // chunk is mapped to and update the map with new begin/end mappings. | |||
1914 | ||||
1915 | MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs); | |||
1916 | --I; | |||
1917 | SourceLocation EndOffsMappedLoc = I->second; | |||
1918 | MacroArgsCache[BeginOffs] = ExpansionLoc; | |||
1919 | MacroArgsCache[EndOffs] = EndOffsMappedLoc; | |||
1920 | } | |||
1921 | ||||
1922 | /// If \arg Loc points inside a function macro argument, the returned | |||
1923 | /// location will be the macro location in which the argument was expanded. | |||
1924 | /// If a macro argument is used multiple times, the expanded location will | |||
1925 | /// be at the first expansion of the argument. | |||
1926 | /// e.g. | |||
1927 | /// MY_MACRO(foo); | |||
1928 | /// ^ | |||
1929 | /// Passing a file location pointing at 'foo', will yield a macro location | |||
1930 | /// where 'foo' was expanded into. | |||
1931 | SourceLocation | |||
1932 | SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const { | |||
1933 | if (Loc.isInvalid() || !Loc.isFileID()) | |||
1934 | return Loc; | |||
1935 | ||||
1936 | FileID FID; | |||
1937 | unsigned Offset; | |||
1938 | std::tie(FID, Offset) = getDecomposedLoc(Loc); | |||
1939 | if (FID.isInvalid()) | |||
1940 | return Loc; | |||
1941 | ||||
1942 | std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID]; | |||
1943 | if (!MacroArgsCache) { | |||
1944 | MacroArgsCache = llvm::make_unique<MacroArgsMap>(); | |||
1945 | computeMacroArgsCache(*MacroArgsCache, FID); | |||
1946 | } | |||
1947 | ||||
1948 | assert(!MacroArgsCache->empty())(static_cast <bool> (!MacroArgsCache->empty()) ? void (0) : __assert_fail ("!MacroArgsCache->empty()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 1948, __extension__ __PRETTY_FUNCTION__)); | |||
1949 | MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset); | |||
1950 | --I; | |||
1951 | ||||
1952 | unsigned MacroArgBeginOffs = I->first; | |||
1953 | SourceLocation MacroArgExpandedLoc = I->second; | |||
1954 | if (MacroArgExpandedLoc.isValid()) | |||
1955 | return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs); | |||
1956 | ||||
1957 | return Loc; | |||
1958 | } | |||
1959 | ||||
1960 | std::pair<FileID, unsigned> | |||
1961 | SourceManager::getDecomposedIncludedLoc(FileID FID) const { | |||
1962 | if (FID.isInvalid()) | |||
1963 | return std::make_pair(FileID(), 0); | |||
1964 | ||||
1965 | // Uses IncludedLocMap to retrieve/cache the decomposed loc. | |||
1966 | ||||
1967 | using DecompTy = std::pair<FileID, unsigned>; | |||
1968 | using MapTy = llvm::DenseMap<FileID, DecompTy>; | |||
1969 | std::pair<MapTy::iterator, bool> | |||
1970 | InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy())); | |||
1971 | DecompTy &DecompLoc = InsertOp.first->second; | |||
1972 | if (!InsertOp.second) | |||
1973 | return DecompLoc; // already in map. | |||
1974 | ||||
1975 | SourceLocation UpperLoc; | |||
1976 | bool Invalid = false; | |||
1977 | const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid); | |||
1978 | if (!Invalid) { | |||
1979 | if (Entry.isExpansion()) | |||
1980 | UpperLoc = Entry.getExpansion().getExpansionLocStart(); | |||
1981 | else | |||
1982 | UpperLoc = Entry.getFile().getIncludeLoc(); | |||
1983 | } | |||
1984 | ||||
1985 | if (UpperLoc.isValid()) | |||
1986 | DecompLoc = getDecomposedLoc(UpperLoc); | |||
1987 | ||||
1988 | return DecompLoc; | |||
1989 | } | |||
1990 | ||||
1991 | /// Given a decomposed source location, move it up the include/expansion stack | |||
1992 | /// to the parent source location. If this is possible, return the decomposed | |||
1993 | /// version of the parent in Loc and return false. If Loc is the top-level | |||
1994 | /// entry, return true and don't modify it. | |||
1995 | static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc, | |||
1996 | const SourceManager &SM) { | |||
1997 | std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first); | |||
1998 | if (UpperLoc.first.isInvalid()) | |||
1999 | return true; // We reached the top. | |||
2000 | ||||
2001 | Loc = UpperLoc; | |||
2002 | return false; | |||
2003 | } | |||
2004 | ||||
2005 | /// Return the cache entry for comparing the given file IDs | |||
2006 | /// for isBeforeInTranslationUnit. | |||
2007 | InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID, | |||
2008 | FileID RFID) const { | |||
2009 | // This is a magic number for limiting the cache size. It was experimentally | |||
2010 | // derived from a small Objective-C project (where the cache filled | |||
2011 | // out to ~250 items). We can make it larger if necessary. | |||
2012 | enum { MagicCacheSize = 300 }; | |||
2013 | IsBeforeInTUCacheKey Key(LFID, RFID); | |||
2014 | ||||
2015 | // If the cache size isn't too large, do a lookup and if necessary default | |||
2016 | // construct an entry. We can then return it to the caller for direct | |||
2017 | // use. When they update the value, the cache will get automatically | |||
2018 | // updated as well. | |||
2019 | if (IBTUCache.size() < MagicCacheSize) | |||
2020 | return IBTUCache[Key]; | |||
2021 | ||||
2022 | // Otherwise, do a lookup that will not construct a new value. | |||
2023 | InBeforeInTUCache::iterator I = IBTUCache.find(Key); | |||
2024 | if (I != IBTUCache.end()) | |||
2025 | return I->second; | |||
2026 | ||||
2027 | // Fall back to the overflow value. | |||
2028 | return IBTUCacheOverflow; | |||
2029 | } | |||
2030 | ||||
2031 | /// Determines the order of 2 source locations in the translation unit. | |||
2032 | /// | |||
2033 | /// \returns true if LHS source location comes before RHS, false otherwise. | |||
2034 | bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS, | |||
2035 | SourceLocation RHS) const { | |||
2036 | assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!")(static_cast <bool> (LHS.isValid() && RHS.isValid () && "Passed invalid source location!") ? void (0) : __assert_fail ("LHS.isValid() && RHS.isValid() && \"Passed invalid source location!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 2036, __extension__ __PRETTY_FUNCTION__)); | |||
2037 | if (LHS == RHS) | |||
2038 | return false; | |||
2039 | ||||
2040 | std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS); | |||
2041 | std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS); | |||
2042 | ||||
2043 | // getDecomposedLoc may have failed to return a valid FileID because, e.g. it | |||
2044 | // is a serialized one referring to a file that was removed after we loaded | |||
2045 | // the PCH. | |||
2046 | if (LOffs.first.isInvalid() || ROffs.first.isInvalid()) | |||
2047 | return LOffs.first.isInvalid() && !ROffs.first.isInvalid(); | |||
2048 | ||||
2049 | std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs); | |||
2050 | if (InSameTU.first) | |||
2051 | return InSameTU.second; | |||
2052 | ||||
2053 | // If we arrived here, the location is either in a built-ins buffer or | |||
2054 | // associated with global inline asm. PR5662 and PR22576 are examples. | |||
2055 | ||||
2056 | StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier(); | |||
2057 | StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier(); | |||
2058 | bool LIsBuiltins = LB == "<built-in>"; | |||
2059 | bool RIsBuiltins = RB == "<built-in>"; | |||
2060 | // Sort built-in before non-built-in. | |||
2061 | if (LIsBuiltins || RIsBuiltins) { | |||
2062 | if (LIsBuiltins != RIsBuiltins) | |||
2063 | return LIsBuiltins; | |||
2064 | // Both are in built-in buffers, but from different files. We just claim that | |||
2065 | // lower IDs come first. | |||
2066 | return LOffs.first < ROffs.first; | |||
2067 | } | |||
2068 | bool LIsAsm = LB == "<inline asm>"; | |||
2069 | bool RIsAsm = RB == "<inline asm>"; | |||
2070 | // Sort assembler after built-ins, but before the rest. | |||
2071 | if (LIsAsm || RIsAsm) { | |||
2072 | if (LIsAsm != RIsAsm) | |||
2073 | return RIsAsm; | |||
2074 | assert(LOffs.first == ROffs.first)(static_cast <bool> (LOffs.first == ROffs.first) ? void (0) : __assert_fail ("LOffs.first == ROffs.first", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 2074, __extension__ __PRETTY_FUNCTION__)); | |||
2075 | return false; | |||
2076 | } | |||
2077 | bool LIsScratch = LB == "<scratch space>"; | |||
2078 | bool RIsScratch = RB == "<scratch space>"; | |||
2079 | // Sort scratch after inline asm, but before the rest. | |||
2080 | if (LIsScratch || RIsScratch) { | |||
2081 | if (LIsScratch != RIsScratch) | |||
2082 | return LIsScratch; | |||
2083 | return LOffs.second < ROffs.second; | |||
2084 | } | |||
2085 | llvm_unreachable("Unsortable locations found")::llvm::llvm_unreachable_internal("Unsortable locations found" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 2085); | |||
2086 | } | |||
2087 | ||||
2088 | std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit( | |||
2089 | std::pair<FileID, unsigned> &LOffs, | |||
2090 | std::pair<FileID, unsigned> &ROffs) const { | |||
2091 | // If the source locations are in the same file, just compare offsets. | |||
2092 | if (LOffs.first == ROffs.first) | |||
2093 | return std::make_pair(true, LOffs.second < ROffs.second); | |||
2094 | ||||
2095 | // If we are comparing a source location with multiple locations in the same | |||
2096 | // file, we get a big win by caching the result. | |||
2097 | InBeforeInTUCacheEntry &IsBeforeInTUCache = | |||
2098 | getInBeforeInTUCache(LOffs.first, ROffs.first); | |||
2099 | ||||
2100 | // If we are comparing a source location with multiple locations in the same | |||
2101 | // file, we get a big win by caching the result. | |||
2102 | if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first)) | |||
2103 | return std::make_pair( | |||
2104 | true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second)); | |||
2105 | ||||
2106 | // Okay, we missed in the cache, start updating the cache for this query. | |||
2107 | IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first, | |||
2108 | /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID); | |||
2109 | ||||
2110 | // We need to find the common ancestor. The only way of doing this is to | |||
2111 | // build the complete include chain for one and then walking up the chain | |||
2112 | // of the other looking for a match. | |||
2113 | // We use a map from FileID to Offset to store the chain. Easier than writing | |||
2114 | // a custom set hash info that only depends on the first part of a pair. | |||
2115 | using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>; | |||
2116 | LocSet LChain; | |||
2117 | do { | |||
2118 | LChain.insert(LOffs); | |||
2119 | // We catch the case where LOffs is in a file included by ROffs and | |||
2120 | // quit early. The other way round unfortunately remains suboptimal. | |||
2121 | } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this)); | |||
2122 | LocSet::iterator I; | |||
2123 | while((I = LChain.find(ROffs.first)) == LChain.end()) { | |||
2124 | if (MoveUpIncludeHierarchy(ROffs, *this)) | |||
2125 | break; // Met at topmost file. | |||
2126 | } | |||
2127 | if (I != LChain.end()) | |||
2128 | LOffs = *I; | |||
2129 | ||||
2130 | // If we exited because we found a nearest common ancestor, compare the | |||
2131 | // locations within the common file and cache them. | |||
2132 | if (LOffs.first == ROffs.first) { | |||
2133 | IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second); | |||
2134 | return std::make_pair( | |||
2135 | true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second)); | |||
2136 | } | |||
2137 | // Clear the lookup cache, it depends on a common location. | |||
2138 | IsBeforeInTUCache.clear(); | |||
2139 | return std::make_pair(false, false); | |||
2140 | } | |||
2141 | ||||
2142 | void SourceManager::PrintStats() const { | |||
2143 | llvm::errs() << "\n*** Source Manager Stats:\n"; | |||
2144 | llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size() | |||
2145 | << " mem buffers mapped.\n"; | |||
2146 | llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated (" | |||
2147 | << llvm::capacity_in_bytes(LocalSLocEntryTable) | |||
2148 | << " bytes of capacity), " | |||
2149 | << NextLocalOffset << "B of Sloc address space used.\n"; | |||
2150 | llvm::errs() << LoadedSLocEntryTable.size() | |||
2151 | << " loaded SLocEntries allocated, " | |||
2152 | << MaxLoadedOffset - CurrentLoadedOffset | |||
2153 | << "B of Sloc address space used.\n"; | |||
2154 | ||||
2155 | unsigned NumLineNumsComputed = 0; | |||
2156 | unsigned NumFileBytesMapped = 0; | |||
2157 | for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){ | |||
2158 | NumLineNumsComputed += I->second->SourceLineCache != nullptr; | |||
2159 | NumFileBytesMapped += I->second->getSizeBytesMapped(); | |||
2160 | } | |||
2161 | unsigned NumMacroArgsComputed = MacroArgsCacheMap.size(); | |||
2162 | ||||
2163 | llvm::errs() << NumFileBytesMapped << " bytes of files mapped, " | |||
2164 | << NumLineNumsComputed << " files with line #'s computed, " | |||
2165 | << NumMacroArgsComputed << " files with macro args computed.\n"; | |||
2166 | llvm::errs() << "FileID scans: " << NumLinearScans << " linear, " | |||
2167 | << NumBinaryProbes << " binary.\n"; | |||
2168 | } | |||
2169 | ||||
2170 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void SourceManager::dump() const { | |||
2171 | llvm::raw_ostream &out = llvm::errs(); | |||
2172 | ||||
2173 | auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry, | |||
2174 | llvm::Optional<unsigned> NextStart) { | |||
2175 | out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion") | |||
2176 | << " <SourceLocation " << Entry.getOffset() << ":"; | |||
2177 | if (NextStart) | |||
2178 | out << *NextStart << ">\n"; | |||
2179 | else | |||
2180 | out << "???\?>\n"; | |||
2181 | if (Entry.isFile()) { | |||
2182 | auto &FI = Entry.getFile(); | |||
2183 | if (FI.NumCreatedFIDs) | |||
2184 | out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs) | |||
2185 | << ">\n"; | |||
2186 | if (FI.getIncludeLoc().isValid()) | |||
2187 | out << " included from " << FI.getIncludeLoc().getOffset() << "\n"; | |||
2188 | if (auto *CC = FI.getContentCache()) { | |||
2189 | out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>") | |||
2190 | << "\n"; | |||
2191 | if (CC->BufferOverridden) | |||
2192 | out << " contents overridden\n"; | |||
2193 | if (CC->ContentsEntry != CC->OrigEntry) { | |||
2194 | out << " contents from " | |||
2195 | << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>") | |||
2196 | << "\n"; | |||
2197 | } | |||
2198 | } | |||
2199 | } else { | |||
2200 | auto &EI = Entry.getExpansion(); | |||
2201 | out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n"; | |||
2202 | out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body") | |||
2203 | << " range <" << EI.getExpansionLocStart().getOffset() << ":" | |||
2204 | << EI.getExpansionLocEnd().getOffset() << ">\n"; | |||
2205 | } | |||
2206 | }; | |||
2207 | ||||
2208 | // Dump local SLocEntries. | |||
2209 | for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) { | |||
2210 | DumpSLocEntry(ID, LocalSLocEntryTable[ID], | |||
2211 | ID == NumIDs - 1 ? NextLocalOffset | |||
2212 | : LocalSLocEntryTable[ID + 1].getOffset()); | |||
2213 | } | |||
2214 | // Dump loaded SLocEntries. | |||
2215 | llvm::Optional<unsigned> NextStart; | |||
2216 | for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) { | |||
2217 | int ID = -(int)Index - 2; | |||
2218 | if (SLocEntryLoaded[Index]) { | |||
2219 | DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart); | |||
2220 | NextStart = LoadedSLocEntryTable[Index].getOffset(); | |||
2221 | } else { | |||
2222 | NextStart = None; | |||
2223 | } | |||
2224 | } | |||
2225 | } | |||
2226 | ||||
2227 | ExternalSLocEntrySource::~ExternalSLocEntrySource() = default; | |||
2228 | ||||
2229 | /// Return the amount of memory used by memory buffers, breaking down | |||
2230 | /// by heap-backed versus mmap'ed memory. | |||
2231 | SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const { | |||
2232 | size_t malloc_bytes = 0; | |||
2233 | size_t mmap_bytes = 0; | |||
2234 | ||||
2235 | for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) | |||
2236 | if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped()) | |||
2237 | switch (MemBufferInfos[i]->getMemoryBufferKind()) { | |||
2238 | case llvm::MemoryBuffer::MemoryBuffer_MMap: | |||
2239 | mmap_bytes += sized_mapped; | |||
2240 | break; | |||
2241 | case llvm::MemoryBuffer::MemoryBuffer_Malloc: | |||
2242 | malloc_bytes += sized_mapped; | |||
2243 | break; | |||
2244 | } | |||
2245 | ||||
2246 | return MemoryBufferSizes(malloc_bytes, mmap_bytes); | |||
2247 | } | |||
2248 | ||||
2249 | size_t SourceManager::getDataStructureSizes() const { | |||
2250 | size_t size = llvm::capacity_in_bytes(MemBufferInfos) | |||
2251 | + llvm::capacity_in_bytes(LocalSLocEntryTable) | |||
2252 | + llvm::capacity_in_bytes(LoadedSLocEntryTable) | |||
2253 | + llvm::capacity_in_bytes(SLocEntryLoaded) | |||
2254 | + llvm::capacity_in_bytes(FileInfos); | |||
2255 | ||||
2256 | if (OverriddenFilesInfo) | |||
2257 | size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles); | |||
2258 | ||||
2259 | return size; | |||
2260 | } | |||
2261 | ||||
2262 | SourceManagerForFile::SourceManagerForFile(StringRef FileName, | |||
2263 | StringRef Content) { | |||
2264 | // This is referenced by `FileMgr` and will be released by `FileMgr` when it | |||
2265 | // is deleted. | |||
2266 | IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem( | |||
2267 | new vfs::InMemoryFileSystem); | |||
2268 | InMemoryFileSystem->addFile( | |||
2269 | FileName, 0, | |||
2270 | llvm::MemoryBuffer::getMemBuffer(Content, FileName, | |||
2271 | /*RequiresNullTerminator=*/false)); | |||
2272 | // This is passed to `SM` as reference, so the pointer has to be referenced | |||
2273 | // in `Environment` so that `FileMgr` can out-live this function scope. | |||
2274 | FileMgr = | |||
2275 | llvm::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem); | |||
2276 | // This is passed to `SM` as reference, so the pointer has to be referenced | |||
2277 | // by `Environment` due to the same reason above. | |||
2278 | Diagnostics = llvm::make_unique<DiagnosticsEngine>( | |||
2279 | IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), | |||
| ||||
2280 | new DiagnosticOptions); | |||
2281 | SourceMgr = llvm::make_unique<SourceManager>(*Diagnostics, *FileMgr); | |||
2282 | FileID ID = SourceMgr->createFileID(FileMgr->getFile(FileName), | |||
2283 | SourceLocation(), clang::SrcMgr::C_User); | |||
2284 | assert(ID.isValid())(static_cast <bool> (ID.isValid()) ? void (0) : __assert_fail ("ID.isValid()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Basic/SourceManager.cpp" , 2284, __extension__ __PRETTY_FUNCTION__)); | |||
2285 | SourceMgr->setMainFileID(ID); | |||
2286 | } |
1 | //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===// |
2 | // |
3 | // The LLVM Compiler Infrastructure |
4 | // |
5 | // This file is distributed under the University of Illinois Open Source |
6 | // License. See LICENSE.TXT for details. |
7 | // |
8 | //===----------------------------------------------------------------------===// |
9 | // |
10 | // This file contains some templates that are useful if you are working with the |
11 | // STL at all. |
12 | // |
13 | // No library is required when using these functions. |
14 | // |
15 | //===----------------------------------------------------------------------===// |
16 | |
17 | #ifndef LLVM_ADT_STLEXTRAS_H |
18 | #define LLVM_ADT_STLEXTRAS_H |
19 | |
20 | #include "llvm/ADT/Optional.h" |
21 | #include "llvm/ADT/SmallVector.h" |
22 | #include "llvm/ADT/iterator.h" |
23 | #include "llvm/ADT/iterator_range.h" |
24 | #include "llvm/Support/ErrorHandling.h" |
25 | #include <algorithm> |
26 | #include <cassert> |
27 | #include <cstddef> |
28 | #include <cstdint> |
29 | #include <cstdlib> |
30 | #include <functional> |
31 | #include <initializer_list> |
32 | #include <iterator> |
33 | #include <limits> |
34 | #include <memory> |
35 | #include <tuple> |
36 | #include <type_traits> |
37 | #include <utility> |
38 | |
39 | #ifdef EXPENSIVE_CHECKS |
40 | #include <random> // for std::mt19937 |
41 | #endif |
42 | |
43 | namespace llvm { |
44 | |
45 | // Only used by compiler if both template types are the same. Useful when |
46 | // using SFINAE to test for the existence of member functions. |
47 | template <typename T, T> struct SameType; |
48 | |
49 | namespace detail { |
50 | |
51 | template <typename RangeT> |
52 | using IterOfRange = decltype(std::begin(std::declval<RangeT &>())); |
53 | |
54 | template <typename RangeT> |
55 | using ValueOfRange = typename std::remove_reference<decltype( |
56 | *std::begin(std::declval<RangeT &>()))>::type; |
57 | |
58 | } // end namespace detail |
59 | |
60 | //===----------------------------------------------------------------------===// |
61 | // Extra additions to <type_traits> |
62 | //===----------------------------------------------------------------------===// |
63 | |
64 | template <typename T> |
65 | struct negation : std::integral_constant<bool, !bool(T::value)> {}; |
66 | |
67 | template <typename...> struct conjunction : std::true_type {}; |
68 | template <typename B1> struct conjunction<B1> : B1 {}; |
69 | template <typename B1, typename... Bn> |
70 | struct conjunction<B1, Bn...> |
71 | : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {}; |
72 | |
73 | //===----------------------------------------------------------------------===// |
74 | // Extra additions to <functional> |
75 | //===----------------------------------------------------------------------===// |
76 | |
77 | template <class Ty> struct identity { |
78 | using argument_type = Ty; |
79 | |
80 | Ty &operator()(Ty &self) const { |
81 | return self; |
82 | } |
83 | const Ty &operator()(const Ty &self) const { |
84 | return self; |
85 | } |
86 | }; |
87 | |
88 | template <class Ty> struct less_ptr { |
89 | bool operator()(const Ty* left, const Ty* right) const { |
90 | return *left < *right; |
91 | } |
92 | }; |
93 | |
94 | template <class Ty> struct greater_ptr { |
95 | bool operator()(const Ty* left, const Ty* right) const { |
96 | return *right < *left; |
97 | } |
98 | }; |
99 | |
100 | /// An efficient, type-erasing, non-owning reference to a callable. This is |
101 | /// intended for use as the type of a function parameter that is not used |
102 | /// after the function in question returns. |
103 | /// |
104 | /// This class does not own the callable, so it is not in general safe to store |
105 | /// a function_ref. |
106 | template<typename Fn> class function_ref; |
107 | |
108 | template<typename Ret, typename ...Params> |
109 | class function_ref<Ret(Params...)> { |
110 | Ret (*callback)(intptr_t callable, Params ...params) = nullptr; |
111 | intptr_t callable; |
112 | |
113 | template<typename Callable> |
114 | static Ret callback_fn(intptr_t callable, Params ...params) { |
115 | return (*reinterpret_cast<Callable*>(callable))( |
116 | std::forward<Params>(params)...); |
117 | } |
118 | |
119 | public: |
120 | function_ref() = default; |
121 | function_ref(std::nullptr_t) {} |
122 | |
123 | template <typename Callable> |
124 | function_ref(Callable &&callable, |
125 | typename std::enable_if< |
126 | !std::is_same<typename std::remove_reference<Callable>::type, |
127 | function_ref>::value>::type * = nullptr) |
128 | : callback(callback_fn<typename std::remove_reference<Callable>::type>), |
129 | callable(reinterpret_cast<intptr_t>(&callable)) {} |
130 | |
131 | Ret operator()(Params ...params) const { |
132 | return callback(callable, std::forward<Params>(params)...); |
133 | } |
134 | |
135 | operator bool() const { return callback; } |
136 | }; |
137 | |
138 | // deleter - Very very very simple method that is used to invoke operator |
139 | // delete on something. It is used like this: |
140 | // |
141 | // for_each(V.begin(), B.end(), deleter<Interval>); |
142 | template <class T> |
143 | inline void deleter(T *Ptr) { |
144 | delete Ptr; |
145 | } |
146 | |
147 | //===----------------------------------------------------------------------===// |
148 | // Extra additions to <iterator> |
149 | //===----------------------------------------------------------------------===// |
150 | |
151 | namespace adl_detail { |
152 | |
153 | using std::begin; |
154 | |
155 | template <typename ContainerTy> |
156 | auto adl_begin(ContainerTy &&container) |
157 | -> decltype(begin(std::forward<ContainerTy>(container))) { |
158 | return begin(std::forward<ContainerTy>(container)); |
159 | } |
160 | |
161 | using std::end; |
162 | |
163 | template <typename ContainerTy> |
164 | auto adl_end(ContainerTy &&container) |
165 | -> decltype(end(std::forward<ContainerTy>(container))) { |
166 | return end(std::forward<ContainerTy>(container)); |
167 | } |
168 | |
169 | using std::swap; |
170 | |
171 | template <typename T> |
172 | void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(), |
173 | std::declval<T>()))) { |
174 | swap(std::forward<T>(lhs), std::forward<T>(rhs)); |
175 | } |
176 | |
177 | } // end namespace adl_detail |
178 | |
179 | template <typename ContainerTy> |
180 | auto adl_begin(ContainerTy &&container) |
181 | -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) { |
182 | return adl_detail::adl_begin(std::forward<ContainerTy>(container)); |
183 | } |
184 | |
185 | template <typename ContainerTy> |
186 | auto adl_end(ContainerTy &&container) |
187 | -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) { |
188 | return adl_detail::adl_end(std::forward<ContainerTy>(container)); |
189 | } |
190 | |
191 | template <typename T> |
192 | void adl_swap(T &&lhs, T &&rhs) noexcept( |
193 | noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) { |
194 | adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs)); |
195 | } |
196 | |
197 | // mapped_iterator - This is a simple iterator adapter that causes a function to |
198 | // be applied whenever operator* is invoked on the iterator. |
199 | |
200 | template <typename ItTy, typename FuncTy, |
201 | typename FuncReturnTy = |
202 | decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))> |
203 | class mapped_iterator |
204 | : public iterator_adaptor_base< |
205 | mapped_iterator<ItTy, FuncTy>, ItTy, |
206 | typename std::iterator_traits<ItTy>::iterator_category, |
207 | typename std::remove_reference<FuncReturnTy>::type> { |
208 | public: |
209 | mapped_iterator(ItTy U, FuncTy F) |
210 | : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {} |
211 | |
212 | ItTy getCurrent() { return this->I; } |
213 | |
214 | FuncReturnTy operator*() { return F(*this->I); } |
215 | |
216 | private: |
217 | FuncTy F; |
218 | }; |
219 | |
220 | // map_iterator - Provide a convenient way to create mapped_iterators, just like |
221 | // make_pair is useful for creating pairs... |
222 | template <class ItTy, class FuncTy> |
223 | inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) { |
224 | return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F)); |
225 | } |
226 | |
227 | /// Helper to determine if type T has a member called rbegin(). |
228 | template <typename Ty> class has_rbegin_impl { |
229 | using yes = char[1]; |
230 | using no = char[2]; |
231 | |
232 | template <typename Inner> |
233 | static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr); |
234 | |
235 | template <typename> |
236 | static no& test(...); |
237 | |
238 | public: |
239 | static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes); |
240 | }; |
241 | |
242 | /// Metafunction to determine if T& or T has a member called rbegin(). |
243 | template <typename Ty> |
244 | struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> { |
245 | }; |
246 | |
247 | // Returns an iterator_range over the given container which iterates in reverse. |
248 | // Note that the container must have rbegin()/rend() methods for this to work. |
249 | template <typename ContainerTy> |
250 | auto reverse(ContainerTy &&C, |
251 | typename std::enable_if<has_rbegin<ContainerTy>::value>::type * = |
252 | nullptr) -> decltype(make_range(C.rbegin(), C.rend())) { |
253 | return make_range(C.rbegin(), C.rend()); |
254 | } |
255 | |
256 | // Returns a std::reverse_iterator wrapped around the given iterator. |
257 | template <typename IteratorTy> |
258 | std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) { |
259 | return std::reverse_iterator<IteratorTy>(It); |
260 | } |
261 | |
262 | // Returns an iterator_range over the given container which iterates in reverse. |
263 | // Note that the container must have begin()/end() methods which return |
264 | // bidirectional iterators for this to work. |
265 | template <typename ContainerTy> |
266 | auto reverse( |
267 | ContainerTy &&C, |
268 | typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr) |
269 | -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)), |
270 | llvm::make_reverse_iterator(std::begin(C)))) { |
271 | return make_range(llvm::make_reverse_iterator(std::end(C)), |
272 | llvm::make_reverse_iterator(std::begin(C))); |
273 | } |
274 | |
275 | /// An iterator adaptor that filters the elements of given inner iterators. |
276 | /// |
277 | /// The predicate parameter should be a callable object that accepts the wrapped |
278 | /// iterator's reference type and returns a bool. When incrementing or |
279 | /// decrementing the iterator, it will call the predicate on each element and |
280 | /// skip any where it returns false. |
281 | /// |
282 | /// \code |
283 | /// int A[] = { 1, 2, 3, 4 }; |
284 | /// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; }); |
285 | /// // R contains { 1, 3 }. |
286 | /// \endcode |
287 | /// |
288 | /// Note: filter_iterator_base implements support for forward iteration. |
289 | /// filter_iterator_impl exists to provide support for bidirectional iteration, |
290 | /// conditional on whether the wrapped iterator supports it. |
291 | template <typename WrappedIteratorT, typename PredicateT, typename IterTag> |
292 | class filter_iterator_base |
293 | : public iterator_adaptor_base< |
294 | filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>, |
295 | WrappedIteratorT, |
296 | typename std::common_type< |
297 | IterTag, typename std::iterator_traits< |
298 | WrappedIteratorT>::iterator_category>::type> { |
299 | using BaseT = iterator_adaptor_base< |
300 | filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>, |
301 | WrappedIteratorT, |
302 | typename std::common_type< |
303 | IterTag, typename std::iterator_traits< |
304 | WrappedIteratorT>::iterator_category>::type>; |
305 | |
306 | protected: |
307 | WrappedIteratorT End; |
308 | PredicateT Pred; |
309 | |
310 | void findNextValid() { |
311 | while (this->I != End && !Pred(*this->I)) |
312 | BaseT::operator++(); |
313 | } |
314 | |
315 | // Construct the iterator. The begin iterator needs to know where the end |
316 | // is, so that it can properly stop when it gets there. The end iterator only |
317 | // needs the predicate to support bidirectional iteration. |
318 | filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End, |
319 | PredicateT Pred) |
320 | : BaseT(Begin), End(End), Pred(Pred) { |
321 | findNextValid(); |
322 | } |
323 | |
324 | public: |
325 | using BaseT::operator++; |
326 | |
327 | filter_iterator_base &operator++() { |
328 | BaseT::operator++(); |
329 | findNextValid(); |
330 | return *this; |
331 | } |
332 | }; |
333 | |
334 | /// Specialization of filter_iterator_base for forward iteration only. |
335 | template <typename WrappedIteratorT, typename PredicateT, |
336 | typename IterTag = std::forward_iterator_tag> |
337 | class filter_iterator_impl |
338 | : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> { |
339 | using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>; |
340 | |
341 | public: |
342 | filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, |
343 | PredicateT Pred) |
344 | : BaseT(Begin, End, Pred) {} |
345 | }; |
346 | |
347 | /// Specialization of filter_iterator_base for bidirectional iteration. |
348 | template <typename WrappedIteratorT, typename PredicateT> |
349 | class filter_iterator_impl<WrappedIteratorT, PredicateT, |
350 | std::bidirectional_iterator_tag> |
351 | : public filter_iterator_base<WrappedIteratorT, PredicateT, |
352 | std::bidirectional_iterator_tag> { |
353 | using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT, |
354 | std::bidirectional_iterator_tag>; |
355 | void findPrevValid() { |
356 | while (!this->Pred(*this->I)) |
357 | BaseT::operator--(); |
358 | } |
359 | |
360 | public: |
361 | using BaseT::operator--; |
362 | |
363 | filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, |
364 | PredicateT Pred) |
365 | : BaseT(Begin, End, Pred) {} |
366 | |
367 | filter_iterator_impl &operator--() { |
368 | BaseT::operator--(); |
369 | findPrevValid(); |
370 | return *this; |
371 | } |
372 | }; |
373 | |
374 | namespace detail { |
375 | |
376 | template <bool is_bidirectional> struct fwd_or_bidi_tag_impl { |
377 | using type = std::forward_iterator_tag; |
378 | }; |
379 | |
380 | template <> struct fwd_or_bidi_tag_impl<true> { |
381 | using type = std::bidirectional_iterator_tag; |
382 | }; |
383 | |
384 | /// Helper which sets its type member to forward_iterator_tag if the category |
385 | /// of \p IterT does not derive from bidirectional_iterator_tag, and to |
386 | /// bidirectional_iterator_tag otherwise. |
387 | template <typename IterT> struct fwd_or_bidi_tag { |
388 | using type = typename fwd_or_bidi_tag_impl<std::is_base_of< |
389 | std::bidirectional_iterator_tag, |
390 | typename std::iterator_traits<IterT>::iterator_category>::value>::type; |
391 | }; |
392 | |
393 | } // namespace detail |
394 | |
395 | /// Defines filter_iterator to a suitable specialization of |
396 | /// filter_iterator_impl, based on the underlying iterator's category. |
397 | template <typename WrappedIteratorT, typename PredicateT> |
398 | using filter_iterator = filter_iterator_impl< |
399 | WrappedIteratorT, PredicateT, |
400 | typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>; |
401 | |
402 | /// Convenience function that takes a range of elements and a predicate, |
403 | /// and return a new filter_iterator range. |
404 | /// |
405 | /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the |
406 | /// lifetime of that temporary is not kept by the returned range object, and the |
407 | /// temporary is going to be dropped on the floor after the make_iterator_range |
408 | /// full expression that contains this function call. |
409 | template <typename RangeT, typename PredicateT> |
410 | iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>> |
411 | make_filter_range(RangeT &&Range, PredicateT Pred) { |
412 | using FilterIteratorT = |
413 | filter_iterator<detail::IterOfRange<RangeT>, PredicateT>; |
414 | return make_range( |
415 | FilterIteratorT(std::begin(std::forward<RangeT>(Range)), |
416 | std::end(std::forward<RangeT>(Range)), Pred), |
417 | FilterIteratorT(std::end(std::forward<RangeT>(Range)), |
418 | std::end(std::forward<RangeT>(Range)), Pred)); |
419 | } |
420 | |
421 | // forward declarations required by zip_shortest/zip_first |
422 | template <typename R, typename UnaryPredicate> |
423 | bool all_of(R &&range, UnaryPredicate P); |
424 | |
425 | template <size_t... I> struct index_sequence; |
426 | |
427 | template <class... Ts> struct index_sequence_for; |
428 | |
429 | namespace detail { |
430 | |
431 | using std::declval; |
432 | |
433 | // We have to alias this since inlining the actual type at the usage site |
434 | // in the parameter list of iterator_facade_base<> below ICEs MSVC 2017. |
435 | template<typename... Iters> struct ZipTupleType { |
436 | using type = std::tuple<decltype(*declval<Iters>())...>; |
437 | }; |
438 | |
439 | template <typename ZipType, typename... Iters> |
440 | using zip_traits = iterator_facade_base< |
441 | ZipType, typename std::common_type<std::bidirectional_iterator_tag, |
442 | typename std::iterator_traits< |
443 | Iters>::iterator_category...>::type, |
444 | // ^ TODO: Implement random access methods. |
445 | typename ZipTupleType<Iters...>::type, |
446 | typename std::iterator_traits<typename std::tuple_element< |
447 | 0, std::tuple<Iters...>>::type>::difference_type, |
448 | // ^ FIXME: This follows boost::make_zip_iterator's assumption that all |
449 | // inner iterators have the same difference_type. It would fail if, for |
450 | // instance, the second field's difference_type were non-numeric while the |
451 | // first is. |
452 | typename ZipTupleType<Iters...>::type *, |
453 | typename ZipTupleType<Iters...>::type>; |
454 | |
455 | template <typename ZipType, typename... Iters> |
456 | struct zip_common : public zip_traits<ZipType, Iters...> { |
457 | using Base = zip_traits<ZipType, Iters...>; |
458 | using value_type = typename Base::value_type; |
459 | |
460 | std::tuple<Iters...> iterators; |
461 | |
462 | protected: |
463 | template <size_t... Ns> value_type deref(index_sequence<Ns...>) const { |
464 | return value_type(*std::get<Ns>(iterators)...); |
465 | } |
466 | |
467 | template <size_t... Ns> |
468 | decltype(iterators) tup_inc(index_sequence<Ns...>) const { |
469 | return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...); |
470 | } |
471 | |
472 | template <size_t... Ns> |
473 | decltype(iterators) tup_dec(index_sequence<Ns...>) const { |
474 | return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...); |
475 | } |
476 | |
477 | public: |
478 | zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {} |
479 | |
480 | value_type operator*() { return deref(index_sequence_for<Iters...>{}); } |
481 | |
482 | const value_type operator*() const { |
483 | return deref(index_sequence_for<Iters...>{}); |
484 | } |
485 | |
486 | ZipType &operator++() { |
487 | iterators = tup_inc(index_sequence_for<Iters...>{}); |
488 | return *reinterpret_cast<ZipType *>(this); |
489 | } |
490 | |
491 | ZipType &operator--() { |
492 | static_assert(Base::IsBidirectional, |
493 | "All inner iterators must be at least bidirectional."); |
494 | iterators = tup_dec(index_sequence_for<Iters...>{}); |
495 | return *reinterpret_cast<ZipType *>(this); |
496 | } |
497 | }; |
498 | |
499 | template <typename... Iters> |
500 | struct zip_first : public zip_common<zip_first<Iters...>, Iters...> { |
501 | using Base = zip_common<zip_first<Iters...>, Iters...>; |
502 | |
503 | bool operator==(const zip_first<Iters...> &other) const { |
504 | return std::get<0>(this->iterators) == std::get<0>(other.iterators); |
505 | } |
506 | |
507 | zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {} |
508 | }; |
509 | |
510 | template <typename... Iters> |
511 | class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> { |
512 | template <size_t... Ns> |
513 | bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const { |
514 | return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) != |
515 | std::get<Ns>(other.iterators)...}, |
516 | identity<bool>{}); |
517 | } |
518 | |
519 | public: |
520 | using Base = zip_common<zip_shortest<Iters...>, Iters...>; |
521 | |
522 | zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {} |
523 | |
524 | bool operator==(const zip_shortest<Iters...> &other) const { |
525 | return !test(other, index_sequence_for<Iters...>{}); |
526 | } |
527 | }; |
528 | |
529 | template <template <typename...> class ItType, typename... Args> class zippy { |
530 | public: |
531 | using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>; |
532 | using iterator_category = typename iterator::iterator_category; |
533 | using value_type = typename iterator::value_type; |
534 | using difference_type = typename iterator::difference_type; |
535 | using pointer = typename iterator::pointer; |
536 | using reference = typename iterator::reference; |
537 | |
538 | private: |
539 | std::tuple<Args...> ts; |
540 | |
541 | template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const { |
542 | return iterator(std::begin(std::get<Ns>(ts))...); |
543 | } |
544 | template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const { |
545 | return iterator(std::end(std::get<Ns>(ts))...); |
546 | } |
547 | |
548 | public: |
549 | zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {} |
550 | |
551 | iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); } |
552 | iterator end() const { return end_impl(index_sequence_for<Args...>{}); } |
553 | }; |
554 | |
555 | } // end namespace detail |
556 | |
557 | /// zip iterator for two or more iteratable types. |
558 | template <typename T, typename U, typename... Args> |
559 | detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u, |
560 | Args &&... args) { |
561 | return detail::zippy<detail::zip_shortest, T, U, Args...>( |
562 | std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); |
563 | } |
564 | |
565 | /// zip iterator that, for the sake of efficiency, assumes the first iteratee to |
566 | /// be the shortest. |
567 | template <typename T, typename U, typename... Args> |
568 | detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u, |
569 | Args &&... args) { |
570 | return detail::zippy<detail::zip_first, T, U, Args...>( |
571 | std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); |
572 | } |
573 | |
574 | /// Iterator wrapper that concatenates sequences together. |
575 | /// |
576 | /// This can concatenate different iterators, even with different types, into |
577 | /// a single iterator provided the value types of all the concatenated |
578 | /// iterators expose `reference` and `pointer` types that can be converted to |
579 | /// `ValueT &` and `ValueT *` respectively. It doesn't support more |
580 | /// interesting/customized pointer or reference types. |
581 | /// |
582 | /// Currently this only supports forward or higher iterator categories as |
583 | /// inputs and always exposes a forward iterator interface. |
584 | template <typename ValueT, typename... IterTs> |
585 | class concat_iterator |
586 | : public iterator_facade_base<concat_iterator<ValueT, IterTs...>, |
587 | std::forward_iterator_tag, ValueT> { |
588 | using BaseT = typename concat_iterator::iterator_facade_base; |
589 | |
590 | /// We store both the current and end iterators for each concatenated |
591 | /// sequence in a tuple of pairs. |
592 | /// |
593 | /// Note that something like iterator_range seems nice at first here, but the |
594 | /// range properties are of little benefit and end up getting in the way |
595 | /// because we need to do mutation on the current iterators. |
596 | std::tuple<std::pair<IterTs, IterTs>...> IterPairs; |
597 | |
598 | /// Attempts to increment a specific iterator. |
599 | /// |
600 | /// Returns true if it was able to increment the iterator. Returns false if |
601 | /// the iterator is already at the end iterator. |
602 | template <size_t Index> bool incrementHelper() { |
603 | auto &IterPair = std::get<Index>(IterPairs); |
604 | if (IterPair.first == IterPair.second) |
605 | return false; |
606 | |
607 | ++IterPair.first; |
608 | return true; |
609 | } |
610 | |
611 | /// Increments the first non-end iterator. |
612 | /// |
613 | /// It is an error to call this with all iterators at the end. |
614 | template <size_t... Ns> void increment(index_sequence<Ns...>) { |
615 | // Build a sequence of functions to increment each iterator if possible. |
616 | bool (concat_iterator::*IncrementHelperFns[])() = { |
617 | &concat_iterator::incrementHelper<Ns>...}; |
618 | |
619 | // Loop over them, and stop as soon as we succeed at incrementing one. |
620 | for (auto &IncrementHelperFn : IncrementHelperFns) |
621 | if ((this->*IncrementHelperFn)()) |
622 | return; |
623 | |
624 | llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!" , "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/STLExtras.h" , 624); |
625 | } |
626 | |
627 | /// Returns null if the specified iterator is at the end. Otherwise, |
628 | /// dereferences the iterator and returns the address of the resulting |
629 | /// reference. |
630 | template <size_t Index> ValueT *getHelper() const { |
631 | auto &IterPair = std::get<Index>(IterPairs); |
632 | if (IterPair.first == IterPair.second) |
633 | return nullptr; |
634 | |
635 | return &*IterPair.first; |
636 | } |
637 | |
638 | /// Finds the first non-end iterator, dereferences, and returns the resulting |
639 | /// reference. |
640 | /// |
641 | /// It is an error to call this with all iterators at the end. |
642 | template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const { |
643 | // Build a sequence of functions to get from iterator if possible. |
644 | ValueT *(concat_iterator::*GetHelperFns[])() const = { |
645 | &concat_iterator::getHelper<Ns>...}; |
646 | |
647 | // Loop over them, and return the first result we find. |
648 | for (auto &GetHelperFn : GetHelperFns) |
649 | if (ValueT *P = (this->*GetHelperFn)()) |
650 | return *P; |
651 | |
652 | llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!" , "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/STLExtras.h" , 652); |
653 | } |
654 | |
655 | public: |
656 | /// Constructs an iterator from a squence of ranges. |
657 | /// |
658 | /// We need the full range to know how to switch between each of the |
659 | /// iterators. |
660 | template <typename... RangeTs> |
661 | explicit concat_iterator(RangeTs &&... Ranges) |
662 | : IterPairs({std::begin(Ranges), std::end(Ranges)}...) {} |
663 | |
664 | using BaseT::operator++; |
665 | |
666 | concat_iterator &operator++() { |
667 | increment(index_sequence_for<IterTs...>()); |
668 | return *this; |
669 | } |
670 | |
671 | ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); } |
672 | |
673 | bool operator==(const concat_iterator &RHS) const { |
674 | return IterPairs == RHS.IterPairs; |
675 | } |
676 | }; |
677 | |
678 | namespace detail { |
679 | |
680 | /// Helper to store a sequence of ranges being concatenated and access them. |
681 | /// |
682 | /// This is designed to facilitate providing actual storage when temporaries |
683 | /// are passed into the constructor such that we can use it as part of range |
684 | /// based for loops. |
685 | template <typename ValueT, typename... RangeTs> class concat_range { |
686 | public: |
687 | using iterator = |
688 | concat_iterator<ValueT, |
689 | decltype(std::begin(std::declval<RangeTs &>()))...>; |
690 | |
691 | private: |
692 | std::tuple<RangeTs...> Ranges; |
693 | |
694 | template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) { |
695 | return iterator(std::get<Ns>(Ranges)...); |
696 | } |
697 | template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) { |
698 | return iterator(make_range(std::end(std::get<Ns>(Ranges)), |
699 | std::end(std::get<Ns>(Ranges)))...); |
700 | } |
701 | |
702 | public: |
703 | concat_range(RangeTs &&... Ranges) |
704 | : Ranges(std::forward<RangeTs>(Ranges)...) {} |
705 | |
706 | iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); } |
707 | iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); } |
708 | }; |
709 | |
710 | } // end namespace detail |
711 | |
712 | /// Concatenated range across two or more ranges. |
713 | /// |
714 | /// The desired value type must be explicitly specified. |
715 | template <typename ValueT, typename... RangeTs> |
716 | detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) { |
717 | static_assert(sizeof...(RangeTs) > 1, |
718 | "Need more than one range to concatenate!"); |
719 | return detail::concat_range<ValueT, RangeTs...>( |
720 | std::forward<RangeTs>(Ranges)...); |
721 | } |
722 | |
723 | //===----------------------------------------------------------------------===// |
724 | // Extra additions to <utility> |
725 | //===----------------------------------------------------------------------===// |
726 | |
727 | /// Function object to check whether the first component of a std::pair |
728 | /// compares less than the first component of another std::pair. |
729 | struct less_first { |
730 | template <typename T> bool operator()(const T &lhs, const T &rhs) const { |
731 | return lhs.first < rhs.first; |
732 | } |
733 | }; |
734 | |
735 | /// Function object to check whether the second component of a std::pair |
736 | /// compares less than the second component of another std::pair. |
737 | struct less_second { |
738 | template <typename T> bool operator()(const T &lhs, const T &rhs) const { |
739 | return lhs.second < rhs.second; |
740 | } |
741 | }; |
742 | |
743 | // A subset of N3658. More stuff can be added as-needed. |
744 | |
745 | /// Represents a compile-time sequence of integers. |
746 | template <class T, T... I> struct integer_sequence { |
747 | using value_type = T; |
748 | |
749 | static constexpr size_t size() { return sizeof...(I); } |
750 | }; |
751 | |
752 | /// Alias for the common case of a sequence of size_ts. |
753 | template <size_t... I> |
754 | struct index_sequence : integer_sequence<std::size_t, I...> {}; |
755 | |
756 | template <std::size_t N, std::size_t... I> |
757 | struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {}; |
758 | template <std::size_t... I> |
759 | struct build_index_impl<0, I...> : index_sequence<I...> {}; |
760 | |
761 | /// Creates a compile-time integer sequence for a parameter pack. |
762 | template <class... Ts> |
763 | struct index_sequence_for : build_index_impl<sizeof...(Ts)> {}; |
764 | |
765 | /// Utility type to build an inheritance chain that makes it easy to rank |
766 | /// overload candidates. |
767 | template <int N> struct rank : rank<N - 1> {}; |
768 | template <> struct rank<0> {}; |
769 | |
770 | /// traits class for checking whether type T is one of any of the given |
771 | /// types in the variadic list. |
772 | template <typename T, typename... Ts> struct is_one_of { |
773 | static const bool value = false; |
774 | }; |
775 | |
776 | template <typename T, typename U, typename... Ts> |
777 | struct is_one_of<T, U, Ts...> { |
778 | static const bool value = |
779 | std::is_same<T, U>::value || is_one_of<T, Ts...>::value; |
780 | }; |
781 | |
782 | /// traits class for checking whether type T is a base class for all |
783 | /// the given types in the variadic list. |
784 | template <typename T, typename... Ts> struct are_base_of { |
785 | static const bool value = true; |
786 | }; |
787 | |
788 | template <typename T, typename U, typename... Ts> |
789 | struct are_base_of<T, U, Ts...> { |
790 | static const bool value = |
791 | std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value; |
792 | }; |
793 | |
794 | //===----------------------------------------------------------------------===// |
795 | // Extra additions for arrays |
796 | //===----------------------------------------------------------------------===// |
797 | |
798 | /// Find the length of an array. |
799 | template <class T, std::size_t N> |
800 | constexpr inline size_t array_lengthof(T (&)[N]) { |
801 | return N; |
802 | } |
803 | |
804 | /// Adapt std::less<T> for array_pod_sort. |
805 | template<typename T> |
806 | inline int array_pod_sort_comparator(const void *P1, const void *P2) { |
807 | if (std::less<T>()(*reinterpret_cast<const T*>(P1), |
808 | *reinterpret_cast<const T*>(P2))) |
809 | return -1; |
810 | if (std::less<T>()(*reinterpret_cast<const T*>(P2), |
811 | *reinterpret_cast<const T*>(P1))) |
812 | return 1; |
813 | return 0; |
814 | } |
815 | |
816 | /// get_array_pod_sort_comparator - This is an internal helper function used to |
817 | /// get type deduction of T right. |
818 | template<typename T> |
819 | inline int (*get_array_pod_sort_comparator(const T &)) |
820 | (const void*, const void*) { |
821 | return array_pod_sort_comparator<T>; |
822 | } |
823 | |
824 | /// array_pod_sort - This sorts an array with the specified start and end |
825 | /// extent. This is just like std::sort, except that it calls qsort instead of |
826 | /// using an inlined template. qsort is slightly slower than std::sort, but |
827 | /// most sorts are not performance critical in LLVM and std::sort has to be |
828 | /// template instantiated for each type, leading to significant measured code |
829 | /// bloat. This function should generally be used instead of std::sort where |
830 | /// possible. |
831 | /// |
832 | /// This function assumes that you have simple POD-like types that can be |
833 | /// compared with std::less and can be moved with memcpy. If this isn't true, |
834 | /// you should use std::sort. |
835 | /// |
836 | /// NOTE: If qsort_r were portable, we could allow a custom comparator and |
837 | /// default to std::less. |
838 | template<class IteratorTy> |
839 | inline void array_pod_sort(IteratorTy Start, IteratorTy End) { |
840 | // Don't inefficiently call qsort with one element or trigger undefined |
841 | // behavior with an empty sequence. |
842 | auto NElts = End - Start; |
843 | if (NElts <= 1) return; |
844 | #ifdef EXPENSIVE_CHECKS |
845 | std::mt19937 Generator(std::random_device{}()); |
846 | std::shuffle(Start, End, Generator); |
847 | #endif |
848 | qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start)); |
849 | } |
850 | |
851 | template <class IteratorTy> |
852 | inline void array_pod_sort( |
853 | IteratorTy Start, IteratorTy End, |
854 | int (*Compare)( |
855 | const typename std::iterator_traits<IteratorTy>::value_type *, |
856 | const typename std::iterator_traits<IteratorTy>::value_type *)) { |
857 | // Don't inefficiently call qsort with one element or trigger undefined |
858 | // behavior with an empty sequence. |
859 | auto NElts = End - Start; |
860 | if (NElts <= 1) return; |
861 | #ifdef EXPENSIVE_CHECKS |
862 | std::mt19937 Generator(std::random_device{}()); |
863 | std::shuffle(Start, End, Generator); |
864 | #endif |
865 | qsort(&*Start, NElts, sizeof(*Start), |
866 | reinterpret_cast<int (*)(const void *, const void *)>(Compare)); |
867 | } |
868 | |
869 | // Provide wrappers to std::sort which shuffle the elements before sorting |
870 | // to help uncover non-deterministic behavior (PR35135). |
871 | template <typename IteratorTy> |
872 | inline void sort(IteratorTy Start, IteratorTy End) { |
873 | #ifdef EXPENSIVE_CHECKS |
874 | std::mt19937 Generator(std::random_device{}()); |
875 | std::shuffle(Start, End, Generator); |
876 | #endif |
877 | std::sort(Start, End); |
878 | } |
879 | |
880 | template <typename IteratorTy, typename Compare> |
881 | inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) { |
882 | #ifdef EXPENSIVE_CHECKS |
883 | std::mt19937 Generator(std::random_device{}()); |
884 | std::shuffle(Start, End, Generator); |
885 | #endif |
886 | std::sort(Start, End, Comp); |
887 | } |
888 | |
889 | //===----------------------------------------------------------------------===// |
890 | // Extra additions to <algorithm> |
891 | //===----------------------------------------------------------------------===// |
892 | |
893 | /// For a container of pointers, deletes the pointers and then clears the |
894 | /// container. |
895 | template<typename Container> |
896 | void DeleteContainerPointers(Container &C) { |
897 | for (auto V : C) |
898 | delete V; |
899 | C.clear(); |
900 | } |
901 | |
902 | /// In a container of pairs (usually a map) whose second element is a pointer, |
903 | /// deletes the second elements and then clears the container. |
904 | template<typename Container> |
905 | void DeleteContainerSeconds(Container &C) { |
906 | for (auto &V : C) |
907 | delete V.second; |
908 | C.clear(); |
909 | } |
910 | |
911 | /// Provide wrappers to std::for_each which take ranges instead of having to |
912 | /// pass begin/end explicitly. |
913 | template <typename R, typename UnaryPredicate> |
914 | UnaryPredicate for_each(R &&Range, UnaryPredicate P) { |
915 | return std::for_each(adl_begin(Range), adl_end(Range), P); |
916 | } |
917 | |
918 | /// Provide wrappers to std::all_of which take ranges instead of having to pass |
919 | /// begin/end explicitly. |
920 | template <typename R, typename UnaryPredicate> |
921 | bool all_of(R &&Range, UnaryPredicate P) { |
922 | return std::all_of(adl_begin(Range), adl_end(Range), P); |
923 | } |
924 | |
925 | /// Provide wrappers to std::any_of which take ranges instead of having to pass |
926 | /// begin/end explicitly. |
927 | template <typename R, typename UnaryPredicate> |
928 | bool any_of(R &&Range, UnaryPredicate P) { |
929 | return std::any_of(adl_begin(Range), adl_end(Range), P); |
930 | } |
931 | |
932 | /// Provide wrappers to std::none_of which take ranges instead of having to pass |
933 | /// begin/end explicitly. |
934 | template <typename R, typename UnaryPredicate> |
935 | bool none_of(R &&Range, UnaryPredicate P) { |
936 | return std::none_of(adl_begin(Range), adl_end(Range), P); |
937 | } |
938 | |
939 | /// Provide wrappers to std::find which take ranges instead of having to pass |
940 | /// begin/end explicitly. |
941 | template <typename R, typename T> |
942 | auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) { |
943 | return std::find(adl_begin(Range), adl_end(Range), Val); |
944 | } |
945 | |
946 | /// Provide wrappers to std::find_if which take ranges instead of having to pass |
947 | /// begin/end explicitly. |
948 | template <typename R, typename UnaryPredicate> |
949 | auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) { |
950 | return std::find_if(adl_begin(Range), adl_end(Range), P); |
951 | } |
952 | |
953 | template <typename R, typename UnaryPredicate> |
954 | auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) { |
955 | return std::find_if_not(adl_begin(Range), adl_end(Range), P); |
956 | } |
957 | |
958 | /// Provide wrappers to std::remove_if which take ranges instead of having to |
959 | /// pass begin/end explicitly. |
960 | template <typename R, typename UnaryPredicate> |
961 | auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) { |
962 | return std::remove_if(adl_begin(Range), adl_end(Range), P); |
963 | } |
964 | |
965 | /// Provide wrappers to std::copy_if which take ranges instead of having to |
966 | /// pass begin/end explicitly. |
967 | template <typename R, typename OutputIt, typename UnaryPredicate> |
968 | OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) { |
969 | return std::copy_if(adl_begin(Range), adl_end(Range), Out, P); |
970 | } |
971 | |
972 | template <typename R, typename OutputIt> |
973 | OutputIt copy(R &&Range, OutputIt Out) { |
974 | return std::copy(adl_begin(Range), adl_end(Range), Out); |
975 | } |
976 | |
977 | /// Wrapper function around std::find to detect if an element exists |
978 | /// in a container. |
979 | template <typename R, typename E> |
980 | bool is_contained(R &&Range, const E &Element) { |
981 | return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range); |
982 | } |
983 | |
984 | /// Wrapper function around std::count to count the number of times an element |
985 | /// \p Element occurs in the given range \p Range. |
986 | template <typename R, typename E> |
987 | auto count(R &&Range, const E &Element) -> |
988 | typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type { |
989 | return std::count(adl_begin(Range), adl_end(Range), Element); |
990 | } |
991 | |
992 | /// Wrapper function around std::count_if to count the number of times an |
993 | /// element satisfying a given predicate occurs in a range. |
994 | template <typename R, typename UnaryPredicate> |
995 | auto count_if(R &&Range, UnaryPredicate P) -> |
996 | typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type { |
997 | return std::count_if(adl_begin(Range), adl_end(Range), P); |
998 | } |
999 | |
1000 | /// Wrapper function around std::transform to apply a function to a range and |
1001 | /// store the result elsewhere. |
1002 | template <typename R, typename OutputIt, typename UnaryPredicate> |
1003 | OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) { |
1004 | return std::transform(adl_begin(Range), adl_end(Range), d_first, P); |
1005 | } |
1006 | |
1007 | /// Provide wrappers to std::partition which take ranges instead of having to |
1008 | /// pass begin/end explicitly. |
1009 | template <typename R, typename UnaryPredicate> |
1010 | auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) { |
1011 | return std::partition(adl_begin(Range), adl_end(Range), P); |
1012 | } |
1013 | |
1014 | /// Provide wrappers to std::lower_bound which take ranges instead of having to |
1015 | /// pass begin/end explicitly. |
1016 | template <typename R, typename ForwardIt> |
1017 | auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) { |
1018 | return std::lower_bound(adl_begin(Range), adl_end(Range), I); |
1019 | } |
1020 | |
1021 | /// Given a range of type R, iterate the entire range and return a |
1022 | /// SmallVector with elements of the vector. This is useful, for example, |
1023 | /// when you want to iterate a range and then sort the results. |
1024 | template <unsigned Size, typename R> |
1025 | SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size> |
1026 | to_vector(R &&Range) { |
1027 | return {adl_begin(Range), adl_end(Range)}; |
1028 | } |
1029 | |
1030 | /// Provide a container algorithm similar to C++ Library Fundamentals v2's |
1031 | /// `erase_if` which is equivalent to: |
1032 | /// |
1033 | /// C.erase(remove_if(C, pred), C.end()); |
1034 | /// |
1035 | /// This version works for any container with an erase method call accepting |
1036 | /// two iterators. |
1037 | template <typename Container, typename UnaryPredicate> |
1038 | void erase_if(Container &C, UnaryPredicate P) { |
1039 | C.erase(remove_if(C, P), C.end()); |
1040 | } |
1041 | |
1042 | /// Get the size of a range. This is a wrapper function around std::distance |
1043 | /// which is only enabled when the operation is O(1). |
1044 | template <typename R> |
1045 | auto size(R &&Range, typename std::enable_if< |
1046 | std::is_same<typename std::iterator_traits<decltype( |
1047 | Range.begin())>::iterator_category, |
1048 | std::random_access_iterator_tag>::value, |
1049 | void>::type * = nullptr) |
1050 | -> decltype(std::distance(Range.begin(), Range.end())) { |
1051 | return std::distance(Range.begin(), Range.end()); |
1052 | } |
1053 | |
1054 | //===----------------------------------------------------------------------===// |
1055 | // Extra additions to <memory> |
1056 | //===----------------------------------------------------------------------===// |
1057 | |
1058 | // Implement make_unique according to N3656. |
1059 | |
1060 | /// Constructs a `new T()` with the given args and returns a |
1061 | /// `unique_ptr<T>` which owns the object. |
1062 | /// |
1063 | /// Example: |
1064 | /// |
1065 | /// auto p = make_unique<int>(); |
1066 | /// auto p = make_unique<std::tuple<int, int>>(0, 1); |
1067 | template <class T, class... Args> |
1068 | typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type |
1069 | make_unique(Args &&... args) { |
1070 | return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); |
1071 | } |
1072 | |
1073 | /// Constructs a `new T[n]` with the given args and returns a |
1074 | /// `unique_ptr<T[]>` which owns the object. |
1075 | /// |
1076 | /// \param n size of the new array. |
1077 | /// |
1078 | /// Example: |
1079 | /// |
1080 | /// auto p = make_unique<int[]>(2); // value-initializes the array with 0's. |
1081 | template <class T> |
1082 | typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0, |
1083 | std::unique_ptr<T>>::type |
1084 | make_unique(size_t n) { |
1085 | return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]()); |
1086 | } |
1087 | |
1088 | /// This function isn't used and is only here to provide better compile errors. |
1089 | template <class T, class... Args> |
1090 | typename std::enable_if<std::extent<T>::value != 0>::type |
1091 | make_unique(Args &&...) = delete; |
1092 | |
1093 | struct FreeDeleter { |
1094 | void operator()(void* v) { |
1095 | ::free(v); |
1096 | } |
1097 | }; |
1098 | |
1099 | template<typename First, typename Second> |
1100 | struct pair_hash { |
1101 | size_t operator()(const std::pair<First, Second> &P) const { |
1102 | return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second); |
1103 | } |
1104 | }; |
1105 | |
1106 | /// A functor like C++14's std::less<void> in its absence. |
1107 | struct less { |
1108 | template <typename A, typename B> bool operator()(A &&a, B &&b) const { |
1109 | return std::forward<A>(a) < std::forward<B>(b); |
1110 | } |
1111 | }; |
1112 | |
1113 | /// A functor like C++14's std::equal<void> in its absence. |
1114 | struct equal { |
1115 | template <typename A, typename B> bool operator()(A &&a, B &&b) const { |
1116 | return std::forward<A>(a) == std::forward<B>(b); |
1117 | } |
1118 | }; |
1119 | |
1120 | /// Binary functor that adapts to any other binary functor after dereferencing |
1121 | /// operands. |
1122 | template <typename T> struct deref { |
1123 | T func; |
1124 | |
1125 | // Could be further improved to cope with non-derivable functors and |
1126 | // non-binary functors (should be a variadic template member function |
1127 | // operator()). |
1128 | template <typename A, typename B> |
1129 | auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) { |
1130 | assert(lhs)(static_cast <bool> (lhs) ? void (0) : __assert_fail ("lhs" , "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/STLExtras.h" , 1130, __extension__ __PRETTY_FUNCTION__)); |
1131 | assert(rhs)(static_cast <bool> (rhs) ? void (0) : __assert_fail ("rhs" , "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/STLExtras.h" , 1131, __extension__ __PRETTY_FUNCTION__)); |
1132 | return func(*lhs, *rhs); |
1133 | } |
1134 | }; |
1135 | |
1136 | namespace detail { |
1137 | |
1138 | template <typename R> class enumerator_iter; |
1139 | |
1140 | template <typename R> struct result_pair { |
1141 | friend class enumerator_iter<R>; |
1142 | |
1143 | result_pair() = default; |
1144 | result_pair(std::size_t Index, IterOfRange<R> Iter) |
1145 | : Index(Index), Iter(Iter) {} |
1146 | |
1147 | result_pair<R> &operator=(const result_pair<R> &Other) { |
1148 | Index = Other.Index; |
1149 | Iter = Other.Iter; |
1150 | return *this; |
1151 | } |
1152 | |
1153 | std::size_t index() const { return Index; } |
1154 | const ValueOfRange<R> &value() const { return *Iter; } |
1155 | ValueOfRange<R> &value() { return *Iter; } |
1156 | |
1157 | private: |
1158 | std::size_t Index = std::numeric_limits<std::size_t>::max(); |
1159 | IterOfRange<R> Iter; |
1160 | }; |
1161 | |
1162 | template <typename R> |
1163 | class enumerator_iter |
1164 | : public iterator_facade_base< |
1165 | enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>, |
1166 | typename std::iterator_traits<IterOfRange<R>>::difference_type, |
1167 | typename std::iterator_traits<IterOfRange<R>>::pointer, |
1168 | typename std::iterator_traits<IterOfRange<R>>::reference> { |
1169 | using result_type = result_pair<R>; |
1170 | |
1171 | public: |
1172 | explicit enumerator_iter(IterOfRange<R> EndIter) |
1173 | : Result(std::numeric_limits<size_t>::max(), EndIter) {} |
1174 | |
1175 | enumerator_iter(std::size_t Index, IterOfRange<R> Iter) |
1176 | : Result(Index, Iter) {} |
1177 | |
1178 | result_type &operator*() { return Result; } |
1179 | const result_type &operator*() const { return Result; } |
1180 | |
1181 | enumerator_iter<R> &operator++() { |
1182 | assert(Result.Index != std::numeric_limits<size_t>::max())(static_cast <bool> (Result.Index != std::numeric_limits <size_t>::max()) ? void (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()" , "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/STLExtras.h" , 1182, __extension__ __PRETTY_FUNCTION__)); |
1183 | ++Result.Iter; |
1184 | ++Result.Index; |
1185 | return *this; |
1186 | } |
1187 | |
1188 | bool operator==(const enumerator_iter<R> &RHS) const { |
1189 | // Don't compare indices here, only iterators. It's possible for an end |
1190 | // iterator to have different indices depending on whether it was created |
1191 | // by calling std::end() versus incrementing a valid iterator. |
1192 | return Result.Iter == RHS.Result.Iter; |
1193 | } |
1194 | |
1195 | enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) { |
1196 | Result = Other.Result; |
1197 | return *this; |
1198 | } |
1199 | |
1200 | private: |
1201 | result_type Result; |
1202 | }; |
1203 | |
1204 | template <typename R> class enumerator { |
1205 | public: |
1206 | explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {} |
1207 | |
1208 | enumerator_iter<R> begin() { |
1209 | return enumerator_iter<R>(0, std::begin(TheRange)); |
1210 | } |
1211 | |
1212 | enumerator_iter<R> end() { |
1213 | return enumerator_iter<R>(std::end(TheRange)); |
1214 | } |
1215 | |
1216 | private: |
1217 | R TheRange; |
1218 | }; |
1219 | |
1220 | } // end namespace detail |
1221 | |
1222 | /// Given an input range, returns a new range whose values are are pair (A,B) |
1223 | /// such that A is the 0-based index of the item in the sequence, and B is |
1224 | /// the value from the original sequence. Example: |
1225 | /// |
1226 | /// std::vector<char> Items = {'A', 'B', 'C', 'D'}; |
1227 | /// for (auto X : enumerate(Items)) { |
1228 | /// printf("Item %d - %c\n", X.index(), X.value()); |
1229 | /// } |
1230 | /// |
1231 | /// Output: |
1232 | /// Item 0 - A |
1233 | /// Item 1 - B |
1234 | /// Item 2 - C |
1235 | /// Item 3 - D |
1236 | /// |
1237 | template <typename R> detail::enumerator<R> enumerate(R &&TheRange) { |
1238 | return detail::enumerator<R>(std::forward<R>(TheRange)); |
1239 | } |
1240 | |
1241 | namespace detail { |
1242 | |
1243 | template <typename F, typename Tuple, std::size_t... I> |
1244 | auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>) |
1245 | -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) { |
1246 | return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...); |
1247 | } |
1248 | |
1249 | } // end namespace detail |
1250 | |
1251 | /// Given an input tuple (a1, a2, ..., an), pass the arguments of the |
1252 | /// tuple variadically to f as if by calling f(a1, a2, ..., an) and |
1253 | /// return the result. |
1254 | template <typename F, typename Tuple> |
1255 | auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl( |
1256 | std::forward<F>(f), std::forward<Tuple>(t), |
1257 | build_index_impl< |
1258 | std::tuple_size<typename std::decay<Tuple>::type>::value>{})) { |
1259 | using Indices = build_index_impl< |
1260 | std::tuple_size<typename std::decay<Tuple>::type>::value>; |
1261 | |
1262 | return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t), |
1263 | Indices{}); |
1264 | } |
1265 | |
1266 | } // end namespace llvm |
1267 | |
1268 | #endif // LLVM_ADT_STLEXTRAS_H |
1 | //==- llvm/ADT/IntrusiveRefCntPtr.h - Smart Refcounting Pointer --*- C++ -*-==// | |||
2 | // | |||
3 | // The LLVM Compiler Infrastructure | |||
4 | // | |||
5 | // This file is distributed under the University of Illinois Open Source | |||
6 | // License. See LICENSE.TXT for details. | |||
7 | // | |||
8 | //===----------------------------------------------------------------------===// | |||
9 | // | |||
10 | // This file defines the RefCountedBase, ThreadSafeRefCountedBase, and | |||
11 | // IntrusiveRefCntPtr classes. | |||
12 | // | |||
13 | // IntrusiveRefCntPtr is a smart pointer to an object which maintains a | |||
14 | // reference count. (ThreadSafe)RefCountedBase is a mixin class that adds a | |||
15 | // refcount member variable and methods for updating the refcount. An object | |||
16 | // that inherits from (ThreadSafe)RefCountedBase deletes itself when its | |||
17 | // refcount hits zero. | |||
18 | // | |||
19 | // For example: | |||
20 | // | |||
21 | // class MyClass : public RefCountedBase<MyClass> {}; | |||
22 | // | |||
23 | // void foo() { | |||
24 | // // Constructing an IntrusiveRefCntPtr increases the pointee's refcount by | |||
25 | // // 1 (from 0 in this case). | |||
26 | // IntrusiveRefCntPtr<MyClass> Ptr1(new MyClass()); | |||
27 | // | |||
28 | // // Copying an IntrusiveRefCntPtr increases the pointee's refcount by 1. | |||
29 | // IntrusiveRefCntPtr<MyClass> Ptr2(Ptr1); | |||
30 | // | |||
31 | // // Constructing an IntrusiveRefCntPtr has no effect on the object's | |||
32 | // // refcount. After a move, the moved-from pointer is null. | |||
33 | // IntrusiveRefCntPtr<MyClass> Ptr3(std::move(Ptr1)); | |||
34 | // assert(Ptr1 == nullptr); | |||
35 | // | |||
36 | // // Clearing an IntrusiveRefCntPtr decreases the pointee's refcount by 1. | |||
37 | // Ptr2.reset(); | |||
38 | // | |||
39 | // // The object deletes itself when we return from the function, because | |||
40 | // // Ptr3's destructor decrements its refcount to 0. | |||
41 | // } | |||
42 | // | |||
43 | // You can use IntrusiveRefCntPtr with isa<T>(), dyn_cast<T>(), etc.: | |||
44 | // | |||
45 | // IntrusiveRefCntPtr<MyClass> Ptr(new MyClass()); | |||
46 | // OtherClass *Other = dyn_cast<OtherClass>(Ptr); // Ptr.get() not required | |||
47 | // | |||
48 | // IntrusiveRefCntPtr works with any class that | |||
49 | // | |||
50 | // - inherits from (ThreadSafe)RefCountedBase, | |||
51 | // - has Retain() and Release() methods, or | |||
52 | // - specializes IntrusiveRefCntPtrInfo. | |||
53 | // | |||
54 | //===----------------------------------------------------------------------===// | |||
55 | ||||
56 | #ifndef LLVM_ADT_INTRUSIVEREFCNTPTR_H | |||
57 | #define LLVM_ADT_INTRUSIVEREFCNTPTR_H | |||
58 | ||||
59 | #include <atomic> | |||
60 | #include <cassert> | |||
61 | #include <cstddef> | |||
62 | ||||
63 | namespace llvm { | |||
64 | ||||
65 | /// A CRTP mixin class that adds reference counting to a type. | |||
66 | /// | |||
67 | /// The lifetime of an object which inherits from RefCountedBase is managed by | |||
68 | /// calls to Release() and Retain(), which increment and decrement the object's | |||
69 | /// refcount, respectively. When a Release() call decrements the refcount to 0, | |||
70 | /// the object deletes itself. | |||
71 | template <class Derived> class RefCountedBase { | |||
72 | mutable unsigned RefCount = 0; | |||
73 | ||||
74 | public: | |||
75 | RefCountedBase() = default; | |||
76 | RefCountedBase(const RefCountedBase &) {} | |||
77 | ||||
78 | void Retain() const { ++RefCount; } | |||
79 | ||||
80 | void Release() const { | |||
81 | assert(RefCount > 0 && "Reference count is already zero.")(static_cast <bool> (RefCount > 0 && "Reference count is already zero." ) ? void (0) : __assert_fail ("RefCount > 0 && \"Reference count is already zero.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/IntrusiveRefCntPtr.h" , 81, __extension__ __PRETTY_FUNCTION__)); | |||
82 | if (--RefCount == 0) | |||
83 | delete static_cast<const Derived *>(this); | |||
84 | } | |||
85 | }; | |||
86 | ||||
87 | /// A thread-safe version of \c RefCountedBase. | |||
88 | template <class Derived> class ThreadSafeRefCountedBase { | |||
89 | mutable std::atomic<int> RefCount; | |||
90 | ||||
91 | protected: | |||
92 | ThreadSafeRefCountedBase() : RefCount(0) {} | |||
93 | ||||
94 | public: | |||
95 | void Retain() const { RefCount.fetch_add(1, std::memory_order_relaxed); } | |||
96 | ||||
97 | void Release() const { | |||
98 | int NewRefCount = RefCount.fetch_sub(1, std::memory_order_acq_rel) - 1; | |||
99 | assert(NewRefCount >= 0 && "Reference count was already zero.")(static_cast <bool> (NewRefCount >= 0 && "Reference count was already zero." ) ? void (0) : __assert_fail ("NewRefCount >= 0 && \"Reference count was already zero.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/IntrusiveRefCntPtr.h" , 99, __extension__ __PRETTY_FUNCTION__)); | |||
100 | if (NewRefCount == 0) | |||
101 | delete static_cast<const Derived *>(this); | |||
102 | } | |||
103 | }; | |||
104 | ||||
105 | /// Class you can specialize to provide custom retain/release functionality for | |||
106 | /// a type. | |||
107 | /// | |||
108 | /// Usually specializing this class is not necessary, as IntrusiveRefCntPtr | |||
109 | /// works with any type which defines Retain() and Release() functions -- you | |||
110 | /// can define those functions yourself if RefCountedBase doesn't work for you. | |||
111 | /// | |||
112 | /// One case when you might want to specialize this type is if you have | |||
113 | /// - Foo.h defines type Foo and includes Bar.h, and | |||
114 | /// - Bar.h uses IntrusiveRefCntPtr<Foo> in inline functions. | |||
115 | /// | |||
116 | /// Because Foo.h includes Bar.h, Bar.h can't include Foo.h in order to pull in | |||
117 | /// the declaration of Foo. Without the declaration of Foo, normally Bar.h | |||
118 | /// wouldn't be able to use IntrusiveRefCntPtr<Foo>, which wants to call | |||
119 | /// T::Retain and T::Release. | |||
120 | /// | |||
121 | /// To resolve this, Bar.h could include a third header, FooFwd.h, which | |||
122 | /// forward-declares Foo and specializes IntrusiveRefCntPtrInfo<Foo>. Then | |||
123 | /// Bar.h could use IntrusiveRefCntPtr<Foo>, although it still couldn't call any | |||
124 | /// functions on Foo itself, because Foo would be an incomplete type. | |||
125 | template <typename T> struct IntrusiveRefCntPtrInfo { | |||
126 | static void retain(T *obj) { obj->Retain(); } | |||
127 | static void release(T *obj) { obj->Release(); } | |||
128 | }; | |||
129 | ||||
130 | /// A smart pointer to a reference-counted object that inherits from | |||
131 | /// RefCountedBase or ThreadSafeRefCountedBase. | |||
132 | /// | |||
133 | /// This class increments its pointee's reference count when it is created, and | |||
134 | /// decrements its refcount when it's destroyed (or is changed to point to a | |||
135 | /// different object). | |||
136 | template <typename T> class IntrusiveRefCntPtr { | |||
137 | T *Obj = nullptr; | |||
138 | ||||
139 | public: | |||
140 | using element_type = T; | |||
141 | ||||
142 | explicit IntrusiveRefCntPtr() = default; | |||
143 | IntrusiveRefCntPtr(T *obj) : Obj(obj) { retain(); } | |||
144 | IntrusiveRefCntPtr(const IntrusiveRefCntPtr &S) : Obj(S.Obj) { retain(); } | |||
145 | IntrusiveRefCntPtr(IntrusiveRefCntPtr &&S) : Obj(S.Obj) { S.Obj = nullptr; } | |||
146 | ||||
147 | template <class X> | |||
148 | IntrusiveRefCntPtr(IntrusiveRefCntPtr<X> &&S) : Obj(S.get()) { | |||
149 | S.Obj = nullptr; | |||
150 | } | |||
151 | ||||
152 | template <class X> | |||
153 | IntrusiveRefCntPtr(const IntrusiveRefCntPtr<X> &S) : Obj(S.get()) { | |||
154 | retain(); | |||
155 | } | |||
156 | ||||
157 | ~IntrusiveRefCntPtr() { release(); } | |||
| ||||
158 | ||||
159 | IntrusiveRefCntPtr &operator=(IntrusiveRefCntPtr S) { | |||
160 | swap(S); | |||
161 | return *this; | |||
162 | } | |||
163 | ||||
164 | T &operator*() const { return *Obj; } | |||
165 | T *operator->() const { return Obj; } | |||
166 | T *get() const { return Obj; } | |||
167 | explicit operator bool() const { return Obj; } | |||
168 | ||||
169 | void swap(IntrusiveRefCntPtr &other) { | |||
170 | T *tmp = other.Obj; | |||
171 | other.Obj = Obj; | |||
172 | Obj = tmp; | |||
173 | } | |||
174 | ||||
175 | void reset() { | |||
176 | release(); | |||
177 | Obj = nullptr; | |||
178 | } | |||
179 | ||||
180 | void resetWithoutRelease() { Obj = nullptr; } | |||
181 | ||||
182 | private: | |||
183 | void retain() { | |||
184 | if (Obj) | |||
185 | IntrusiveRefCntPtrInfo<T>::retain(Obj); | |||
186 | } | |||
187 | ||||
188 | void release() { | |||
189 | if (Obj) | |||
190 | IntrusiveRefCntPtrInfo<T>::release(Obj); | |||
191 | } | |||
192 | ||||
193 | template <typename X> friend class IntrusiveRefCntPtr; | |||
194 | }; | |||
195 | ||||
196 | template <class T, class U> | |||
197 | inline bool operator==(const IntrusiveRefCntPtr<T> &A, | |||
198 | const IntrusiveRefCntPtr<U> &B) { | |||
199 | return A.get() == B.get(); | |||
200 | } | |||
201 | ||||
202 | template <class T, class U> | |||
203 | inline bool operator!=(const IntrusiveRefCntPtr<T> &A, | |||
204 | const IntrusiveRefCntPtr<U> &B) { | |||
205 | return A.get() != B.get(); | |||
206 | } | |||
207 | ||||
208 | template <class T, class U> | |||
209 | inline bool operator==(const IntrusiveRefCntPtr<T> &A, U *B) { | |||
210 | return A.get() == B; | |||
211 | } | |||
212 | ||||
213 | template <class T, class U> | |||
214 | inline bool operator!=(const IntrusiveRefCntPtr<T> &A, U *B) { | |||
215 | return A.get() != B; | |||
216 | } | |||
217 | ||||
218 | template <class T, class U> | |||
219 | inline bool operator==(T *A, const IntrusiveRefCntPtr<U> &B) { | |||
220 | return A == B.get(); | |||
221 | } | |||
222 | ||||
223 | template <class T, class U> | |||
224 | inline bool operator!=(T *A, const IntrusiveRefCntPtr<U> &B) { | |||
225 | return A != B.get(); | |||
226 | } | |||
227 | ||||
228 | template <class T> | |||
229 | bool operator==(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) { | |||
230 | return !B; | |||
231 | } | |||
232 | ||||
233 | template <class T> | |||
234 | bool operator==(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) { | |||
235 | return B == A; | |||
236 | } | |||
237 | ||||
238 | template <class T> | |||
239 | bool operator!=(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) { | |||
240 | return !(A == B); | |||
241 | } | |||
242 | ||||
243 | template <class T> | |||
244 | bool operator!=(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) { | |||
245 | return !(A == B); | |||
246 | } | |||
247 | ||||
248 | // Make IntrusiveRefCntPtr work with dyn_cast, isa, and the other idioms from | |||
249 | // Casting.h. | |||
250 | template <typename From> struct simplify_type; | |||
251 | ||||
252 | template <class T> struct simplify_type<IntrusiveRefCntPtr<T>> { | |||
253 | using SimpleType = T *; | |||
254 | ||||
255 | static SimpleType getSimplifiedValue(IntrusiveRefCntPtr<T> &Val) { | |||
256 | return Val.get(); | |||
257 | } | |||
258 | }; | |||
259 | ||||
260 | template <class T> struct simplify_type<const IntrusiveRefCntPtr<T>> { | |||
261 | using SimpleType = /*const*/ T *; | |||
262 | ||||
263 | static SimpleType getSimplifiedValue(const IntrusiveRefCntPtr<T> &Val) { | |||
264 | return Val.get(); | |||
265 | } | |||
266 | }; | |||
267 | ||||
268 | } // end namespace llvm | |||
269 | ||||
270 | #endif // LLVM_ADT_INTRUSIVEREFCNTPTR_H |