SourceManager.cpp 67 KB

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