Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Basic/SourceManager.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- SourceManager.cpp - Track and cache source files -------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the SourceManager interface.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Basic/SourceManager.h"
14
#include "clang/Basic/Diagnostic.h"
15
#include "clang/Basic/FileManager.h"
16
#include "clang/Basic/LLVM.h"
17
#include "clang/Basic/SourceLocation.h"
18
#include "clang/Basic/SourceManagerInternals.h"
19
#include "llvm/ADT/DenseMap.h"
20
#include "llvm/ADT/None.h"
21
#include "llvm/ADT/Optional.h"
22
#include "llvm/ADT/STLExtras.h"
23
#include "llvm/ADT/SmallVector.h"
24
#include "llvm/ADT/StringRef.h"
25
#include "llvm/ADT/StringSwitch.h"
26
#include "llvm/Support/Allocator.h"
27
#include "llvm/Support/Capacity.h"
28
#include "llvm/Support/Compiler.h"
29
#include "llvm/Support/Endian.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
/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
54
/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
55
7
unsigned ContentCache::getSizeBytesMapped() const {
56
7
  return Buffer ? Buffer->getBufferSize() : 
00
;
57
7
}
58
59
/// Returns the kind of memory used to back the memory buffer for
60
/// this content cache.  This is used for performance analysis.
61
1
llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
62
1
  assert(Buffer);
63
64
  // Should be unreachable, but keep for sanity.
65
1
  if (!Buffer)
66
0
    return llvm::MemoryBuffer::MemoryBuffer_Malloc;
67
68
1
  return Buffer->getBufferKind();
69
1
}
70
71
/// getSize - Returns the size of the content encapsulated by this ContentCache.
72
///  This can be the size of the source file or the size of an arbitrary
73
///  scratch buffer.  If the ContentCache encapsulates a source file, that
74
///  file is not lazily brought in from disk to satisfy this query.
75
976k
unsigned ContentCache::getSize() const {
76
976k
  return Buffer ? 
(unsigned)Buffer->getBufferSize()333k
77
976k
                : 
(unsigned)ContentsEntry->getSize()642k
;
78
976k
}
79
80
684k
const char *ContentCache::getInvalidBOM(StringRef BufStr) {
81
  // If the buffer is valid, check to see if it has a UTF Byte Order Mark
82
  // (BOM).  We only support UTF-8 with and without a BOM right now.  See
83
  // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
84
684k
  const char *InvalidBOM =
85
684k
      llvm::StringSwitch<const char *>(BufStr)
86
684k
          .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
87
684k
                      "UTF-32 (BE)")
88
684k
          .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
89
684k
                      "UTF-32 (LE)")
90
684k
          .StartsWith("\xFE\xFF", "UTF-16 (BE)")
91
684k
          .StartsWith("\xFF\xFE", "UTF-16 (LE)")
92
684k
          .StartsWith("\x2B\x2F\x76", "UTF-7")
93
684k
          .StartsWith("\xF7\x64\x4C", "UTF-1")
94
684k
          .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
95
684k
          .StartsWith("\x0E\xFE\xFF", "SCSU")
96
684k
          .StartsWith("\xFB\xEE\x28", "BOCU-1")
97
684k
          .StartsWith("\x84\x31\x95\x33", "GB-18030")
98
684k
          .Default(nullptr);
99
100
684k
  return InvalidBOM;
101
684k
}
102
103
llvm::Optional<llvm::MemoryBufferRef>
104
ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
105
279M
                              SourceLocation Loc) const {
106
  // Lazily create the Buffer for ContentCaches that wrap files.  If we already
107
  // computed it, just return what we have.
108
279M
  if (IsBufferInvalid)
109
2
    return None;
110
279M
  if (Buffer)
111
278M
    return Buffer->getMemBufferRef();
112
684k
  if (!ContentsEntry)
113
0
    return None;
114
115
  // Start with the assumption that the buffer is invalid to simplify early
116
  // return paths.
117
684k
  IsBufferInvalid = true;
118
119
684k
  auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
120
121
  // If we were unable to open the file, then we are in an inconsistent
122
  // situation where the content cache referenced a file which no longer
123
  // exists. Most likely, we were using a stat cache with an invalid entry but
124
  // the file could also have been removed during processing. Since we can't
125
  // really deal with this situation, just create an empty buffer.
126
684k
  if (!BufferOrError) {
127
1
    if (Diag.isDiagnosticInFlight())
128
0
      Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
129
0
                                ContentsEntry->getName(),
130
0
                                BufferOrError.getError().message());
131
1
    else
132
1
      Diag.Report(Loc, diag::err_cannot_open_file)
133
1
          << ContentsEntry->getName() << BufferOrError.getError().message();
134
135
1
    return None;
136
1
  }
137
138
684k
  Buffer = std::move(*BufferOrError);
139
140
  // Check that the file's size fits in an 'unsigned' (with room for a
141
  // past-the-end value). This is deeply regrettable, but various parts of
142
  // Clang (including elsewhere in this file!) use 'unsigned' to represent file
143
  // offsets, line numbers, string literal lengths, and so on, and fail
144
  // miserably on large source files.
145
  //
146
  // Note: ContentsEntry could be a named pipe, in which case
147
  // ContentsEntry::getSize() could have the wrong size. Use
148
  // MemoryBuffer::getBufferSize() instead.
149
684k
  if (Buffer->getBufferSize() >= std::numeric_limits<unsigned>::max()) {
150
0
    if (Diag.isDiagnosticInFlight())
151
0
      Diag.SetDelayedDiagnostic(diag::err_file_too_large,
152
0
                                ContentsEntry->getName());
153
0
    else
154
0
      Diag.Report(Loc, diag::err_file_too_large)
155
0
        << ContentsEntry->getName();
156
157
0
    return None;
158
0
  }
159
160
  // Unless this is a named pipe (in which case we can handle a mismatch),
161
  // check that the file's size is the same as in the file entry (which may
162
  // have come from a stat cache).
163
684k
  if (!ContentsEntry->isNamedPipe() &&
164
684k
      
Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()684k
) {
165
0
    if (Diag.isDiagnosticInFlight())
166
0
      Diag.SetDelayedDiagnostic(diag::err_file_modified,
167
0
                                ContentsEntry->getName());
168
0
    else
169
0
      Diag.Report(Loc, diag::err_file_modified)
170
0
        << ContentsEntry->getName();
171
172
0
    return None;
173
0
  }
174
175
  // If the buffer is valid, check to see if it has a UTF Byte Order Mark
176
  // (BOM).  We only support UTF-8 with and without a BOM right now.  See
177
  // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
178
684k
  StringRef BufStr = Buffer->getBuffer();
179
684k
  const char *InvalidBOM = getInvalidBOM(BufStr);
180
181
684k
  if (InvalidBOM) {
182
1
    Diag.Report(Loc, diag::err_unsupported_bom)
183
1
      << InvalidBOM << ContentsEntry->getName();
184
1
    return None;
185
1
  }
186
187
  // Buffer has been validated.
188
684k
  IsBufferInvalid = false;
189
684k
  return Buffer->getMemBufferRef();
190
684k
}
191
192
918k
unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
193
918k
  auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
194
918k
  if (IterBool.second)
195
800k
    FilenamesByID.push_back(&*IterBool.first);
196
918k
  return IterBool.first->second;
197
918k
}
198
199
/// Add a line note to the line table that indicates that there is a \#line or
200
/// GNU line marker at the specified FID/Offset location which changes the
201
/// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
202
/// change the presumed \#include stack.  If it is 1, this is a file entry, if
203
/// it is 2 then this is a file exit. FileKind specifies whether this is a
204
/// system header or extern C system header.
205
void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
206
                                int FilenameID, unsigned EntryExit,
207
468k
                                SrcMgr::CharacteristicKind FileKind) {
208
468k
  std::vector<LineEntry> &Entries = LineEntries[FID];
209
210
  // An unspecified FilenameID means use the last filename if available, or the
211
  // main source file otherwise.
212
468k
  if (FilenameID == -1 && 
!Entries.empty()1.87k
)
213
1.68k
    FilenameID = Entries.back().FilenameID;
214
215
468k
  assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
216
468k
         "Adding line entries out of order!");
217
218
0
  unsigned IncludeOffset = 0;
219
468k
  if (EntryExit == 0) {  // No #include stack change.
220
279k
    IncludeOffset = Entries.empty() ? 
0233k
:
Entries.back().IncludeOffset46.1k
;
221
279k
  } else 
if (189k
EntryExit == 1189k
) {
222
94.6k
    IncludeOffset = Offset-1;
223
94.6k
  } else 
if (94.6k
EntryExit == 294.6k
) {
224
94.6k
    assert(!Entries.empty() && Entries.back().IncludeOffset &&
225
94.6k
       "PPDirectives should have caught case when popping empty include stack");
226
227
    // Get the include loc of the last entries' include loc as our include loc.
228
0
    IncludeOffset = 0;
229
94.6k
    if (const LineEntry *PrevEntry =
230
94.6k
          FindNearestLineEntry(FID, Entries.back().IncludeOffset))
231
94.6k
      IncludeOffset = PrevEntry->IncludeOffset;
232
94.6k
  }
233
234
0
  Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
235
468k
                                   IncludeOffset));
236
468k
}
237
238
/// FindNearestLineEntry - Find the line entry nearest to FID that is before
239
/// it.  If there is no line entry before Offset in FID, return null.
240
const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
241
127M
                                                     unsigned Offset) {
242
127M
  const std::vector<LineEntry> &Entries = LineEntries[FID];
243
127M
  assert(!Entries.empty() && "No #line entries for this FID after all!");
244
245
  // It is very common for the query to be after the last #line, check this
246
  // first.
247
127M
  if (Entries.back().FileOffset <= Offset)
248
126M
    return &Entries.back();
249
250
  // Do a binary search to find the maximal element that is still before Offset.
251
1.39M
  std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
252
1.39M
  if (I == Entries.begin())
253
1.25M
    return nullptr;
254
143k
  return &*--I;
255
1.39M
}
256
257
/// Add a new line entry that has already been encoded into
258
/// the internal representation of the line table.
259
void LineTableInfo::AddEntry(FileID FID,
260
433k
                             const std::vector<LineEntry> &Entries) {
261
433k
  LineEntries[FID] = Entries;
262
433k
}
263
264
/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
265
467k
unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
266
467k
  return getLineTable().getLineTableFilenameID(Name);
267
467k
}
268
269
/// AddLineNote - Add a line note to the line table for the FileID and offset
270
/// specified by Loc.  If FilenameID is -1, it is considered to be
271
/// unspecified.
272
void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
273
                                int FilenameID, bool IsFileEntry,
274
                                bool IsFileExit,
275
468k
                                SrcMgr::CharacteristicKind FileKind) {
276
468k
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
277
278
468k
  bool Invalid = false;
279
468k
  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
280
468k
  if (!Entry.isFile() || 
Invalid468k
)
281
0
    return;
282
283
468k
  const SrcMgr::FileInfo &FileInfo = Entry.getFile();
284
285
  // Remember that this file has #line directives now if it doesn't already.
286
468k
  const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
287
288
468k
  (void) getLineTable();
289
290
468k
  unsigned EntryExit = 0;
291
468k
  if (IsFileEntry)
292
94.6k
    EntryExit = 1;
293
374k
  else if (IsFileExit)
294
94.6k
    EntryExit = 2;
295
296
468k
  LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
297
468k
                         EntryExit, FileKind);
298
468k
}
299
300
959k
LineTableInfo &SourceManager::getLineTable() {
301
959k
  if (!LineTable)
302
98.1k
    LineTable.reset(new LineTableInfo());
303
959k
  return *LineTable;
304
959k
}
305
306
//===----------------------------------------------------------------------===//
307
// Private 'Create' methods.
308
//===----------------------------------------------------------------------===//
309
310
SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
311
                             bool UserFilesAreVolatile)
312
221k
  : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
313
221k
  clearIDTables();
314
221k
  Diag.setSourceManager(this);
