SourceManager.cpp 79 KB

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