SourceManager.cpp 71 KB

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