315
221k
}
316
317
215k
SourceManager::~SourceManager() {
318
  // Delete FileEntry objects corresponding to content caches.  Since the actual
319
  // content cache objects are bump pointer allocated, we just have to run the
320
  // dtors, but we call the deallocate method for completeness.
321
400k
  for (unsigned i = 0, e = MemBufferInfos.size(); i != e; 
++i184k
) {
322
184k
    if (MemBufferInfos[i]) {
323
184k
      MemBufferInfos[i]->~ContentCache();
324
184k
      ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
325
184k
    }
326
184k
  }
327
215k
  for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
328
650k
       I = FileInfos.begin(), E = FileInfos.end(); I != E; 
++I434k
) {
329
434k
    if (I->second) {
330
434k
      I->second->~ContentCache();
331
434k
      ContentCacheAlloc.Deallocate(I->second);
332
434k
    }
333
434k
  }
334
215k
}
335
336
242k
void SourceManager::clearIDTables() {
337
242k
  MainFileID = FileID();
338
242k
  LocalSLocEntryTable.clear();
339
242k
  LoadedSLocEntryTable.clear();
340
242k
  SLocEntryLoaded.clear();
341
242k
  LastLineNoFileIDQuery = FileID();
342
242k
  LastLineNoContentCache = nullptr;
343
242k
  LastFileIDLookup = FileID();
344
345
242k
  if (LineTable)
346
50
    LineTable->clear();
347
348
  // Use up FileID #0 as an invalid expansion.
349
242k
  NextLocalOffset = 0;
350
242k
  CurrentLoadedOffset = MaxLoadedOffset;
351
242k
  createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
352
242k
}
353
354
78
bool SourceManager::isMainFile(const FileEntry &SourceFile) {
355
78
  assert(MainFileID.isValid() && "expected initialized SourceManager");
356
78
  if (auto *FE = getFileEntryForID(MainFileID))
357
77
    return FE->getUID() == SourceFile.getUID();
358
1
  return false;
359
78
}
360
361
15
void SourceManager::initializeForReplay(const SourceManager &Old) {
362
15
  assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
363
364
52
  auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
365
52
    auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
366
52
    Clone->OrigEntry = Cache->OrigEntry;
367
52
    Clone->ContentsEntry = Cache->ContentsEntry;
368
52
    Clone->BufferOverridden = Cache->BufferOverridden;
369
52
    Clone->IsFileVolatile = Cache->IsFileVolatile;
370
52
    Clone->IsTransient = Cache->IsTransient;
371
52
    Clone->setUnownedBuffer(Cache->getBufferIfLoaded());
372
52
    return Clone;
373
52
  };
374
375
  // Ensure all SLocEntries are loaded from the external source.
376
142
  for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; 
++I127
)
377
127
    if (!Old.SLocEntryLoaded[I])
378
102
      Old.loadSLocEntry(I, nullptr);
379
380
  // Inherit any content cache data from the old source manager.
381
52
  for (auto &FileInfo : Old.FileInfos) {
382
52
    SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
383
52
    if (Slot)
384
0
      continue;
385
52
    Slot = CloneContentCache(FileInfo.second);
386
52
  }
387
15
}
388
389
ContentCache &SourceManager::getOrCreateContentCache(FileEntryRef FileEnt,
390
1.87M
                                                     bool isSystemFile) {
391
  // Do we already have information about this file?
392
1.87M
  ContentCache *&Entry = FileInfos[FileEnt];
393
1.87M
  if (Entry)
394
985k
    return *Entry;
395
396
  // Nope, create a new Cache entry.
397
893k
  Entry = ContentCacheAlloc.Allocate<ContentCache>();
398
399
893k
  if (OverriddenFilesInfo) {
400
    // If the file contents are overridden with contents from another file,
401
    // pass that file to ContentCache.
402
84.0k
    llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
403
84.0k
        overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
404
84.0k
    if (overI == OverriddenFilesInfo->OverriddenFiles.end())
405
84.0k
      new (Entry) ContentCache(FileEnt);
406
11
    else
407
11
      new (Entry) ContentCache(OverridenFilesKeepOriginalName ? 
FileEnt7
408
11
                                                              : 
overI->second4
,
409
11
                               overI->second);
410
809k
  } else {
411
809k
    new (Entry) ContentCache(FileEnt);
412
809k
  }
413
414
893k
  Entry->IsFileVolatile = UserFilesAreVolatile && 
!isSystemFile2.70k
;
415
893k
  Entry->IsTransient = FilesAreTransient;
416
893k
  Entry->BufferOverridden |= FileEnt.isNamedPipe();
417
418
893k
  return *Entry;
419
1.87M
}
420
421
/// Create a new ContentCache for the specified memory buffer.
422
/// This does no caching.
423
ContentCache &SourceManager::createMemBufferContentCache(
424
255k
    std::unique_ptr<llvm::MemoryBuffer> Buffer) {
425
  // Add a new ContentCache to the MemBufferInfos list and return it.
426
255k
  ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
427
255k
  new (Entry) ContentCache();
428
255k
  MemBufferInfos.push_back(Entry);
429
255k
  Entry->setBuffer(std::move(Buffer));
430
255k
  return *Entry;
431
255k
}
432
433
const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
434
8.97M
                                                      bool *Invalid) const {
435
8.97M
  assert(!SLocEntryLoaded[Index]);
436
8.97M
  if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
437
94
    if (Invalid)
438
44
      *Invalid = true;
439
    // If the file of the SLocEntry changed we could still have loaded it.
440
94
    if (!SLocEntryLoaded[Index]) {
441
      // Try to recover; create a SLocEntry so the rest of clang can handle it.
442
94
      if (!FakeSLocEntryForRecovery)
443
2
        FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(SLocEntry::get(
444
2
            0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
445
2
                             SrcMgr::C_User, "")));
446
94
      return *FakeSLocEntryForRecovery;
447
94
    }
448
94
  }
449
450
8.97M
  return LoadedSLocEntryTable[Index];
451
8.97M
}
452
453
std::pair<int, SourceLocation::UIntTy>
454
SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
455
17.8k
                                         SourceLocation::UIntTy TotalSize) {
456
17.8k
  assert(ExternalSLocEntries && "Don't have an external sloc source");
457
  // Make sure we're not about to run out of source locations.
458
17.8k
  if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
459
0
    return std::make_pair(0, 0);
460
17.8k
  LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
461
17.8k
  SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
462
17.8k
  CurrentLoadedOffset -= TotalSize;
463
17.8k
  int ID = LoadedSLocEntryTable.size();
464
17.8k
  return std::make_pair(-ID - 1, CurrentLoadedOffset);
465
17.8k
}
466
467
/// As part of recovering from missing or changed content, produce a
468
/// fake, non-empty buffer.
469
5
llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery() const {
470
5
  if (!FakeBufferForRecovery)
471
5
    FakeBufferForRecovery =
472
5
        llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
473
474
5
  return *FakeBufferForRecovery;
475
5
}
476
477
/// As part of recovering from missing or changed content, produce a
478
/// fake content cache.
479
2
SrcMgr::ContentCache &SourceManager::getFakeContentCacheForRecovery() const {
480
2
  if (!FakeContentCacheForRecovery) {
481
2
    FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
482
2
    FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery());
483
2
  }
484
2
  return *FakeContentCacheForRecovery;
485
2
}
486
487
/// Returns the previous in-order FileID or an invalid FileID if there
488
/// is no previous one.
489
2.23M
FileID SourceManager::getPreviousFileID(FileID FID) const {
490
2.23M
  if (FID.isInvalid())
491
0
    return FileID();
492
493
2.23M
  int ID = FID.ID;
494
2.23M
  if (ID == -1)
495
0
    return FileID();
496
497
2.23M
  if (ID > 0) {
498
2.23M
    if (ID-1 == 0)
499
0
      return FileID();
500
2.23M
  } else 
if (0
unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()0
) {
501
0
    return FileID();
502
0
  }
503
504
2.23M
  return FileID::get(ID-1);
505
2.23M
}
506
507
/// Returns the next in-order FileID or an invalid FileID if there is
508
/// no next one.
509
46.6k
FileID SourceManager::getNextFileID(FileID FID) const {
510
46.6k
  if (FID.isInvalid())
511
0
    return FileID();
512
513
46.6k
  int ID = FID.ID;
514
46.6k
  if (ID > 0) {
515
46.6k
    if (unsigned(ID+1) >= local_sloc_entry_size())
516
46
      return FileID();
517
46.6k
  } else 
if (0
ID+1 >= -10
) {
518
0
    return FileID();
519
0
  }
520
521
46.6k
  return FileID::get(ID+1);
522
46.6k
}
523
524
//===----------------------------------------------------------------------===//
525
// Methods to create new FileID's and macro expansions.
526
//===----------------------------------------------------------------------===//
527
528
/// Create a new FileID that represents the specified file
529
/// being \#included from the specified IncludePosition.
530
///
531
/// This translates NULL into standard input.
532
FileID SourceManager::createFileID(const FileEntry *SourceFile,
533
                                   SourceLocation IncludePos,
534
                                   SrcMgr::CharacteristicKind FileCharacter,
535
                                   int LoadedID,
536
55.2k
                                   SourceLocation::UIntTy LoadedOffset) {
537
55.2k
  return createFileID(SourceFile->getLastRef(), IncludePos, FileCharacter,
538
55.2k
                      LoadedID, LoadedOffset);
539
55.2k
}
540
541
FileID SourceManager::createFileID(FileEntryRef SourceFile,
542
                                   SourceLocation IncludePos,
543
                                   SrcMgr::CharacteristicKind FileCharacter,
544
                                   int LoadedID,
545
1.31M
                                   SourceLocation::UIntTy LoadedOffset) {
546
1.31M
  SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile,
547
1.31M
                                                     isSystem(FileCharacter));
548
549
  // If this is a named pipe, immediately load the buffer to ensure subsequent
550
  // calls to ContentCache::getSize() are accurate.
551
1.31M
  if (IR.ContentsEntry->isNamedPipe())
552
669
    (void)IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
553
554
1.31M
  return createFileIDImpl(IR, SourceFile.getName(), IncludePos, FileCharacter,
555
1.31M
                          LoadedID, LoadedOffset);
556
1.31M
}
557
558
/// Create a new FileID that represents the specified memory buffer.
559
///
560
/// This does no caching of the buffer and takes ownership of the
561
/// MemoryBuffer, so only pass a MemoryBuffer to this once.
562
FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
563
                                   SrcMgr::CharacteristicKind FileCharacter,
564
                                   int LoadedID,
565
                                   SourceLocation::UIntTy LoadedOffset,
566
255k
                                   SourceLocation IncludeLoc) {
567
255k
  StringRef Name = Buffer->getBufferIdentifier();
568
255k
  return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name,
569
255k
                          IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
570
255k
}
571
572
/// Create a new FileID that represents the specified memory buffer.
573
///
574
/// This does not take ownership of the MemoryBuffer. The memory buffer must
575
/// outlive the SourceManager.
576
FileID SourceManager::createFileID(const llvm::MemoryBufferRef &Buffer,
577
                                   SrcMgr::CharacteristicKind FileCharacter,
578
                                   int LoadedID,
579
                                   SourceLocation::UIntTy LoadedOffset,
580
33.3k
                                   SourceLocation IncludeLoc) {
581
33.3k
  return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter,
582
33.3k
                      LoadedID, LoadedOffset, IncludeLoc);
