SourceManager.cpp 82 KB

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