SourceManager.cpp 74 KB

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