583
33.3k
}
584
585
/// Get the FileID for \p SourceFile if it exists. Otherwise, create a
586
/// new FileID for the \p SourceFile.
587
FileID
588
SourceManager::getOrCreateFileID(const FileEntry *SourceFile,
589
55.3k
                                 SrcMgr::CharacteristicKind FileCharacter) {
590
55.3k
  FileID ID = translateFile(SourceFile);
591
55.3k
  return ID.isValid() ? 
ID55.3k
: createFileID(SourceFile, SourceLocation(),
592
73
            FileCharacter);
593
55.3k
}
594
595
/// createFileID - Create a new FileID for the specified ContentCache and
596
/// include position.  This works regardless of whether the ContentCache
597
/// corresponds to a file or some other input source.
598
FileID SourceManager::createFileIDImpl(ContentCache &File, StringRef Filename,
599
                                       SourceLocation IncludePos,
600
                                       SrcMgr::CharacteristicKind FileCharacter,
601
                                       int LoadedID,
602
1.56M
                                       SourceLocation::UIntTy LoadedOffset) {
603
1.56M
  if (LoadedID < 0) {
604
591k
    assert(LoadedID != -1 && "Loading sentinel FileID");
605
0
    unsigned Index = unsigned(-LoadedID) - 2;
606
591k
    assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
607
0
    assert(!SLocEntryLoaded[Index] && "FileID already loaded");
608
0
    LoadedSLocEntryTable[Index] = SLocEntry::get(
609
591k
        LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
610
591k
    SLocEntryLoaded[Index] = true;
611
591k
    return FileID::get(LoadedID);
612
591k
  }
613
976k
  unsigned FileSize = File.getSize();
614
976k
  if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
615
976k
        NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
616
1
    Diag.Report(IncludePos, diag::err_include_too_large);
617
1
    return FileID();
618
1
  }
619
976k
  LocalSLocEntryTable.push_back(
620
976k
      SLocEntry::get(NextLocalOffset,
621
976k
                     FileInfo::get(IncludePos, File, FileCharacter, Filename)));
622
  // We do a +1 here because we want a SourceLocation that means "the end of the
623
  // file", e.g. for the "no newline at the end of the file" diagnostic.
624
976k
  NextLocalOffset += FileSize + 1;
625
626
  // Set LastFileIDLookup to the newly created file.  The next getFileID call is
627
  // almost guaranteed to be from that file.
628
976k
  FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
629
976k
  return LastFileIDLookup = FID;
630
976k
}
631
632
SourceLocation
633
SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
634
                                          SourceLocation ExpansionLoc,
635
36.1M
                                          unsigned TokLength) {
636
36.1M
  ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
637
36.1M
                                                        ExpansionLoc);
638
36.1M
  return createExpansionLocImpl(Info, TokLength);
639
36.1M
}
640
641
SourceLocation SourceManager::createExpansionLoc(
642
    SourceLocation SpellingLoc, SourceLocation ExpansionLocStart,
643
    SourceLocation ExpansionLocEnd, unsigned TokLength,
644
    bool ExpansionIsTokenRange, int LoadedID,
645
78.9M
    SourceLocation::UIntTy LoadedOffset) {
646
78.9M
  ExpansionInfo Info = ExpansionInfo::create(
647
78.9M
      SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
648
78.9M
  return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
649
78.9M
}
650
651
SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
652
                                                  SourceLocation TokenStart,
653
17.1k
                                                  SourceLocation TokenEnd) {
654
17.1k
  assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
655
17.1k
         "token spans multiple files");
656
0
  return createExpansionLocImpl(
657
17.1k
      ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
658
17.1k
      TokenEnd.getOffset() - TokenStart.getOffset());
659
17.1k
}
660
661
SourceLocation
662
SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
663
                                      unsigned TokLength, int LoadedID,
664
115M
                                      SourceLocation::UIntTy LoadedOffset) {
665
115M
  if (LoadedID < 0) {
666
8.38M
    assert(LoadedID != -1 && "Loading sentinel FileID");
667
0
    unsigned Index = unsigned(-LoadedID) - 2;
668
8.38M
    assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
669
0
    assert(!SLocEntryLoaded[Index] && "FileID already loaded");
670
0
    LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
671
8.38M
    SLocEntryLoaded[Index] = true;
672
8.38M
    return SourceLocation::getMacroLoc(LoadedOffset);
673
8.38M
  }
674
106M
  LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
675
106M
  assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
676
106M
         NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
677
106M
         "Ran out of source locations!");
678
  // See createFileID for that +1.
679
0
  NextLocalOffset += TokLength + 1;
680
106M
  return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
681
115M
}
682
683
llvm::Optional<llvm::MemoryBufferRef>
684
1.26k
SourceManager::getMemoryBufferForFileOrNone(const FileEntry *File) {
685
1.26k
  SrcMgr::ContentCache &IR = getOrCreateContentCache(File->getLastRef());
686
1.26k
  return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
687
1.26k
}
688
689
void SourceManager::overrideFileContents(
690
5.70k
    const FileEntry *SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) {
691
5.70k
  SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile->getLastRef());
692
693
5.70k
  IR.setBuffer(std::move(Buffer));
694
5.70k
  IR.BufferOverridden = true;
695
696
5.70k
  getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
697
5.70k
}
698
699
void SourceManager::overrideFileContents(const FileEntry *SourceFile,
700
18
                                         const FileEntry *NewFile) {
701
18
  assert(SourceFile->getSize() == NewFile->getSize() &&
702
18
         "Different sizes, use the FileManager to create a virtual file with "
703
18
         "the correct size");
704
0
  assert(FileInfos.count(SourceFile) == 0 &&
705
18
         "This function should be called at the initialization stage, before "
706
18
         "any parsing occurs.");
707
0
  getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
708
18
}
709
710
Optional<FileEntryRef>
711
1
SourceManager::bypassFileContentsOverride(FileEntryRef File) {
712
1
  assert(isFileOverridden(&File.getFileEntry()));
713
0
  llvm::Optional<FileEntryRef> BypassFile = FileMgr.getBypassFile(File);
714
715
  // If the file can't be found in the FS, give up.
716
1
  if (!BypassFile)
717
0
    return None;
718
719
1
  (void)getOrCreateContentCache(*BypassFile);
720
1
  return BypassFile;
721
1
}
722
723
2
void SourceManager::setFileIsTransient(const FileEntry *File) {
724
2
  getOrCreateContentCache(File->getLastRef()).IsTransient = true;
725
2
}
726
727
Optional<StringRef>
728
430k
SourceManager::getNonBuiltinFilenameForID(FileID FID) const {
729
430k
  if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
730
430k
    if (Entry->getFile().getContentCache().OrigEntry)
731
423k
      return Entry->getFile().getName();
732
6.85k
  return None;
733
430k
}
734
735
112M
StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
736
112M
  auto B = getBufferDataOrNone(FID);
737
112M
  if (Invalid)
738
112M
    *Invalid = !B;
739
112M
  return B ? 
*B112M
:
"<<<<<INVALID SOURCE LOCATION>>>>>"27
;
740
112M
}
741
742
llvm::Optional<StringRef>
743
0
SourceManager::getBufferDataIfLoaded(FileID FID) const {
744
0
  if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
745
0
    return Entry->getFile().getContentCache().getBufferDataIfLoaded();
746
0
  return None;
747
0
}
748
749
112M
llvm::Optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const {
750
112M
  if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
751
112M
    if (auto B = Entry->getFile().getContentCache().getBufferOrNone(
752
112M
            Diag, getFileManager(), SourceLocation()))
753
112M
      return B->getBuffer();
754
27
  return None;
755
112M
}
756
757
//===----------------------------------------------------------------------===//
758
// SourceLocation manipulation methods.
759
//===----------------------------------------------------------------------===//
760
761
/// Return the FileID for a SourceLocation.
762
///
763
/// This is the cache-miss path of getFileID. Not as hot as that function, but
764
/// still very important. It is responsible for finding the entry in the
765
/// SLocEntry tables that contains the specified location.
766
375M
FileID SourceManager::getFileIDSlow(SourceLocation::UIntTy SLocOffset) const {
767
375M
  if (!SLocOffset)
768
1.11M
    return FileID::get(0);
769
770
  // Now it is time to search for the correct file. See where the SLocOffset
771
  // sits in the global view and consult local or loaded buffers for it.
772
374M
  if (SLocOffset < NextLocalOffset)
773
356M
    return getFileIDLocal(SLocOffset);
774
18.5M
  return getFileIDLoaded(SLocOffset);
775
374M
}
776
777
/// Return the FileID for a SourceLocation with a low offset.
778
///
779
/// This function knows that the SourceLocation is in a local buffer, not a
780
/// loaded one.
781
356M
FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
782
356M
  assert(SLocOffset < NextLocalOffset && "Bad function choice");
783
784
  // After the first and second level caches, I see two common sorts of
785
  // behavior: 1) a lot of searched FileID's are "near" the cached file
786
  // location or are "near" the cached expansion location. 2) others are just
787
  // completely random and may be a very long way away.
788
  //
789
  // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
790
  // then we fall back to a less cache efficient, but more scalable, binary
791
  // search to find the location.
792
793
  // See if this is near the file point - worst case we start scanning from the
794
  // most newly created FileID.
795
0
  const SrcMgr::SLocEntry *I;
796
797
356M
  if (LastFileIDLookup.ID < 0 ||
798
356M
      
LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset354M
) {
799
    // Neither loc prunes our search.
800
166M
    I = LocalSLocEntryTable.end();
801
190M
  } else {
802
    // Perhaps it is near the file point.
803
190M
    I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
804
190M
  }
805
806
  // Find the FileID that contains this.  "I" is an iterator that points to a
807
  // FileID whose offset is known to be larger than SLocOffset.
808
356M
  unsigned NumProbes = 0;
809
1.69G
  while (true) {
810
1.69G
    --I;
811
1.69G
    if (I->getOffset() <= SLocOffset) {
812
196M
      FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
813
      // Remember it.  We have good locality across FileID lookups.
814
196M
      LastFileIDLookup = Res;
815
196M
      NumLinearScans += NumProbes+1;
816
196M
      return Res;
817
196M
    }
818
1.49G
    if (++NumProbes == 8)
819
159M
      break;
820
1.49G
  }
821
822
  // Convert "I" back into an index.  We know that it is an entry whose index is
823
  // larger than the offset we are looking for.
824
159M
  unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
825
  // LessIndex - This is the lower bound of the range that we're searching.
826
  // We know that the offset corresponding to the FileID is is less than
827
  // SLocOffset.
828
159M
  unsigned LessIndex = 0;
829
159M
  NumProbes = 0;
830
2.01G
  while (true) {
831
2.01G
    unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
832
2.01G
    SourceLocation::UIntTy MidOffset =
833
2.01G
        getLocalSLocEntry(MiddleIndex).getOffset();
834
835
2.01G
    ++NumProbes;
836
837
    // If the offset of the midpoint is too large, chop the high side of the
838
    // range to the midpoint.
839
2.01G
    if (MidOffset > SLocOffset) {
840
1.15G
      GreaterIndex = MiddleIndex;
841
1.15G
      continue;
842
1.15G
    }
843
844
    // If the middle index contains the value, succeed and return.
845
860M
    if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
846
860M
        SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
847
159M
      FileID Res = FileID::get(MiddleIndex);
848
849
      // Remember it.  We have good locality across FileID lookups.
850
159M
      LastFileIDLookup = Res;
851
159M
      NumBinaryProbes += NumProbes;
852
159M
      return Res;
853
159M
    }
854
855
    // Otherwise, move the low-side up to the middle index.
856
701M
    LessIndex = MiddleIndex;
857
701M
  }
858
159M
}
859
860
/// Return the FileID for a SourceLocation with a high offset.
861
///
862
/// This function knows that the SourceLocation is in a loaded buffer, not a
863
/// local one.
864
18.5M
FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const {
865
  // Sanity checking, otherwise a bug may lead to hanging in release build.
866
18.5M
  if (SLocOffset < CurrentLoadedOffset) {
867
0
    assert(0 && "Invalid SLocOffset or bad function choice");
868
0
    return FileID();
869
0
  }
870
871
  // Essentially the same as the local case, but the loaded array is sorted
872
  // in the other direction.
873
874
  // First do a linear scan from the last lookup position, if possible.
875
18.5M
  unsigned I;
876
18.5M
  int LastID = LastFileIDLookup.ID;
877
18.5M
  if (LastID >= 0 || 
getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset17.2M
)
878
8.87M
    I = 0;
879
9.70M
  else
880
9.70M
    I = (-LastID - 2) + 1;
881
882
18.5M
  unsigned NumProbes;
883
138M
  for (NumProbes = 0; NumProbes < 8; 
++NumProbes, ++I119M
) {
884
    // Make sure the entry is loaded!
885
123M
    const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
886
123M
    if (E.getOffset() <= SLocOffset) {
887
3.88M
      FileID Res = FileID::get(-int(I) - 2);
888
3.88M
      LastFileIDLookup = Res;
889
3.88M
      NumLinearScans += NumProbes + 1;
890
3.88M
      return Res;
891
3.88M
    }
892
123M
  }
893
894
  // Linear scan failed. Do the binary search. Note the reverse sorting of the
895
  // table: GreaterIndex is the one where the offset is greater, which is
896
  // actually a lower index!
897
14.6M
  unsigned GreaterIndex = I;
898
14.6M
  unsigned LessIndex = LoadedSLocEntryTable.size();
899
14.6M
  NumProbes = 0;
900
218M
  while (true) {
901
218M
    ++NumProbes;
902
218M
    unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
903
218M
    const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
904
218M
    if (E.getOffset() == 0)
905
0
      return FileID(); // invalid entry.
906
907
218M
    ++NumProbes;
908
909
218M
    if (E.getOffset() > SLocOffset) {
910
      // Sanity checking, otherwise a bug may lead to hanging in release build.
911
92.9M
      if (GreaterIndex == MiddleIndex) {
912
0
        assert(0 && "binary search missed the entry");
913
0
        return FileID();
914
0
      }
915
92.9M
      GreaterIndex = MiddleIndex;
916
92.9M
      continue;
917
92.9M
    }
918
919
125M
    if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
920
14.6M
      FileID Res = FileID::get(-int(MiddleIndex) - 2);
921
14.6M
      LastFileIDLookup = Res;
922
14.6M
      NumBinaryProbes += NumProbes;
923
14.6M
      return Res;
924
14.6M
    }
925
926
    // Sanity checking, otherwise a bug may lead to hanging in release build.
927
110M
    if (LessIndex == MiddleIndex) {
928
0
      assert(0 && "binary search missed the entry");
929
0
      return FileID();
930
0
    }
931
110M
    LessIndex = MiddleIndex;
932
110M
  }
