SourceManager.cpp 80 KB

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