SourceManager.cpp 82 KB

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