933
14.6M
}
934
935
SourceLocation SourceManager::
936
8.47M
getExpansionLocSlowCase(SourceLocation Loc) const {
937
14.4M
  do {
938
    // Note: If Loc indicates an offset into a token that came from a macro
939
    // expansion (e.g. the 5th character of the token) we do not want to add
940
    // this offset when going to the expansion location.  The expansion
941
    // location is the macro invocation, which the offset has nothing to do
942
    // with.  This is unlike when we get the spelling loc, because the offset
943
    // directly correspond to the token whose spelling we're inspecting.
944
14.4M
    Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
945
14.4M
  } while (!Loc.isFileID());
946
947
8.47M
  return Loc;
948
8.47M
}
949
950
87.3M
SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
951
87.4M
  do {
952
87.4M
    std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
953
87.4M
    Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
954
87.4M
    Loc = Loc.getLocWithOffset(LocInfo.second);
955
87.4M
  } while (!Loc.isFileID());
956
87.3M
  return Loc;
957
87.3M
}
958
959
25.0k
SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
960
117k
  do {
961
117k
    if (isMacroArgExpansion(Loc))
962
21.6k
      Loc = getImmediateSpellingLoc(Loc);
963
95.5k
    else
964
95.5k
      Loc = getImmediateExpansionRange(Loc).getBegin();
965
117k
  } while (!Loc.isFileID());
966
25.0k
  return Loc;
967
25.0k
}
968
969
970
std::pair<FileID, unsigned>
971
SourceManager::getDecomposedExpansionLocSlowCase(
972
3.55M
                                             const SrcMgr::SLocEntry *E) const {
973
  // If this is an expansion record, walk through all the expansion points.
974
3.55M
  FileID FID;
975
3.55M
  SourceLocation Loc;
976
3.55M
  unsigned Offset;
977
7.77M
  do {
978
7.77M
    Loc = E->getExpansion().getExpansionLocStart();
979
980
7.77M
    FID = getFileID(Loc);
981
7.77M
    E = &getSLocEntry(FID);
982
7.77M
    Offset = Loc.getOffset()-E->getOffset();
983
7.77M
  } while (!Loc.isFileID());
984
985
3.55M
  return std::make_pair(FID, Offset);
986
3.55M
}
987
988
std::pair<FileID, unsigned>
989
SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
990
697k
                                                unsigned Offset) const {
991
  // If this is an expansion record, walk through all the expansion points.
992
697k
  FileID FID;
993
697k
  SourceLocation Loc;
994
791k
  do {
995
791k
    Loc = E->getExpansion().getSpellingLoc();
996
791k
    Loc = Loc.getLocWithOffset(Offset);
997
998
791k
    FID = getFileID(Loc);
999
791k
    E = &getSLocEntry(FID);
1000
791k
    Offset = Loc.getOffset()-E->getOffset();
1001
791k
  } while (!Loc.isFileID());
1002
1003
697k
  return std::make_pair(FID, Offset);
1004
697k
}
1005
1006
/// getImmediateSpellingLoc - Given a SourceLocation object, return the
1007
/// spelling location referenced by the ID.  This is the first level down
1008
/// towards the place where the characters that make up the lexed token can be
1009
/// found.  This should not generally be used by clients.
1010
37.4k
SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
1011
37.4k
  if (Loc.isFileID()) 
return Loc0
;
1012
37.4k
  std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
1013
37.4k
  Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
1014
37.4k
  return Loc.getLocWithOffset(LocInfo.second);
1015
37.4k
}
1016
1017
/// Return the filename of the file containing a SourceLocation.
1018
196k
StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {
1019
196k
  if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
1020
196k
    return F->getName();
1021
155
  return StringRef();
1022
196k
}
1023
1024
/// getImmediateExpansionRange - Loc is required to be an expansion location.
1025
/// Return the start/end of the expansion information.
1026
CharSourceRange
1027
19.3M
SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
1028
19.3M
  assert(Loc.isMacroID() && "Not a macro expansion loc!");
1029
0
  const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
1030
19.3M
  return Expansion.getExpansionLocRange();
1031
19.3M
}
1032
1033
5.36k
SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
1034
5.52k
  while (isMacroArgExpansion(Loc))
1035
160
    Loc = getImmediateSpellingLoc(Loc);
1036
5.36k
  return Loc;
1037
5.36k
}
1038
1039
/// getExpansionRange - Given a SourceLocation object, return the range of
1040
/// tokens covered by the expansion in the ultimate file.
1041
3.97M
CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
1042
3.97M
  if (Loc.isFileID())
1043
8.70k
    return CharSourceRange(SourceRange(Loc, Loc), true);
1044
1045
3.96M
  CharSourceRange Res = getImmediateExpansionRange(Loc);
1046
1047
  // Fully resolve the start and end locations to their ultimate expansion
1048
  // points.
1049
7.77M
  while (!Res.getBegin().isFileID())
1050
3.81M
    Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
1051
6.91M
  while (!Res.getEnd().isFileID()) {
1052
2.94M
    CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
1053
2.94M
    Res.setEnd(EndRange.getEnd());
1054
2.94M
    Res.setTokenRange(EndRange.isTokenRange());
1055
2.94M
  }
1056
3.96M
  return Res;
1057
3.97M
}
1058
1059
bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1060
301k
                                        SourceLocation *StartLoc) const {
1061
301k
  if (!Loc.isMacroID()) 
return false143k
;
1062
1063
158k
  FileID FID = getFileID(Loc);
1064
158k
  const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1065
158k
  if (!Expansion.isMacroArgExpansion()) 
return false121k
;
1066
1067
37.0k
  if (StartLoc)
1068
237
    *StartLoc = Expansion.getExpansionLocStart();
1069
37.0k
  return true;
1070
158k
}
1071
1072
2.46M
bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1073
2.46M
  if (!Loc.isMacroID()) 
return false2.26M
;
1074
1075
199k
  FileID FID = getFileID(Loc);
1076
199k
  const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1077
199k
  return Expansion.isMacroBodyExpansion();
1078
2.46M
}
1079
1080
bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1081
53.6M
                                             SourceLocation *MacroBegin) const {
1082
53.6M
  assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1083
1084
0
  std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1085
53.6M
  if (DecompLoc.second > 0)
1086
29.6M
    return false; // Does not point at the start of expansion range.
1087
1088
23.9M
  bool Invalid = false;
1089
23.9M
  const SrcMgr::ExpansionInfo &ExpInfo =
1090
23.9M
      getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1091
23.9M
  if (Invalid)
1092
0
    return false;
1093
23.9M
  SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1094
1095
23.9M
  if (ExpInfo.isMacroArgExpansion()) {
1096
    // For macro argument expansions, check if the previous FileID is part of
1097
    // the same argument expansion, in which case this Loc is not at the
1098
    // beginning of the expansion.
1099
2.23M
    FileID PrevFID = getPreviousFileID(DecompLoc.first);
1100
2.23M
    if (!PrevFID.isInvalid()) {
1101
2.23M
      const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1102
2.23M
      if (Invalid)
1103
0
        return false;
1104
2.23M
      if (PrevEntry.isExpansion() &&
1105
2.23M
          PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1106
4.84k
        return false;
1107
2.23M
    }
1108
2.23M
  }
1109
1110
23.9M
  if (MacroBegin)
1111
23.9M
    *MacroBegin = ExpLoc;
1112
23.9M
  return true;
1113
23.9M
}
1114
1115
bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1116
49.2M
                                               SourceLocation *MacroEnd) const {
1117
49.2M
  assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1118
1119
0
  FileID FID = getFileID(Loc);
1120
49.2M
  SourceLocation NextLoc = Loc.getLocWithOffset(1);
1121
49.2M
  if (isInFileID(NextLoc, FID))
1122
4.15M
    return false; // Does not point at the end of expansion range.
1123
1124
45.1M
  bool Invalid = false;
1125
45.1M
  const SrcMgr::ExpansionInfo &ExpInfo =
1126
45.1M
      getSLocEntry(FID, &Invalid).getExpansion();
1127
45.1M
  if (Invalid)
1128
0
    return false;
1129
1130
45.1M
  if (ExpInfo.isMacroArgExpansion()) {
1131
    // For macro argument expansions, check if the next FileID is part of the
1132
    // same argument expansion, in which case this Loc is not at the end of the
1133
    // expansion.
1134
46.6k
    FileID NextFID = getNextFileID(FID);
1135
46.6k
    if (!NextFID.isInvalid()) {
1136
46.6k
      const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1137
46.6k
      if (Invalid)
1138
0
        return false;
1139
46.6k
      if (NextEntry.isExpansion() &&
1140
46.6k
          NextEntry.getExpansion().getExpansionLocStart() ==
1141
46.6k
              ExpInfo.getExpansionLocStart())
1142
46.4k
        return false;
1143
46.6k
    }
1144
46.6k
  }
1145
1146
45.0M
  if (MacroEnd)
1147
45.0M
    *MacroEnd = ExpInfo.getExpansionLocEnd();
1148
45.0M
  return true;
1149
45.1M
}
1150
1151
//===----------------------------------------------------------------------===//
1152
// Queries about the code at a SourceLocation.
1153
//===----------------------------------------------------------------------===//
1154
1155
/// getCharacterData - Return a pointer to the start of the specified location
1156
/// in the appropriate MemoryBuffer.
1157
const char *SourceManager::getCharacterData(SourceLocation SL,
1158
52.8M
                                            bool *Invalid) const {
1159
  // Note that this is a hot function in the getSpelling() path, which is
1160
  // heavily used by -E mode.
1161
52.8M
  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1162
1163
  // Note that calling 'getBuffer()' may lazily page in a source file.
1164
52.8M
  bool CharDataInvalid = false;
1165
52.8M
  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1166
52.8M
  if (CharDataInvalid || 
!Entry.isFile()52.8M
) {
1167
4
    if (Invalid)
1168
0
      *Invalid = true;
1169
1170
4
    return "<<<<INVALID BUFFER>>>>";
1171
4
  }
1172
52.8M
  llvm::Optional<llvm::MemoryBufferRef> Buffer =
1173
52.8M
      Entry.getFile().getContentCache().getBufferOrNone(Diag, getFileManager(),
1174
52.8M
                                                        SourceLocation());
1175
52.8M
  if (Invalid)
1176
6.88M
    *Invalid = !Buffer;
1177
52.8M
  return Buffer ? Buffer->getBufferStart() + LocInfo.second
1178
52.8M
                : 
"<<<<INVALID BUFFER>>>>"0
;
1179
52.8M
}
1180
1181
/// getColumnNumber - Return the column # for the specified file position.
1182
/// this is significantly cheaper to compute than the line number.
1183
unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1184
102M
                                        bool *Invalid) const {
1185
102M
  llvm::Optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID);
1186
102M
  if (Invalid)
1187
102M
    *Invalid = !MemBuf;
1188
1189
102M
  if (!MemBuf)
1190
61
    return 1;
1191
1192
  // It is okay to request a position just past the end of the buffer.
