SourceManager.cpp 81 KB

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