SourceManager.cpp 80 KB

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