1193
102M
  if (FilePos > MemBuf->getBufferSize()) {
1194
1
    if (Invalid)
1195
1
      *Invalid = true;
1196
1
    return 1;
1197
1
  }
1198
1199
102M
  const char *Buf = MemBuf->getBufferStart();
1200
  // See if we just calculated the line number for this FilePos and can use
1201
  // that to lookup the start of the line instead of searching for it.
1202
102M
  if (LastLineNoFileIDQuery == FID && 
LastLineNoContentCache->SourceLineCache102M
&&
1203
102M
      
LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()102M
) {
1204
102M
    const unsigned *SourceLineCache =
1205
102M
        LastLineNoContentCache->SourceLineCache.begin();
1206
102M
    unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1207
102M
    unsigned LineEnd = SourceLineCache[LastLineNoResult];
1208
102M
    if (FilePos >= LineStart && 
FilePos < LineEnd102M
) {
1209
      // LineEnd is the LineStart of the next line.
1210
      // A line ends with separator LF or CR+LF on Windows.
1211
      // FilePos might point to the last separator,
1212
      // but we need a column number at most 1 + the last column.
1213
102M
      if (FilePos + 1 == LineEnd && 
FilePos > LineStart359k
) {
1214
353k
        if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1215
0
          --FilePos;
1216
353k
      }
1217
102M
      return FilePos - LineStart + 1;
1218
102M
    }
1219
102M
  }
1220
1221
200k
  unsigned LineStart = FilePos;
1222
34.7M
  while (LineStart && 
Buf[LineStart-1] != '\n'34.5M
&&
Buf[LineStart-1] != '\r'34.5M
)
1223
34.5M
    --LineStart;
1224
200k
  return FilePos-LineStart+1;
1225
102M
}
1226
1227
// isInvalid - Return the result of calling loc.isInvalid(), and
1228
// if Invalid is not null, set its value to same.
1229
template<typename LocType>
1230
14.7M
static bool isInvalid(LocType Loc, bool *Invalid) {
1231
14.7M
  bool MyInvalid = Loc.isInvalid();
1232
14.7M
  if (Invalid)
1233
311k
    *Invalid = MyInvalid;
1234
14.7M
  return MyInvalid;
1235
14.7M
}
SourceManager.cpp:bool isInvalid<clang::SourceLocation>(clang::SourceLocation, bool*)
Line
Count
Source
1230
12.1M
static bool isInvalid(LocType Loc, bool *Invalid) {
1231
12.1M
  bool MyInvalid = Loc.isInvalid();
1232
12.1M
  if (Invalid)
1233
309k
    *Invalid = MyInvalid;
1234
12.1M
  return MyInvalid;
1235
12.1M
}
SourceManager.cpp:bool isInvalid<clang::PresumedLoc>(clang::PresumedLoc, bool*)
Line
Count
Source
1230
2.54M
static bool isInvalid(LocType Loc, bool *Invalid) {
1231
2.54M
  bool MyInvalid = Loc.isInvalid();
1232
2.54M
  if (Invalid)
1233
1.94k
    *Invalid = MyInvalid;
1234
2.54M
  return MyInvalid;
1235
2.54M
}
1236
1237
unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1238
175k
                                                bool *Invalid) const {
1239
175k
  if (isInvalid(Loc, Invalid)) 
return 0224
;
1240
174k
  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1241
174k
  return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1242
175k
}
1243
1244
unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1245
89.9k
                                                 bool *Invalid) const {
1246
89.9k
  if (isInvalid(Loc, Invalid)) 
return 00
;
1247
89.9k
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1248
89.9k
  return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1249
89.9k
}
1250
1251
unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1252
914
                                                bool *Invalid) const {
1253
914
  PresumedLoc PLoc = getPresumedLoc(Loc);
1254
914
  if (isInvalid(PLoc, Invalid)) 
return 00
;
1255
914
  return PLoc.getColumn();
1256
914
}
1257
1258
// Check if mutli-byte word x has bytes between m and n, included. This may also
1259
// catch bytes equal to n + 1.
1260
// The returned value holds a 0x80 at each byte position that holds a match.
1261
// see http://graphics.stanford.edu/~seander/bithacks.html#HasBetweenInWord
1262
template <class T>
1263
static constexpr inline T likelyhasbetween(T x, unsigned char m,
1264
1.84G
                                           unsigned char n) {
1265
1.84G
  return ((x - ~static_cast<T>(0) / 255 * (n + 1)) & ~x &
1266
1.84G
          ((x & ~static_cast<T>(0) / 255 * 127) +
1267
1.84G
           (~static_cast<T>(0) / 255 * (127 - (m - 1))))) &
1268
1.84G
         ~static_cast<T>(0) / 255 * 128;
1269
1.84G
}
1270
1271
LineOffsetMapping LineOffsetMapping::get(llvm::MemoryBufferRef Buffer,
1272
382k
                                         llvm::BumpPtrAllocator &Alloc) {
1273
1274
  // Find the file offsets of all of the *physical* source lines.  This does
1275
  // not look at trigraphs, escaped newlines, or anything else tricky.
1276
382k
  SmallVector<unsigned, 256> LineOffsets;
1277
1278
  // Line #1 starts at char 0.
1279
382k
  LineOffsets.push_back(0);
1280
1281
382k
  const unsigned char *Buf = (const unsigned char *)Buffer.getBufferStart();
1282
382k
  const unsigned char *End = (const unsigned char *)Buffer.getBufferEnd();
1283
382k
  const std::size_t BufLen = End - Buf;
1284
1285
382k
  unsigned I = 0;
1286
382k
  uint64_t Word;
1287
1288
  // scan sizeof(Word) bytes at a time for new lines.
1289
  // This is much faster than scanning each byte independently.
1290
382k
  if (BufLen > sizeof(Word)) {
1291
1.84G
    do {
1292
1.84G
      Word = llvm::support::endian::read64(Buf + I, llvm::support::little);
1293
      // no new line => jump over sizeof(Word) bytes.
1294
1.84G
      auto Mask = likelyhasbetween(Word, '\n', '\r');
1295
1.84G
      if (!Mask) {
1296
1.58G
        I += sizeof(Word);
1297
1.58G
        continue;
1298
1.58G
      }
1299
1300
      // At that point, Mask contains 0x80 set at each byte that holds a value
1301
      // in [\n, \r + 1 [
1302
1303
      // Scan for the next newline - it's very likely there's one.
1304
257M
      unsigned N =
1305
257M
          llvm::countTrailingZeros(Mask) - 7; // -7 because 0x80 is the marker
1306
257M
      Word >>= N;
1307
257M
      I += N / 8 + 1;
1308
257M
      unsigned char Byte = Word;
1309
257M
      if (Byte == '\n') {
1310
257M
        LineOffsets.push_back(I);
1311
257M
      } else 
if (4.95k
Byte == '\r'4.95k
) {
1312
        // If this is \r\n, skip both characters.
1313
6.41k
        if (Buf[I] == '\n')
1314
6.41k
          ++I;
1315
6.41k
        LineOffsets.push_back(I);
1316
6.41k
      }
1317
1.84G
    } while (I < BufLen - sizeof(Word) - 1);
1318
377k
  }
1319
1320
  // Handle tail using a regular check.
1321
2.34M
  while (I < BufLen) {
1322
1.96M
    if (Buf[I] == '\n') {
1323
404k
      LineOffsets.push_back(I + 1);
1324
1.56M
    } else if (Buf[I] == '\r') {
1325
      // If this is \r\n, skip both characters.
1326
56
      if (I + 1 < BufLen && Buf[I + 1] == '\n')
1327
56
        ++I;
1328
56
      LineOffsets.push_back(I + 1);
1329
56
    }
1330
1.96M
    ++I;
1331
1.96M
  }
1332
1333
382k
  return LineOffsetMapping(LineOffsets, Alloc);
1334
382k
}
1335
1336
LineOffsetMapping::LineOffsetMapping(ArrayRef<unsigned> LineOffsets,
1337
                                     llvm::BumpPtrAllocator &Alloc)
1338
382k
    : Storage(Alloc.Allocate<unsigned>(LineOffsets.size() + 1)) {
1339
382k
  Storage[0] = LineOffsets.size();
1340
382k
  std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1);
1341
382k
}
1342
1343
/// getLineNumber - Given a SourceLocation, return the spelling line number
1344
/// for the position indicated.  This requires building and caching a table of
1345
/// line offsets for the MemoryBuffer, so this is not cheap: use only when
1346
/// about to emit a diagnostic.
1347
unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1348
139M
                                      bool *Invalid) const {
1349
139M
  if (FID.isInvalid()) {
1350
50
    if (Invalid)
1351
0
      *Invalid = true;
1352
50
    return 1;
1353
50
  }
1354
1355
139M
  const ContentCache *Content;
1356
139M
  if (LastLineNoFileIDQuery == FID)
1357
135M
    Content = LastLineNoContentCache;
1358
4.48M
  else {
1359
4.48M
    bool MyInvalid = false;
1360
4.48M
    const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1361
4.48M
    if (MyInvalid || !Entry.isFile()) {
1362
9
      if (Invalid)
1363
0
        *Invalid = true;
1364
9
      return 1;
1365
9
    }
1366
1367
4.48M
    Content = &Entry.getFile().getContentCache();
1368
4.48M
  }
1369
1370
  // If this is the first use of line information for this buffer, compute the
1371
  /// SourceLineCache for it on demand.
1372
139M
  if (!Content->SourceLineCache) {
1373
382k
    llvm::Optional<llvm::MemoryBufferRef> Buffer =
1374
382k
        Content->getBufferOrNone(Diag, getFileManager(), SourceLocation());
1375
382k
    if (Invalid)
1376
363k
      *Invalid = !Buffer;
1377
382k
    if (!Buffer)
1378
0
      return 1;
1379
1380
382k
    Content->SourceLineCache =
1381
382k
        LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
1382
139M
  } else if (Invalid)
1383
101M
    *Invalid = false;
1384
1385
  // Okay, we know we have a line number table.  Do a binary search to find the
1386
  // line number that this character position lands on.
1387
139M
  const unsigned *SourceLineCache = Content->SourceLineCache.begin();
1388
139M
  const unsigned *SourceLineCacheStart = SourceLineCache;
1389
139M
  const unsigned *SourceLineCacheEnd = Content->SourceLineCache.end();
1390
1391
139M
  unsigned QueriedFilePos = FilePos+1;
1392
1393
  // FIXME: I would like to be convinced that this code is worth being as
1394
  // complicated as it is, binary search isn't that slow.
1395
  //
1396
  // If it is worth being optimized, then in my opinion it could be more
1397
  // performant, simpler, and more obviously correct by just "galloping" outward
1398
  // from the queried file position. In fact, this could be incorporated into a
1399
  // generic algorithm such as lower_bound_with_hint.
1400
  //
1401
  // If someone gives me a test case where this matters, and I will do it! - DWD
1402
1403
  // If the previous query was to the same file, we know both the file pos from
1404
  // that query and the line number returned.  This allows us to narrow the
1405
  // search space from the entire file to something near the match.
1406
139M
  if (LastLineNoFileIDQuery == FID) {
1407
135M
    if (QueriedFilePos >= LastLineNoFilePos) {
1408
      // FIXME: Potential overflow?
1409
74.6M
      SourceLineCache = SourceLineCache+LastLineNoResult-1;
1410
1411
      // The query is likely to be nearby the previous one.  Here we check to
1412
      // see if it is within 5, 10 or 20 lines.  It can be far away in cases
1413
      // where big comment blocks and vertical whitespace eat up lines but
1414
      // contribute no tokens.
1415
74.6M
      if (SourceLineCache+5 < SourceLineCacheEnd) {
1416
73.8M
        if (SourceLineCache[5] > QueriedFilePos)
1417
16.1M
          SourceLineCacheEnd = SourceLineCache+5;
1418
57.7M
        else if (SourceLineCache+10 < SourceLineCacheEnd) {
1419
57.7M
          if (SourceLineCache[10] > QueriedFilePos)
1420
960k
            SourceLineCacheEnd = SourceLineCache+10;
1421
56.7M
          else if (SourceLineCache+20 < SourceLineCacheEnd) {
1422
56.7M
            if (SourceLineCache[20] > QueriedFilePos)
1423
816k
              SourceLineCacheEnd = SourceLineCache+20;
1424
56.7M
          }
1425
57.7M
        }
1426
73.8M
      }
1427
74.6M
    } else {
1428
60.8M
      if (LastLineNoResult < Content->SourceLineCache.size())
1429
60.8M
        SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1430
60.8M
    }
1431
135M
  }
1432
1433
139M
  const unsigned *Pos =
1434
139M
      std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1435
139M
  unsigned LineNo = Pos-SourceLineCacheStart;
1436
1437
139M
  LastLineNoFileIDQuery = FID;
1438
139M
  LastLineNoContentCache = Content;
1439
139M
  LastLineNoFilePos = QueriedFilePos;
1440
139M
  LastLineNoResult = LineNo;
1441
139M
  return LineNo;
1442
139M
}
1443
1444
unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1445
174k
                                              bool *Invalid) const {
1446
174k
  if (isInvalid(Loc, Invalid)) 
return 01.46k
;
1447
173k
  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1448
173k
  return getLineNumber(LocInfo.first, LocInfo.second);
1449
174k
}
1450
unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1451
3.19M
                                               bool *Invalid) const {
1452
3.19M
  if (isInvalid(Loc, Invalid)) 
return 00
;
1453
3.19M
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1454
3.19M
  return getLineNumber(LocInfo.first, LocInfo.second);
1455
3.19M
}
1456
unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1457
2.54M
                                              bool *Invalid) const {
1458
2.54M
  PresumedLoc PLoc = getPresumedLoc(Loc);
1459
2.54M
  if (isInvalid(PLoc, Invalid)) 
return 0461
;
1460
2.54M
  return PLoc.getLine();
1461
2.54M
}
1462
1463
/// getFileCharacteristic - return the file characteristic of the specified
1464
/// source location, indicating whether this is a normal file, a system
1465
/// header, or an "implicit extern C" system header.
1466
///
1467
/// This state can be modified with flags on GNU linemarker directives like:
1468
///   # 4 "foo.h" 3
1469
/// which changes all source locations in the current file after that to be
1470
/// considered to be from a system header.
1471
SrcMgr::CharacteristicKind
1472
213M
SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1473
213M
  assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1474
