SourceManager.cpp 71 KB

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