SourceManager.cpp 82 KB

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