0
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1475
213M
  const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first);
1476
213M
  if (!SEntry)
1477
6
    return C_User;
1478
1479
213M
  const SrcMgr::FileInfo &FI = SEntry->getFile();
1480
1481
  // If there are no #line directives in this file, just return the whole-file
1482
  // state.
1483
213M
  if (!FI.hasLineDirectives())
1484
159M
    return FI.getFileCharacteristic();
1485
1486
53.9M
  assert(LineTable && "Can't have linetable entries without a LineTable!");
1487
  // See if there is a #line directive before the location.
1488
0
  const LineEntry *Entry =
1489
53.9M
    LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1490
1491
  // If this is before the first line marker, use the file characteristic.
1492
53.9M
  if (!Entry)
1493
1.22M
    return FI.getFileCharacteristic();
1494
1495
52.7M
  return Entry->FileKind;
1496
53.9M
}
1497
1498
/// Return the filename or buffer identifier of the buffer the location is in.
1499
/// Note that this name does not respect \#line directives.  Use getPresumedLoc
1500
/// for normal clients.
1501
StringRef SourceManager::getBufferName(SourceLocation Loc,
1502
8.55M
                                       bool *Invalid) const {
1503
8.55M
  if (isInvalid(Loc, Invalid)) 
return "<invalid loc>"1.26k
;
1504
1505
8.55M
  auto B = getBufferOrNone(getFileID(Loc));
1506
8.55M
  if (Invalid)
1507
0
    *Invalid = !B;
1508
8.55M
  return B ? 
B->getBufferIdentifier()8.55M
:
"<invalid buffer>"883
;
1509
8.55M
}
1510
1511
/// getPresumedLoc - This method returns the "presumed" location of a
1512
/// SourceLocation specifies.  A "presumed location" can be modified by \#line
1513
/// or GNU line marker directives.  This provides a view on the data that a
1514
/// user should see in diagnostics, for example.
1515
///
1516
/// Note that a presumed location is always given as the expansion point of an
1517
/// expansion location, not at the spelling location.
1518
PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1519
102M
                                          bool UseLineDirectives) const {
1520
102M
  if (Loc.isInvalid()) 
return PresumedLoc()29.2k
;
1521
1522
  // Presumed locations are always for expansion points.
1523
102M
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1524
1525
102M
  bool Invalid = false;
1526
102M
  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1527
102M
  if (Invalid || 
!Entry.isFile()102M
)
1528
4
    return PresumedLoc();
1529
1530
102M
  const SrcMgr::FileInfo &FI = Entry.getFile();
1531
102M
  const SrcMgr::ContentCache *C = &FI.getContentCache();
1532
1533
  // To get the source name, first consult the FileEntry (if one exists)
1534
  // before the MemBuffer as this will avoid unnecessarily paging in the
1535
  // MemBuffer.
1536
102M
  FileID FID = LocInfo.first;
1537
102M
  StringRef Filename;
1538
102M
  if (C->OrigEntry)
1539
101M
    Filename = C->OrigEntry->getName();
1540
208k
  else if (auto Buffer = C->getBufferOrNone(Diag, getFileManager()))
1541
208k
    Filename = Buffer->getBufferIdentifier();
1542
1543
102M
  unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1544
102M
  if (Invalid)
1545
0
    return PresumedLoc();
1546
102M
  unsigned ColNo  = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1547
102M
  if (Invalid)
1548
0
    return PresumedLoc();
1549
1550
102M
  SourceLocation IncludeLoc = FI.getIncludeLoc();
1551
1552
  // If we have #line directives in this file, update and overwrite the physical
1553
  // location info if appropriate.
1554
102M
  if (UseLineDirectives && 
FI.hasLineDirectives()102M
) {
1555
34.2M
    assert(LineTable && "Can't have linetable entries without a LineTable!");
1556
    // See if there is a #line directive before this.  If so, get it.
1557
34.2M
    if (const LineEntry *Entry =
1558
34.2M
          LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1559
      // If the LineEntry indicates a filename, use it.
1560
34.1M
      if (Entry->FilenameID != -1) {
1561
34.1M
        Filename = LineTable->getFilename(Entry->FilenameID);
1562
        // The contents of files referenced by #line are not in the
1563
        // SourceManager
1564
34.1M
        FID = FileID::get(0);
1565
34.1M
      }
1566
1567
      // Use the line number specified by the LineEntry.  This line number may
1568
      // be multiple lines down from the line entry.  Add the difference in
1569
      // physical line numbers from the query point and the line marker to the
1570
      // total.
1571
34.1M
      unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1572
34.1M
      LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1573
1574
      // Note that column numbers are not molested by line markers.
1575
1576
      // Handle virtual #include manipulation.
1577
34.1M
      if (Entry->IncludeOffset) {
1578
100k
        IncludeLoc = getLocForStartOfFile(LocInfo.first);
1579
100k
        IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1580
100k
      }
1581
34.1M
    }
1582
34.2M
  }
1583
1584
0
  return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1585
102M
}
1586
1587
/// Returns whether the PresumedLoc for a given SourceLocation is
1588
/// in the main file.
1589
///
1590
/// This computes the "presumed" location for a SourceLocation, then checks
1591
/// whether it came from a file other than the main file. This is different
1592
/// from isWrittenInMainFile() because it takes line marker directives into
1593
/// account.
1594
82.0M
bool SourceManager::isInMainFile(SourceLocation Loc) const {
1595
82.0M
  if (Loc.isInvalid()) 
return false297
;
1596
1597
  // Presumed locations are always for expansion points.
1598
82.0M
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1599
1600
82.0M
  const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first);
1601
82.0M
  if (!Entry)
1602
2
    return false;
1603
1604
82.0M
  const SrcMgr::FileInfo &FI = Entry->getFile();
1605
1606
  // Check if there is a line directive for this location.
1607
82.0M
  if (FI.hasLineDirectives())
1608
39.4M
    if (const LineEntry *Entry =
1609
39.4M
            LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1610
39.4M
      if (Entry->IncludeOffset)
1611
350k
        return false;
1612
1613
81.6M
  return FI.getIncludeLoc().isInvalid();
1614
82.0M
}
1615
1616
/// The size of the SLocEntry that \p FID represents.
1617
1.10M
unsigned SourceManager::getFileIDSize(FileID FID) const {
1618
1.10M
  bool Invalid = false;
1619
1.10M
  const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1620
1.10M
  if (Invalid)
1621
0
    return 0;
1622
1623
1.10M
  int ID = FID.ID;
1624
1.10M
  SourceLocation::UIntTy NextOffset;
1625
1.10M
  if ((ID > 0 && 
unsigned(ID+1) == local_sloc_entry_size()84.1k
))
1626
59.6k
    NextOffset = getNextLocalOffset();
1627
1.04M
  else if (ID+1 == -1)
1628
7
    NextOffset = MaxLoadedOffset;
1629
1.04M
  else
1630
1.04M
    NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1631
1632
1.10M
  return NextOffset - Entry.getOffset() - 1;
1633
1.10M
}
1634
1635
//===----------------------------------------------------------------------===//
1636
// Other miscellaneous methods.
1637
//===----------------------------------------------------------------------===//
1638
1639
/// Get the source location for the given file:line:col triplet.
1640
///
1641
/// If the source file is included multiple times, the source location will
1642
/// be based upon an arbitrary inclusion.
1643
SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1644
                                                  unsigned Line,
1645
9.71k
                                                  unsigned Col) const {
1646
9.71k
  assert(SourceFile && "Null source file!");
1647
0
  assert(Line && Col && "Line and column should start from 1!");
1648
1649
0
  FileID FirstFID = translateFile(SourceFile);
1650
9.71k
  return translateLineCol(FirstFID, Line, Col);
1651
9.71k
}
1652
1653
/// Get the FileID for the given file.
1654
///
1655
/// If the source file is included multiple times, the FileID will be the
1656
/// first inclusion.
1657
67.3k
FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1658
67.3k
  assert(SourceFile && "Null source file!");
1659
1660
  // First, check the main file ID, since it is common to look for a
1661
  // location in the main file.
1662
67.3k
  if (MainFileID.isValid()) {
1663
11.9k
    bool Invalid = false;
1664
11.9k
    const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1665
11.9k
    if (Invalid)
1666
0
      return FileID();
1667
1668
11.9k
    if (MainSLoc.isFile()) {
1669
11.9k
      if (MainSLoc.getFile().getContentCache().OrigEntry == SourceFile)
1670
9.70k
        return MainFileID;
1671
11.9k
    }
1672
11.9k
  }
1673
1674
  // The location we're looking for isn't in the main file; look
1675
  // through all of the local source locations.
1676
1.48M
  
for (unsigned I = 0, N = local_sloc_entry_size(); 57.6k
I != N;
++I1.42M
) {
1677
1.48M
    const SLocEntry &SLoc = getLocalSLocEntry(I);
1678
1.48M
    if (SLoc.isFile() &&
1679
1.48M
        
SLoc.getFile().getContentCache().OrigEntry == SourceFile109k
)
1680
56.4k
      return FileID::get(I);
1681
1.48M
  }
1682
1683
  // If that still didn't help, try the modules.
1684
65.2k
  
for (unsigned I = 0, N = loaded_sloc_entry_size(); 1.23k
I != N;
++I63.9k
) {
1685
65.1k
    const SLocEntry &SLoc = getLoadedSLocEntry(I);
1686
65.1k
    if (SLoc.isFile() &&
1687
65.1k
        
SLoc.getFile().getContentCache().OrigEntry == SourceFile4.71k
)
1688
1.11k
      return FileID::get(-int(I) - 2);
1689
65.1k
  }
1690
1691
121
  return FileID();
1692
1.23k
}
1693
1694
/// Get the source location in \arg FID for the given line:col.
1695
/// Returns null location if \arg FID is not a file SLocEntry.
1696
SourceLocation SourceManager::translateLineCol(FileID FID,
1697
                                               unsigned Line,
1698
105k
                                               unsigned Col) const {
1699
  // Lines are used as a one-based index into a zero-based array. This assert
1700
  // checks for possible buffer underruns.
1701
105k
  assert(Line && Col && "Line and column should start from 1!");
1702
1703
105k
  if (FID.isInvalid())
1704
0
    return SourceLocation();
1705
1706
105k
  bool Invalid = false;
1707
105k
  const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1708
105k
  if (Invalid)
1709
0
    return SourceLocation();
1710
1711
105k
  if (!Entry.isFile())
1712
0
    return SourceLocation();
1713
1714
105k
  SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1715
1716
105k
  if (Line == 1 && 
Col == 13.69k
)
1717
3.39k
    return FileLoc;
1718
1719
102k
  const ContentCache *Content = &Entry.getFile().getContentCache();
1720
1721
  // If this is the first use of line information for this buffer, compute the
1722
  // SourceLineCache for it on demand.
1723
102k
  llvm::Optional<llvm::MemoryBufferRef> Buffer =
1724
102k
      Content->getBufferOrNone(Diag, getFileManager());
1725
102k
  if (!Buffer)
1726
0
    return SourceLocation();
1727
102k
  if (!Content->SourceLineCache)
1728
561
    Content->SourceLineCache =
1729
561
        LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
1730
1731
102k
  if (Line > Content->SourceLineCache.size()) {
1732
3
    unsigned Size = Buffer->getBufferSize();
1733
3
    if (Size > 0)
1734
3
      --Size;
1735
3
    return FileLoc.getLocWithOffset(Size);
1736
3
  }
1737
1738
102k
  unsigned FilePos = Content->SourceLineCache[Line - 1];
1739
102k
  const char *Buf = Buffer->getBufferStart() + FilePos;
1740
102k
  unsigned BufLength = Buffer->getBufferSize() - FilePos;
1741
102k
  if (BufLength == 0)
1742
29
    return FileLoc.getLocWithOffset(FilePos);
1743
1744
102k
  unsigned i = 0;
1745
1746
  // Check that the given column is valid.
1747
363k
  while (i < BufLength-1 && 
i < Col-1363k
&&
Buf[i] != '\n'260k
&&
Buf[i] != '\r'260k
)
1748
260k
    ++i;
1749
102k
  return FileLoc.getLocWithOffset(FilePos + i);
1750
102k
}
1751
1752
/// Compute a map of macro argument chunks to their expanded source
1753
/// location. Chunks that are not part of a macro argument will map to an
1754
/// invalid source location. e.g. if a file contains one macro argument at
1755
/// offset 100 with length 10, this is how the map will be formed:
1756
///     0   -> SourceLocation()
1757
///     100 -> Expanded macro arg location
1758
///     110 -> SourceLocation()
1759
void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1760
274
                                          FileID FID) const {
1761
274
  assert(FID.isValid());
1762
1763
  // Initially no macro argument chunk is present.
1764
0
  MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1765
1766
274
  int ID = FID.ID;
1767
1.58k
  while (true) {
1768
1.58k
    ++ID;
1769
    // Stop if there are no more FileIDs to check.
1770
1.58k
    if (ID > 0) {
1771
1.43k
      if (unsigned(ID) >= local_sloc_entry_size())
1772
208
        return;
1773
1.43k
    } else 
if (145
ID == -1145
) {
1774
37
      return;
1775
37
    }
1776
1777
1.33k
    bool Invalid = false;
1778
1.33k
    const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1779
1.33k
    if (Invalid)
1780
0
      return;
1781
1.33k
    if (Entry.isFile()) {
1782
402
      auto& File = Entry.getFile();
1783
402
      if (File.getFileCharacteristic() == C_User_ModuleMap ||
1784
402
          
File.getFileCharacteristic() == C_System_ModuleMap393
)
1785
9
        continue;
1786
1787
393
      SourceLocation IncludeLoc = File.getIncludeLoc();
1788
393
      bool IncludedInFID =
1789
393
          (IncludeLoc.isValid() && 
isInFileID(IncludeLoc, FID)106
) ||
1790
          // Predefined header doesn't have a valid include location in main
1791
          // file, but any files created by it should still be skipped when
1792
          // computing macro args expanded in the main file.
1793
393
          
(315
FID == MainFileID315
&&
Entry.getFile().getName() == "<built-in>"267
);
1794
393
      if (IncludedInFID) {
1795
        // Skip the files/macros of the #include'd file, we only care about
1796
        // macros that lexed macro arguments from our file.
1797
284
        if (Entry.getFile().NumCreatedFIDs)
1798
281
          ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;
1799
284
        continue;
1800
284
      } else 
if (109
IncludeLoc.isValid()109
) {
1801
        // If file was included but not from FID, there is no more files/macros
1802
        // that may be "contained" in this file.
1803
28
        return;
1804
28
      }
1805
81
      continue;
1806
393
    }
1807
1808
934
    const ExpansionInfo &ExpInfo = Entry.getExpansion();
1809
1810
934
    if (ExpInfo.getExpansionLocStart().isFileID()) {
1811
364
      if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1812
1
        return; // No more files/macros that may be "contained" in this file.
1813
364
    }
1814
1815
933
    if (!ExpInfo.isMacroArgExpansion())
1816
430
      continue;
1817
1818
503
    associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1819
503
                                 ExpInfo.getSpellingLoc(),
1820
503
                                 SourceLocation::getMacroLoc(Entry.getOffset()),
1821
503
                                 getFileIDSize(FileID::get(ID)));
1822
503
  }
1823
274
}
1824
1825
void SourceManager::associateFileChunkWithMacroArgExp(
1826
                                         MacroArgsMap &MacroArgsCache,
1827
                                         FileID FID,
1828
                                         SourceLocation SpellLoc,
1829
                                         SourceLocation ExpansionLoc,
1830
546
                                         unsigned ExpansionLength) const {
1831
546
  if (!SpellLoc.isFileID()) {
1832
48
    SourceLocation::UIntTy SpellBeginOffs = SpellLoc.getOffset();
1833
48
    SourceLocation::UIntTy SpellEndOffs = SpellBeginOffs + ExpansionLength;
1834
1835
    // The spelling range for this macro argument expansion can span multiple
1836
    // consecutive FileID entries. Go through each entry contained in the
1837
    // spelling range and if one is itself a macro argument expansion, recurse
1838
    // and associate the file chunk that it represents.
1839
1840
48
    FileID SpellFID; // Current FileID in the spelling range.
1841
48
    unsigned SpellRelativeOffs;
1842
48
    std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1843
48
    while (true) {
1844
48
      const SLocEntry &Entry = getSLocEntry(SpellFID);
1845
48
      SourceLocation::UIntTy SpellFIDBeginOffs = Entry.getOffset();
1846
48
      unsigned SpellFIDSize = getFileIDSize(SpellFID);
1847
48
      SourceLocation::UIntTy SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1848
48
      const ExpansionInfo &Info = Entry.getExpansion();
1849
48
      if (Info.isMacroArgExpansion()) {
1850
43
        unsigned CurrSpellLength;
1851
43
        if (SpellFIDEndOffs < SpellEndOffs)
1852
0
          CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1853
43
        else
1854
43
          CurrSpellLength = ExpansionLength;
1855
43
        associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1856
43
                      Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1857
43
                      ExpansionLoc, CurrSpellLength);
1858
43
      }
1859
1860
48
      if (SpellFIDEndOffs >= SpellEndOffs)
1861
48
        return; // we covered all FileID entries in the spelling range.
1862
1863
      // Move to the next FileID entry in the spelling range.
1864
0
      unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1865
0
      ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1866
0
      ExpansionLength -= advance;
1867
0
      ++SpellFID.ID;
1868
0
      SpellRelativeOffs = 0;
1869
0
    }
1870
48
  }
1871
1872
498
  assert(SpellLoc.isFileID());
1873
1874
0
  unsigned BeginOffs;
1875
498
  if (!isInFileID(SpellLoc, FID, &BeginOffs))
1876
0
    return;
1877
1878
498
  unsigned EndOffs = BeginOffs + ExpansionLength;
1879
1880
  // Add a new chunk for this macro argument. A previous macro argument chunk
1881
  // may have been lexed again, so e.g. if the map is
1882
  //     0   -> SourceLocation()
1883
  //     100 -> Expanded loc #1
1884
  //     110 -> SourceLocation()
1885
  // and we found a new macro FileID that lexed from offset 105 with length 3,
1886
  // the new map will be:
1887
  //     0   -> SourceLocation()
1888
  //     100 -> Expanded loc #1
1889
  //     105 -> Expanded loc #2
1890
  //     108 -> Expanded loc #1
1891
  //     110 -> SourceLocation()
1892
  //
1893
  // Since re-lexed macro chunks will always be the same size or less of
1894
  // previous chunks, we only need to find where the ending of the new macro
1895
  // chunk is mapped to and update the map with new begin/end mappings.
1896
1897
498
  MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1898
498
  --I;
1899
498
  SourceLocation EndOffsMappedLoc = I->second;
1900
498
  MacroArgsCache[BeginOffs] = ExpansionLoc;
1901
498
  MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1902
498
}
1903
1904
/// If \arg Loc points inside a function macro argument, the returned
1905
/// location will be the macro location in which the argument was expanded.
1906
/// If a macro argument is used multiple times, the expanded location will
1907
/// be at the first expansion of the argument.
1908
/// e.g.
1909
///   MY_MACRO(foo);
1910
///             ^
1911
/// Passing a file location pointing at 'foo', will yield a macro location
1912
/// where 'foo' was expanded into.
1913
SourceLocation
1914
9.93k
SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1915
9.93k
  if (Loc.isInvalid() || !Loc.isFileID())
1916
0
    return Loc;
1917
1918
9.93k
  FileID FID;
1919
9.93k
  unsigned Offset;
1920
9.93k
  std::tie(FID, Offset) = getDecomposedLoc(Loc);
1921
9.93k
  if (FID.isInvalid())
1922
0
    return Loc;
1923
1924
9.93k
  std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1925
9.93k
  if (!MacroArgsCache) {
1926
274
    MacroArgsCache = std::make_unique<MacroArgsMap>();
1927
274
    computeMacroArgsCache(*MacroArgsCache, FID);
1928
274
  }
1929
1930
9.93k
  assert(!MacroArgsCache->empty());
1931
0
  MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1932
  // In case every element in MacroArgsCache is greater than Offset we can't
1933
  // decrement the iterator.
1934
9.93k
  if (I == MacroArgsCache->begin())
1935
0
    return Loc;
1936
1937
9.93k
  --I;
1938
1939
9.93k
  SourceLocation::UIntTy MacroArgBeginOffs = I->first;
1940
9.93k
  SourceLocation MacroArgExpandedLoc = I->second;
1941
9.93k
  if (MacroArgExpandedLoc.isValid())
1942
129
    return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1943
1944
9.80k
  return Loc;
1945
9.93k
}
1946
1947
std::pair<FileID, unsigned>
1948
2.96M
SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1949
2.96M
  if (FID.isInvalid())
1950
0
    return std::make_pair(FileID(), 0);
1951
1952
  // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1953
1954
2.96M
  using DecompTy = std::pair<FileID, unsigned>;
1955
2.96M
  auto InsertOp = IncludedLocMap.try_emplace(FID);
1956
2.96M
  DecompTy &DecompLoc = InsertOp.first->second;
1957
2.96M
  if (!InsertOp.second)
1958
257k
    return DecompLoc; // already in map.
1959
1960
2.71M
  SourceLocation UpperLoc;
1961
2.71M
  bool Invalid = false;
1962
2.71M
  const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1963
2.71M
  if (!Invalid) {
1964
2.71M
    if (Entry.isExpansion())
1965
2.40M
      UpperLoc = Entry.getExpansion().getExpansionLocStart();
1966
308k
    else
1967
308k
      UpperLoc = Entry.getFile().getIncludeLoc();
1968
2.71M
  }
1969
1970
2.71M
  if (UpperLoc.isValid())
1971
2.70M
    DecompLoc = getDecomposedLoc(UpperLoc);
1972
1973
2.71M
  return DecompLoc;
1974
2.96M
}
1975
1976
/// Given a decomposed source location, move it up the include/expansion stack
1977
/// to the parent source location.  If this is possible, return the decomposed
1978
/// version of the parent in Loc and return false.  If Loc is the top-level
1979
/// entry, return true and don't modify it.
1980
static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1981
261k
                                   const SourceManager &SM) {
1982
261k
  std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1983
261k
  if (UpperLoc.first.isInvalid())
1984
244k
    return true; // We reached the top.
1985
1986
17.0k
  Loc = UpperLoc;
1987
17.0k
  return false;
1988
261k
}
1989
1990
/// Return the cache entry for comparing the given file IDs
1991
/// for isBeforeInTranslationUnit.
1992
InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1993
139k
                                                            FileID RFID) const {
1994
  // This is a magic number for limiting the cache size.  It was experimentally
1995
  // derived from a small Objective-C project (where the cache filled
1996
  // out to ~250 items).  We can make it larger if necessary.
1997
139k
  enum { MagicCacheSize = 300 };
1998
139k
  IsBeforeInTUCacheKey Key(LFID, RFID);
1999
2000
  // If the cache size isn't too large, do a lookup and if necessary default
2001
  // construct an entry.  We can then return it to the caller for direct
2002
  // use.  When they update the value, the cache will get automatically
2003
  // updated as well.
2004
139k
  if (IBTUCache.size() < MagicCacheSize)
2005
139k
    return IBTUCache[Key];
2006
2007
  // Otherwise, do a lookup that will not construct a new value.
2008
0
  InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2009
0
  if (I != IBTUCache.end())
2010
0
    return I->second;
2011
2012
  // Fall back to the overflow value.
2013
0
  return IBTUCacheOverflow;
2014
0
}
2015
2016
/// Determines the order of 2 source locations in the translation unit.
2017
///
2018
/// \returns true if LHS source location comes before RHS, false otherwise.
2019
bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2020
27.0M
                                              SourceLocation RHS) const {
2021
27.0M
  assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2022
27.0M
  if (LHS == RHS)
2023
158k
    return false;
2024
2025
26.9M
  std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2026
26.9M
  std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2027
2028
  // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2029
  // is a serialized one referring to a file that was removed after we loaded
2030
  // the PCH.
2031
26.9M
  if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2032
0
    return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2033
2034
26.9M
  std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2035
26.9M
  if (InSameTU.first)
2036
26.8M
    return InSameTU.second;
2037
2038
  // If we arrived here, the location is either in a built-ins buffer or
2039
  // associated with global inline asm. PR5662 and PR22576 are examples.
2040
2041
121k
  StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier();
2042
121k
  StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier();
2043
121k
  bool LIsBuiltins = LB == "<built-in>";
2044
121k
  bool RIsBuiltins = RB == "<built-in>";
2045
  // Sort built-in before non-built-in.
2046
121k
  if (LIsBuiltins || 
RIsBuiltins8.07k
) {
2047
121k
    if (LIsBuiltins != RIsBuiltins)
2048
121k
      return LIsBuiltins;
2049
    // Both are in built-in buffers, but from different files. We just claim that
2050
    // lower IDs come first.
2051
0
    return LOffs.first < ROffs.first;
2052
121k
  }
2053
0
  bool LIsAsm = LB == "<inline asm>";
2054
0
  bool RIsAsm = RB == "<inline asm>";
2055
  // Sort assembler after built-ins, but before the rest.
2056
0
  if (LIsAsm || RIsAsm) {
2057
0
    if (LIsAsm != RIsAsm)
2058
0
      return RIsAsm;
2059
0
    assert(LOffs.first == ROffs.first);
2060
0
    return false;
2061
0
  }
2062
0
  bool LIsScratch = LB == "<scratch space>";
2063
0
  bool RIsScratch = RB == "<scratch space>";
2064
  // Sort scratch after inline asm, but before the rest.
2065
0
  if (LIsScratch || RIsScratch) {
2066
0
    if (LIsScratch != RIsScratch)
2067
0
      return LIsScratch;
2068
0
    return LOffs.second < ROffs.second;
2069
0
  }
2070
0
  llvm_unreachable("Unsortable locations found");
2071
0
}
2072
2073
std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2074
    std::pair<FileID, unsigned> &LOffs,
2075
27.0M
    std::pair<FileID, unsigned> &ROffs) const {
2076
  // If the source locations are in the same file, just compare offsets.
2077
27.0M
  if (LOffs.first == ROffs.first)
2078
26.9M
    return std::make_pair(true, LOffs.second < ROffs.second);
2079
2080
  // If we are comparing a source location with multiple locations in the same
2081
  // file, we get a big win by caching the result.
2082
139k
  InBeforeInTUCacheEntry &IsBeforeInTUCache =
2083
139k
    getInBeforeInTUCache(LOffs.first, ROffs.first);
2084
2085
  // If we are comparing a source location with multiple locations in the same
2086
  // file, we get a big win by caching the result.
2087
139k
  if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2088
15.0k
    return std::make_pair(
2089
15.0k
        true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2090
2091
  // Okay, we missed in the cache, start updating the cache for this query.
2092
124k
  IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2093
124k
                          /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2094
2095
  // We need to find the common ancestor. The only way of doing this is to
2096
  // build the complete include chain for one and then walking up the chain
2097
  // of the other looking for a match.
2098
  // We use a map from FileID to Offset to store the chain. Easier than writing
2099
  // a custom set hash info that only depends on the first part of a pair.
2100
124k
  using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
2101
124k
  LocSet LChain;
2102
132k
  do {
2103
132k
    LChain.insert(LOffs);
2104
    // We catch the case where LOffs is in a file included by ROffs and
2105
    // quit early. The other way round unfortunately remains suboptimal.
2106
132k
  } while (LOffs.first != ROffs.first && 
!MoveUpIncludeHierarchy(LOffs, *this)131k
);
2107
124k
  LocSet::iterator I;
2108
133k
  while((I = LChain.find(ROffs.first)) == LChain.end()) {
2109
130k
    if (MoveUpIncludeHierarchy(ROffs, *this))
2110
121k
      break; // Met at topmost file.
2111
130k
  }
2112
124k
  if (I != LChain.end())
2113
3.41k
    LOffs = *I;
2114
2115
  // If we exited because we found a nearest common ancestor, compare the
2116
  // locations within the common file and cache them.
2117
124k
  if (LOffs.first == ROffs.first) {
2118
3.41k
    IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2119
3.41k
    return std::make_pair(
2120
3.41k
        true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2121
3.41k
  }
2122
  // Clear the lookup cache, it depends on a common location.
2123
121k
  IsBeforeInTUCache.clear();
2124
121k
  return std::make_pair(false, false);
2125
124k
}
2126
2127
3
void SourceManager::PrintStats() const {
2128
3
  llvm::errs() << "\n*** Source Manager Stats:\n";
2129
3
  llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2130
3
               << " mem buffers mapped.\n";
2131
3
  llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2132
3
               << llvm::capacity_in_bytes(LocalSLocEntryTable)
2133
3
               << " bytes of capacity), "
2134
3
               << NextLocalOffset << "B of Sloc address space used.\n";
2135
3
  llvm::errs() << LoadedSLocEntryTable.size()
2136
3
               << " loaded SLocEntries allocated, "
2137
3
               << MaxLoadedOffset - CurrentLoadedOffset
2138
3
               << "B of Sloc address space used.\n";
2139
2140
3
  unsigned NumLineNumsComputed = 0;
2141
3
  unsigned NumFileBytesMapped = 0;
2142
9
  for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; 
++I6
){
2143
6
    NumLineNumsComputed += bool(I->second->SourceLineCache);
2144
6
    NumFileBytesMapped  += I->second->getSizeBytesMapped();
2145
6
  }
2146
3
  unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2147
2148
3
  llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2149
3
               << NumLineNumsComputed << " files with line #'s computed, "
2150
3
               << NumMacroArgsComputed << " files with macro args computed.\n";
2151
3
  llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2152
3
               << NumBinaryProbes << " binary.\n";
2153
3
}
2154
2155
0
LLVM_DUMP_METHOD void SourceManager::dump() const {
2156
0
  llvm::raw_ostream &out = llvm::errs();
2157
2158
0
  auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2159
0
                           llvm::Optional<SourceLocation::UIntTy> NextStart) {
2160
0
    out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2161
0
        << " <SourceLocation " << Entry.getOffset() << ":";
2162
0
    if (NextStart)
2163
0
      out << *NextStart << ">\n";
2164
0
    else
2165
0
      out << "???\?>\n";
2166
0
    if (Entry.isFile()) {
2167
0
      auto &FI = Entry.getFile();
2168
0
      if (FI.NumCreatedFIDs)
2169
0
        out << "  covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2170
0
            << ">\n";
2171
0
      if (FI.getIncludeLoc().isValid())
2172
0
        out << "  included from " << FI.getIncludeLoc().getOffset() << "\n";
2173
0
      auto &CC = FI.getContentCache();
2174
0
      out << "  for " << (CC.OrigEntry ? CC.OrigEntry->getName() : "<none>")
2175
0
          << "\n";
2176
0
      if (CC.BufferOverridden)
2177
0
        out << "  contents overridden\n";
2178
0
      if (CC.ContentsEntry != CC.OrigEntry) {
2179
0
        out << "  contents from "
2180
0
            << (CC.ContentsEntry ? CC.ContentsEntry->getName() : "<none>")
2181
0
            << "\n";
2182
0
      }
2183
0
    } else {
2184
0
      auto &EI = Entry.getExpansion();
2185
0
      out << "  spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2186
0
      out << "  macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2187
0
          << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2188
0
          << EI.getExpansionLocEnd().getOffset() << ">\n";
2189
0
    }
2190
0
  };
2191
2192
  // Dump local SLocEntries.
2193
0
  for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2194
0
    DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2195
0
                  ID == NumIDs - 1 ? NextLocalOffset
2196
0
                                   : LocalSLocEntryTable[ID + 1].getOffset());
2197
0
  }
2198
  // Dump loaded SLocEntries.
2199
0
  llvm::Optional<SourceLocation::UIntTy> NextStart;
2200
0
  for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2201
0
    int ID = -(int)Index - 2;
2202
0
    if (SLocEntryLoaded[Index]) {
2203
0
      DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2204
0
      NextStart = LoadedSLocEntryTable[Index].getOffset();
2205
0
    } else {
2206
0
      NextStart = None;
2207
0
    }
2208
0
  }
2209
0
}
2210
2211
12.4k
ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2212
2213
/// Return the amount of memory used by memory buffers, breaking down
2214
/// by heap-backed versus mmap'ed memory.
2215
1
SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2216
1
  size_t malloc_bytes = 0;
2217
1
  size_t mmap_bytes = 0;
2218
2219
2
  for (unsigned i = 0, e = MemBufferInfos.size(); i != e; 
++i1
)
2220
1
    if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2221
1
      switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2222
0
        case llvm::MemoryBuffer::MemoryBuffer_MMap:
2223
0
          mmap_bytes += sized_mapped;
2224
0
          break;
2225
1
        case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2226
1
          malloc_bytes += sized_mapped;
2227
1
          break;
2228
1
      }
2229
2230
1
  return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2231
1
}
2232
2233
1
size_t SourceManager::getDataStructureSizes() const {
2234
1
  size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2235
1
    + llvm::capacity_in_bytes(LocalSLocEntryTable)
2236
1
    + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2237
1
    + llvm::capacity_in_bytes(SLocEntryLoaded)
2238
1
    + llvm::capacity_in_bytes(FileInfos);
2239
2240
1
  if (OverriddenFilesInfo)
2241
0
    size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2242
2243
1
  return size;
2244
1
}
2245
2246
SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2247
41.4k
                                           StringRef Content) {
2248
  // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2249
  // is deleted.
2250
41.4k
  IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2251
41.4k
      new llvm::vfs::InMemoryFileSystem);
2252
41.4k
  InMemoryFileSystem->addFile(
2253
41.4k
      FileName, 0,
2254
41.4k
      llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2255
41.4k
                                       /*RequiresNullTerminator=*/false));
2256
  // This is passed to `SM` as reference, so the pointer has to be referenced
2257
  // in `Environment` so that `FileMgr` can out-live this function scope.
2258
41.4k
  FileMgr =
2259
41.4k
      std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2260
  // This is passed to `SM` as reference, so the pointer has to be referenced
2261
  // by `Environment` due to the same reason above.
2262
41.4k
  Diagnostics = std::make_unique<DiagnosticsEngine>(
2263
41.4k
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2264
41.4k
      new DiagnosticOptions);
2265
41.4k
  SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2266
41.4k
  FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
2267
41.4k
                                      SourceLocation(), clang::SrcMgr::C_User);
2268
41.4k
  assert(ID.isValid());
2269
0
  SourceMgr->setMainFileID(ID);
2270
41.4k
}