SourceManager.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  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. assert(SLocOffset >= CurrentLoadedOffset && "Bad function choice");
  625. // Essentially the same as the local case, but the loaded array is sorted
  626. // in the other direction.
  627. // First do a linear scan from the last lookup position, if possible.
  628. unsigned I;
  629. int LastID = LastFileIDLookup.ID;
  630. if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
  631. I = 0;
  632. else
  633. I = (-LastID - 2) + 1;
  634. unsigned NumProbes;
  635. for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
  636. // Make sure the entry is loaded!
  637. const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
  638. if (E.getOffset() <= SLocOffset) {
  639. FileID Res = FileID::get(-int(I) - 2);
  640. if (!E.isExpansion())
  641. LastFileIDLookup = Res;
  642. NumLinearScans += NumProbes + 1;
  643. return Res;
  644. }
  645. }
  646. // Linear scan failed. Do the binary search. Note the reverse sorting of the
  647. // table: GreaterIndex is the one where the offset is greater, which is
  648. // actually a lower index!
  649. unsigned GreaterIndex = I;
  650. unsigned LessIndex = LoadedSLocEntryTable.size();
  651. NumProbes = 0;
  652. while (1) {
  653. ++NumProbes;
  654. unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
  655. const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
  656. ++NumProbes;
  657. if (E.getOffset() > SLocOffset) {
  658. GreaterIndex = MiddleIndex;
  659. continue;
  660. }
  661. if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
  662. FileID Res = FileID::get(-int(MiddleIndex) - 2);
  663. if (!E.isExpansion())
  664. LastFileIDLookup = Res;
  665. NumBinaryProbes += NumProbes;
  666. return Res;
  667. }
  668. LessIndex = MiddleIndex;
  669. }
  670. }
  671. SourceLocation SourceManager::
  672. getExpansionLocSlowCase(SourceLocation Loc) const {
  673. do {
  674. // Note: If Loc indicates an offset into a token that came from a macro
  675. // expansion (e.g. the 5th character of the token) we do not want to add
  676. // this offset when going to the expansion location. The expansion
  677. // location is the macro invocation, which the offset has nothing to do
  678. // with. This is unlike when we get the spelling loc, because the offset
  679. // directly correspond to the token whose spelling we're inspecting.
  680. Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
  681. } while (!Loc.isFileID());
  682. return Loc;
  683. }
  684. SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
  685. do {
  686. std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
  687. Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
  688. Loc = Loc.getLocWithOffset(LocInfo.second);
  689. } while (!Loc.isFileID());
  690. return Loc;
  691. }
  692. std::pair<FileID, unsigned>
  693. SourceManager::getDecomposedExpansionLocSlowCase(
  694. const SrcMgr::SLocEntry *E) const {
  695. // If this is an expansion record, walk through all the expansion points.
  696. FileID FID;
  697. SourceLocation Loc;
  698. unsigned Offset;
  699. do {
  700. Loc = E->getExpansion().getExpansionLocStart();
  701. FID = getFileID(Loc);
  702. E = &getSLocEntry(FID);
  703. Offset = Loc.getOffset()-E->getOffset();
  704. } while (!Loc.isFileID());
  705. return std::make_pair(FID, Offset);
  706. }
  707. std::pair<FileID, unsigned>
  708. SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
  709. unsigned Offset) const {
  710. // If this is an expansion record, walk through all the expansion points.
  711. FileID FID;
  712. SourceLocation Loc;
  713. do {
  714. Loc = E->getExpansion().getSpellingLoc();
  715. Loc = Loc.getLocWithOffset(Offset);
  716. FID = getFileID(Loc);
  717. E = &getSLocEntry(FID);
  718. Offset = Loc.getOffset()-E->getOffset();
  719. } while (!Loc.isFileID());
  720. return std::make_pair(FID, Offset);
  721. }
  722. /// getImmediateSpellingLoc - Given a SourceLocation object, return the
  723. /// spelling location referenced by the ID. This is the first level down
  724. /// towards the place where the characters that make up the lexed token can be
  725. /// found. This should not generally be used by clients.
  726. SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
  727. if (Loc.isFileID()) return Loc;
  728. std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
  729. Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
  730. return Loc.getLocWithOffset(LocInfo.second);
  731. }
  732. /// getImmediateExpansionRange - Loc is required to be an expansion location.
  733. /// Return the start/end of the expansion information.
  734. std::pair<SourceLocation,SourceLocation>
  735. SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
  736. assert(Loc.isMacroID() && "Not a macro expansion loc!");
  737. const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
  738. return Expansion.getExpansionLocRange();
  739. }
  740. /// getExpansionRange - Given a SourceLocation object, return the range of
  741. /// tokens covered by the expansion in the ultimate file.
  742. std::pair<SourceLocation,SourceLocation>
  743. SourceManager::getExpansionRange(SourceLocation Loc) const {
  744. if (Loc.isFileID()) return std::make_pair(Loc, Loc);
  745. std::pair<SourceLocation,SourceLocation> Res =
  746. getImmediateExpansionRange(Loc);
  747. // Fully resolve the start and end locations to their ultimate expansion
  748. // points.
  749. while (!Res.first.isFileID())
  750. Res.first = getImmediateExpansionRange(Res.first).first;
  751. while (!Res.second.isFileID())
  752. Res.second = getImmediateExpansionRange(Res.second).second;
  753. return Res;
  754. }
  755. bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const {
  756. if (!Loc.isMacroID()) return false;
  757. FileID FID = getFileID(Loc);
  758. const SrcMgr::SLocEntry *E = &getSLocEntry(FID);
  759. const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
  760. return Expansion.isMacroArgExpansion();
  761. }
  762. //===----------------------------------------------------------------------===//
  763. // Queries about the code at a SourceLocation.
  764. //===----------------------------------------------------------------------===//
  765. /// getCharacterData - Return a pointer to the start of the specified location
  766. /// in the appropriate MemoryBuffer.
  767. const char *SourceManager::getCharacterData(SourceLocation SL,
  768. bool *Invalid) const {
  769. // Note that this is a hot function in the getSpelling() path, which is
  770. // heavily used by -E mode.
  771. std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
  772. // Note that calling 'getBuffer()' may lazily page in a source file.
  773. bool CharDataInvalid = false;
  774. const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
  775. if (CharDataInvalid || !Entry.isFile()) {
  776. if (Invalid)
  777. *Invalid = true;
  778. return "<<<<INVALID BUFFER>>>>";
  779. }
  780. const llvm::MemoryBuffer *Buffer
  781. = Entry.getFile().getContentCache()
  782. ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
  783. if (Invalid)
  784. *Invalid = CharDataInvalid;
  785. return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
  786. }
  787. /// getColumnNumber - Return the column # for the specified file position.
  788. /// this is significantly cheaper to compute than the line number.
  789. unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
  790. bool *Invalid) const {
  791. bool MyInvalid = false;
  792. const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
  793. if (Invalid)
  794. *Invalid = MyInvalid;
  795. if (MyInvalid)
  796. return 1;
  797. unsigned LineStart = FilePos;
  798. while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
  799. --LineStart;
  800. return FilePos-LineStart+1;
  801. }
  802. // isInvalid - Return the result of calling loc.isInvalid(), and
  803. // if Invalid is not null, set its value to same.
  804. static bool isInvalid(SourceLocation Loc, bool *Invalid) {
  805. bool MyInvalid = Loc.isInvalid();
  806. if (Invalid)
  807. *Invalid = MyInvalid;
  808. return MyInvalid;
  809. }
  810. unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
  811. bool *Invalid) const {
  812. if (isInvalid(Loc, Invalid)) return 0;
  813. std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
  814. return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
  815. }
  816. unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
  817. bool *Invalid) const {
  818. if (isInvalid(Loc, Invalid)) return 0;
  819. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  820. return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
  821. }
  822. unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
  823. bool *Invalid) const {
  824. if (isInvalid(Loc, Invalid)) return 0;
  825. return getPresumedLoc(Loc).getColumn();
  826. }
  827. static LLVM_ATTRIBUTE_NOINLINE void
  828. ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
  829. llvm::BumpPtrAllocator &Alloc,
  830. const SourceManager &SM, bool &Invalid);
  831. static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
  832. llvm::BumpPtrAllocator &Alloc,
  833. const SourceManager &SM, bool &Invalid) {
  834. // Note that calling 'getBuffer()' may lazily page in the file.
  835. const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
  836. &Invalid);
  837. if (Invalid)
  838. return;
  839. // Find the file offsets of all of the *physical* source lines. This does
  840. // not look at trigraphs, escaped newlines, or anything else tricky.
  841. SmallVector<unsigned, 256> LineOffsets;
  842. // Line #1 starts at char 0.
  843. LineOffsets.push_back(0);
  844. const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
  845. const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
  846. unsigned Offs = 0;
  847. while (1) {
  848. // Skip over the contents of the line.
  849. // TODO: Vectorize this? This is very performance sensitive for programs
  850. // with lots of diagnostics and in -E mode.
  851. const unsigned char *NextBuf = (const unsigned char *)Buf;
  852. while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
  853. ++NextBuf;
  854. Offs += NextBuf-Buf;
  855. Buf = NextBuf;
  856. if (Buf[0] == '\n' || Buf[0] == '\r') {
  857. // If this is \n\r or \r\n, skip both characters.
  858. if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
  859. ++Offs, ++Buf;
  860. ++Offs, ++Buf;
  861. LineOffsets.push_back(Offs);
  862. } else {
  863. // Otherwise, this is a null. If end of file, exit.
  864. if (Buf == End) break;
  865. // Otherwise, skip the null.
  866. ++Offs, ++Buf;
  867. }
  868. }
  869. // Copy the offsets into the FileInfo structure.
  870. FI->NumLines = LineOffsets.size();
  871. FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
  872. std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
  873. }
  874. /// getLineNumber - Given a SourceLocation, return the spelling line number
  875. /// for the position indicated. This requires building and caching a table of
  876. /// line offsets for the MemoryBuffer, so this is not cheap: use only when
  877. /// about to emit a diagnostic.
  878. unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
  879. bool *Invalid) const {
  880. if (FID.isInvalid()) {
  881. if (Invalid)
  882. *Invalid = true;
  883. return 1;
  884. }
  885. ContentCache *Content;
  886. if (LastLineNoFileIDQuery == FID)
  887. Content = LastLineNoContentCache;
  888. else {
  889. bool MyInvalid = false;
  890. const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
  891. if (MyInvalid || !Entry.isFile()) {
  892. if (Invalid)
  893. *Invalid = true;
  894. return 1;
  895. }
  896. Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
  897. }
  898. // If this is the first use of line information for this buffer, compute the
  899. /// SourceLineCache for it on demand.
  900. if (Content->SourceLineCache == 0) {
  901. bool MyInvalid = false;
  902. ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
  903. if (Invalid)
  904. *Invalid = MyInvalid;
  905. if (MyInvalid)
  906. return 1;
  907. } else if (Invalid)
  908. *Invalid = false;
  909. // Okay, we know we have a line number table. Do a binary search to find the
  910. // line number that this character position lands on.
  911. unsigned *SourceLineCache = Content->SourceLineCache;
  912. unsigned *SourceLineCacheStart = SourceLineCache;
  913. unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
  914. unsigned QueriedFilePos = FilePos+1;
  915. // FIXME: I would like to be convinced that this code is worth being as
  916. // complicated as it is, binary search isn't that slow.
  917. //
  918. // If it is worth being optimized, then in my opinion it could be more
  919. // performant, simpler, and more obviously correct by just "galloping" outward
  920. // from the queried file position. In fact, this could be incorporated into a
  921. // generic algorithm such as lower_bound_with_hint.
  922. //
  923. // If someone gives me a test case where this matters, and I will do it! - DWD
  924. // If the previous query was to the same file, we know both the file pos from
  925. // that query and the line number returned. This allows us to narrow the
  926. // search space from the entire file to something near the match.
  927. if (LastLineNoFileIDQuery == FID) {
  928. if (QueriedFilePos >= LastLineNoFilePos) {
  929. // FIXME: Potential overflow?
  930. SourceLineCache = SourceLineCache+LastLineNoResult-1;
  931. // The query is likely to be nearby the previous one. Here we check to
  932. // see if it is within 5, 10 or 20 lines. It can be far away in cases
  933. // where big comment blocks and vertical whitespace eat up lines but
  934. // contribute no tokens.
  935. if (SourceLineCache+5 < SourceLineCacheEnd) {
  936. if (SourceLineCache[5] > QueriedFilePos)
  937. SourceLineCacheEnd = SourceLineCache+5;
  938. else if (SourceLineCache+10 < SourceLineCacheEnd) {
  939. if (SourceLineCache[10] > QueriedFilePos)
  940. SourceLineCacheEnd = SourceLineCache+10;
  941. else if (SourceLineCache+20 < SourceLineCacheEnd) {
  942. if (SourceLineCache[20] > QueriedFilePos)
  943. SourceLineCacheEnd = SourceLineCache+20;
  944. }
  945. }
  946. }
  947. } else {
  948. if (LastLineNoResult < Content->NumLines)
  949. SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
  950. }
  951. }
  952. // If the spread is large, do a "radix" test as our initial guess, based on
  953. // the assumption that lines average to approximately the same length.
  954. // NOTE: This is currently disabled, as it does not appear to be profitable in
  955. // initial measurements.
  956. if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
  957. unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
  958. // Take a stab at guessing where it is.
  959. unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
  960. // Check for -10 and +10 lines.
  961. unsigned LowerBound = std::max(int(ApproxPos-10), 0);
  962. unsigned UpperBound = std::min(ApproxPos+10, FileLen);
  963. // If the computed lower bound is less than the query location, move it in.
  964. if (SourceLineCache < SourceLineCacheStart+LowerBound &&
  965. SourceLineCacheStart[LowerBound] < QueriedFilePos)
  966. SourceLineCache = SourceLineCacheStart+LowerBound;
  967. // If the computed upper bound is greater than the query location, move it.
  968. if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
  969. SourceLineCacheStart[UpperBound] >= QueriedFilePos)
  970. SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
  971. }
  972. unsigned *Pos
  973. = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
  974. unsigned LineNo = Pos-SourceLineCacheStart;
  975. LastLineNoFileIDQuery = FID;
  976. LastLineNoContentCache = Content;
  977. LastLineNoFilePos = QueriedFilePos;
  978. LastLineNoResult = LineNo;
  979. return LineNo;
  980. }
  981. unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
  982. bool *Invalid) const {
  983. if (isInvalid(Loc, Invalid)) return 0;
  984. std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
  985. return getLineNumber(LocInfo.first, LocInfo.second);
  986. }
  987. unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
  988. bool *Invalid) const {
  989. if (isInvalid(Loc, Invalid)) return 0;
  990. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  991. return getLineNumber(LocInfo.first, LocInfo.second);
  992. }
  993. unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
  994. bool *Invalid) const {
  995. if (isInvalid(Loc, Invalid)) return 0;
  996. return getPresumedLoc(Loc).getLine();
  997. }
  998. /// getFileCharacteristic - return the file characteristic of the specified
  999. /// source location, indicating whether this is a normal file, a system
  1000. /// header, or an "implicit extern C" system header.
  1001. ///
  1002. /// This state can be modified with flags on GNU linemarker directives like:
  1003. /// # 4 "foo.h" 3
  1004. /// which changes all source locations in the current file after that to be
  1005. /// considered to be from a system header.
  1006. SrcMgr::CharacteristicKind
  1007. SourceManager::getFileCharacteristic(SourceLocation Loc) const {
  1008. assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
  1009. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  1010. bool Invalid = false;
  1011. const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
  1012. if (Invalid || !SEntry.isFile())
  1013. return C_User;
  1014. const SrcMgr::FileInfo &FI = SEntry.getFile();
  1015. // If there are no #line directives in this file, just return the whole-file
  1016. // state.
  1017. if (!FI.hasLineDirectives())
  1018. return FI.getFileCharacteristic();
  1019. assert(LineTable && "Can't have linetable entries without a LineTable!");
  1020. // See if there is a #line directive before the location.
  1021. const LineEntry *Entry =
  1022. LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
  1023. // If this is before the first line marker, use the file characteristic.
  1024. if (!Entry)
  1025. return FI.getFileCharacteristic();
  1026. return Entry->FileKind;
  1027. }
  1028. /// Return the filename or buffer identifier of the buffer the location is in.
  1029. /// Note that this name does not respect #line directives. Use getPresumedLoc
  1030. /// for normal clients.
  1031. const char *SourceManager::getBufferName(SourceLocation Loc,
  1032. bool *Invalid) const {
  1033. if (isInvalid(Loc, Invalid)) return "<invalid loc>";
  1034. return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
  1035. }
  1036. /// getPresumedLoc - This method returns the "presumed" location of a
  1037. /// SourceLocation specifies. A "presumed location" can be modified by #line
  1038. /// or GNU line marker directives. This provides a view on the data that a
  1039. /// user should see in diagnostics, for example.
  1040. ///
  1041. /// Note that a presumed location is always given as the expansion point of an
  1042. /// expansion location, not at the spelling location.
  1043. PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
  1044. if (Loc.isInvalid()) return PresumedLoc();
  1045. // Presumed locations are always for expansion points.
  1046. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
  1047. bool Invalid = false;
  1048. const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
  1049. if (Invalid || !Entry.isFile())
  1050. return PresumedLoc();
  1051. const SrcMgr::FileInfo &FI = Entry.getFile();
  1052. const SrcMgr::ContentCache *C = FI.getContentCache();
  1053. // To get the source name, first consult the FileEntry (if one exists)
  1054. // before the MemBuffer as this will avoid unnecessarily paging in the
  1055. // MemBuffer.
  1056. const char *Filename;
  1057. if (C->OrigEntry)
  1058. Filename = C->OrigEntry->getName();
  1059. else
  1060. Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
  1061. unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
  1062. if (Invalid)
  1063. return PresumedLoc();
  1064. unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
  1065. if (Invalid)
  1066. return PresumedLoc();
  1067. SourceLocation IncludeLoc = FI.getIncludeLoc();
  1068. // If we have #line directives in this file, update and overwrite the physical
  1069. // location info if appropriate.
  1070. if (FI.hasLineDirectives()) {
  1071. assert(LineTable && "Can't have linetable entries without a LineTable!");
  1072. // See if there is a #line directive before this. If so, get it.
  1073. if (const LineEntry *Entry =
  1074. LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
  1075. // If the LineEntry indicates a filename, use it.
  1076. if (Entry->FilenameID != -1)
  1077. Filename = LineTable->getFilename(Entry->FilenameID);
  1078. // Use the line number specified by the LineEntry. This line number may
  1079. // be multiple lines down from the line entry. Add the difference in
  1080. // physical line numbers from the query point and the line marker to the
  1081. // total.
  1082. unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
  1083. LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
  1084. // Note that column numbers are not molested by line markers.
  1085. // Handle virtual #include manipulation.
  1086. if (Entry->IncludeOffset) {
  1087. IncludeLoc = getLocForStartOfFile(LocInfo.first);
  1088. IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
  1089. }
  1090. }
  1091. }
  1092. return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
  1093. }
  1094. /// \brief The size of the SLocEnty that \arg FID represents.
  1095. unsigned SourceManager::getFileIDSize(FileID FID) const {
  1096. bool Invalid = false;
  1097. const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
  1098. if (Invalid)
  1099. return 0;
  1100. int ID = FID.ID;
  1101. unsigned NextOffset;
  1102. if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
  1103. NextOffset = getNextLocalOffset();
  1104. else if (ID+1 == -1)
  1105. NextOffset = MaxLoadedOffset;
  1106. else
  1107. NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
  1108. return NextOffset - Entry.getOffset() - 1;
  1109. }
  1110. //===----------------------------------------------------------------------===//
  1111. // Other miscellaneous methods.
  1112. //===----------------------------------------------------------------------===//
  1113. /// \brief Retrieve the inode for the given file entry, if possible.
  1114. ///
  1115. /// This routine involves a system call, and therefore should only be used
  1116. /// in non-performance-critical code.
  1117. static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
  1118. if (!File)
  1119. return llvm::Optional<ino_t>();
  1120. struct stat StatBuf;
  1121. if (::stat(File->getName(), &StatBuf))
  1122. return llvm::Optional<ino_t>();
  1123. return StatBuf.st_ino;
  1124. }
  1125. /// \brief Get the source location for the given file:line:col triplet.
  1126. ///
  1127. /// If the source file is included multiple times, the source location will
  1128. /// be based upon an arbitrary inclusion.
  1129. SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
  1130. unsigned Line,
  1131. unsigned Col) const {
  1132. assert(SourceFile && "Null source file!");
  1133. assert(Line && Col && "Line and column should start from 1!");
  1134. // Find the first file ID that corresponds to the given file.
  1135. FileID FirstFID;
  1136. // First, check the main file ID, since it is common to look for a
  1137. // location in the main file.
  1138. llvm::Optional<ino_t> SourceFileInode;
  1139. llvm::Optional<StringRef> SourceFileName;
  1140. if (!MainFileID.isInvalid()) {
  1141. bool Invalid = false;
  1142. const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
  1143. if (Invalid)
  1144. return SourceLocation();
  1145. if (MainSLoc.isFile()) {
  1146. const ContentCache *MainContentCache
  1147. = MainSLoc.getFile().getContentCache();
  1148. if (!MainContentCache) {
  1149. // Can't do anything
  1150. } else if (MainContentCache->OrigEntry == SourceFile) {
  1151. FirstFID = MainFileID;
  1152. } else {
  1153. // Fall back: check whether we have the same base name and inode
  1154. // as the main file.
  1155. const FileEntry *MainFile = MainContentCache->OrigEntry;
  1156. SourceFileName = llvm::sys::path::filename(SourceFile->getName());
  1157. if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
  1158. SourceFileInode = getActualFileInode(SourceFile);
  1159. if (SourceFileInode) {
  1160. if (llvm::Optional<ino_t> MainFileInode
  1161. = getActualFileInode(MainFile)) {
  1162. if (*SourceFileInode == *MainFileInode) {
  1163. FirstFID = MainFileID;
  1164. SourceFile = MainFile;
  1165. }
  1166. }
  1167. }
  1168. }
  1169. }
  1170. }
  1171. }
  1172. if (FirstFID.isInvalid()) {
  1173. // The location we're looking for isn't in the main file; look
  1174. // through all of the local source locations.
  1175. for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
  1176. bool Invalid = false;
  1177. const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
  1178. if (Invalid)
  1179. return SourceLocation();
  1180. if (SLoc.isFile() &&
  1181. SLoc.getFile().getContentCache() &&
  1182. SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
  1183. FirstFID = FileID::get(I);
  1184. break;
  1185. }
  1186. }
  1187. // If that still didn't help, try the modules.
  1188. if (FirstFID.isInvalid()) {
  1189. for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
  1190. const SLocEntry &SLoc = getLoadedSLocEntry(I);
  1191. if (SLoc.isFile() &&
  1192. SLoc.getFile().getContentCache() &&
  1193. SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
  1194. FirstFID = FileID::get(-int(I) - 2);
  1195. break;
  1196. }
  1197. }
  1198. }
  1199. }
  1200. // If we haven't found what we want yet, try again, but this time stat()
  1201. // each of the files in case the files have changed since we originally
  1202. // parsed the file.
  1203. if (FirstFID.isInvalid() &&
  1204. (SourceFileName ||
  1205. (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
  1206. (SourceFileInode ||
  1207. (SourceFileInode = getActualFileInode(SourceFile)))) {
  1208. bool Invalid = false;
  1209. for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
  1210. FileID IFileID;
  1211. IFileID.ID = I;
  1212. const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
  1213. if (Invalid)
  1214. return SourceLocation();
  1215. if (SLoc.isFile()) {
  1216. const ContentCache *FileContentCache
  1217. = SLoc.getFile().getContentCache();
  1218. const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
  1219. if (Entry &&
  1220. *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
  1221. if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
  1222. if (*SourceFileInode == *EntryInode) {
  1223. FirstFID = FileID::get(I);
  1224. SourceFile = Entry;
  1225. break;
  1226. }
  1227. }
  1228. }
  1229. }
  1230. }
  1231. }
  1232. return translateLineCol(FirstFID, Line, Col);
  1233. }
  1234. /// \brief Get the source location in \arg FID for the given line:col.
  1235. /// Returns null location if \arg FID is not a file SLocEntry.
  1236. SourceLocation SourceManager::translateLineCol(FileID FID,
  1237. unsigned Line,
  1238. unsigned Col) const {
  1239. if (FID.isInvalid())
  1240. return SourceLocation();
  1241. bool Invalid = false;
  1242. const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
  1243. if (Invalid)
  1244. return SourceLocation();
  1245. if (!Entry.isFile())
  1246. return SourceLocation();
  1247. SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
  1248. if (Line == 1 && Col == 1)
  1249. return FileLoc;
  1250. ContentCache *Content
  1251. = const_cast<ContentCache *>(Entry.getFile().getContentCache());
  1252. if (!Content)
  1253. return SourceLocation();
  1254. // If this is the first use of line information for this buffer, compute the
  1255. // SourceLineCache for it on demand.
  1256. if (Content->SourceLineCache == 0) {
  1257. bool MyInvalid = false;
  1258. ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
  1259. if (MyInvalid)
  1260. return SourceLocation();
  1261. }
  1262. if (Line > Content->NumLines) {
  1263. unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
  1264. if (Size > 0)
  1265. --Size;
  1266. return FileLoc.getLocWithOffset(Size);
  1267. }
  1268. unsigned FilePos = Content->SourceLineCache[Line - 1];
  1269. const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
  1270. unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
  1271. if (BufLength == 0)
  1272. return FileLoc.getLocWithOffset(FilePos);
  1273. unsigned i = 0;
  1274. // Check that the given column is valid.
  1275. while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
  1276. ++i;
  1277. if (i < Col-1)
  1278. return FileLoc.getLocWithOffset(FilePos + i);
  1279. return FileLoc.getLocWithOffset(FilePos + Col - 1);
  1280. }
  1281. /// \brief Compute a map of macro argument chunks to their expanded source
  1282. /// location. Chunks that are not part of a macro argument will map to an
  1283. /// invalid source location. e.g. if a file contains one macro argument at
  1284. /// offset 100 with length 10, this is how the map will be formed:
  1285. /// 0 -> SourceLocation()
  1286. /// 100 -> Expanded macro arg location
  1287. /// 110 -> SourceLocation()
  1288. void SourceManager::computeMacroArgsCache(MacroArgsMap *&CachePtr,
  1289. FileID FID) const {
  1290. assert(!FID.isInvalid());
  1291. assert(!CachePtr);
  1292. CachePtr = new MacroArgsMap();
  1293. MacroArgsMap &MacroArgsCache = *CachePtr;
  1294. // Initially no macro argument chunk is present.
  1295. MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
  1296. int ID = FID.ID;
  1297. while (1) {
  1298. ++ID;
  1299. // Stop if there are no more FileIDs to check.
  1300. if (ID > 0) {
  1301. if (unsigned(ID) >= local_sloc_entry_size())
  1302. return;
  1303. } else if (ID == -1) {
  1304. return;
  1305. }
  1306. const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID);
  1307. if (Entry.isFile()) {
  1308. SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
  1309. if (IncludeLoc.isInvalid())
  1310. continue;
  1311. if (!isInFileID(IncludeLoc, FID))
  1312. return; // No more files/macros that may be "contained" in this file.
  1313. // Skip the files/macros of the #include'd file, we only care about macros
  1314. // that lexed macro arguments from our file.
  1315. if (Entry.getFile().NumCreatedFIDs)
  1316. ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
  1317. continue;
  1318. }
  1319. if (!Entry.getExpansion().isMacroArgExpansion())
  1320. continue;
  1321. SourceLocation SpellLoc =
  1322. getSpellingLoc(Entry.getExpansion().getSpellingLoc());
  1323. unsigned BeginOffs;
  1324. if (!isInFileID(SpellLoc, FID, &BeginOffs))
  1325. return; // No more files/macros that may be "contained" in this file.
  1326. unsigned EndOffs = BeginOffs + getFileIDSize(FileID::get(ID));
  1327. // Add a new chunk for this macro argument. A previous macro argument chunk
  1328. // may have been lexed again, so e.g. if the map is
  1329. // 0 -> SourceLocation()
  1330. // 100 -> Expanded loc #1
  1331. // 110 -> SourceLocation()
  1332. // and we found a new macro FileID that lexed from offet 105 with length 3,
  1333. // the new map will be:
  1334. // 0 -> SourceLocation()
  1335. // 100 -> Expanded loc #1
  1336. // 105 -> Expanded loc #2
  1337. // 108 -> Expanded loc #1
  1338. // 110 -> SourceLocation()
  1339. //
  1340. // Since re-lexed macro chunks will always be the same size or less of
  1341. // previous chunks, we only need to find where the ending of the new macro
  1342. // chunk is mapped to and update the map with new begin/end mappings.
  1343. MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
  1344. --I;
  1345. SourceLocation EndOffsMappedLoc = I->second;
  1346. MacroArgsCache[BeginOffs] = SourceLocation::getMacroLoc(Entry.getOffset());
  1347. MacroArgsCache[EndOffs] = EndOffsMappedLoc;
  1348. }
  1349. }
  1350. /// \brief If \arg Loc points inside a function macro argument, the returned
  1351. /// location will be the macro location in which the argument was expanded.
  1352. /// If a macro argument is used multiple times, the expanded location will
  1353. /// be at the first expansion of the argument.
  1354. /// e.g.
  1355. /// MY_MACRO(foo);
  1356. /// ^
  1357. /// Passing a file location pointing at 'foo', will yield a macro location
  1358. /// where 'foo' was expanded into.
  1359. SourceLocation
  1360. SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
  1361. if (Loc.isInvalid() || !Loc.isFileID())
  1362. return Loc;
  1363. FileID FID;
  1364. unsigned Offset;
  1365. llvm::tie(FID, Offset) = getDecomposedLoc(Loc);
  1366. if (FID.isInvalid())
  1367. return Loc;
  1368. MacroArgsMap *&MacroArgsCache = MacroArgsCacheMap[FID];
  1369. if (!MacroArgsCache)
  1370. computeMacroArgsCache(MacroArgsCache, FID);
  1371. assert(!MacroArgsCache->empty());
  1372. MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
  1373. --I;
  1374. unsigned MacroArgBeginOffs = I->first;
  1375. SourceLocation MacroArgExpandedLoc = I->second;
  1376. if (MacroArgExpandedLoc.isValid())
  1377. return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
  1378. return Loc;
  1379. }
  1380. /// Given a decomposed source location, move it up the include/expansion stack
  1381. /// to the parent source location. If this is possible, return the decomposed
  1382. /// version of the parent in Loc and return false. If Loc is the top-level
  1383. /// entry, return true and don't modify it.
  1384. static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
  1385. const SourceManager &SM) {
  1386. SourceLocation UpperLoc;
  1387. const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
  1388. if (Entry.isExpansion())
  1389. UpperLoc = Entry.getExpansion().getExpansionLocEnd();
  1390. else
  1391. UpperLoc = Entry.getFile().getIncludeLoc();
  1392. if (UpperLoc.isInvalid())
  1393. return true; // We reached the top.
  1394. Loc = SM.getDecomposedLoc(UpperLoc);
  1395. return false;
  1396. }
  1397. /// \brief Determines the order of 2 source locations in the translation unit.
  1398. ///
  1399. /// \returns true if LHS source location comes before RHS, false otherwise.
  1400. bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
  1401. SourceLocation RHS) const {
  1402. assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
  1403. if (LHS == RHS)
  1404. return false;
  1405. std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
  1406. std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
  1407. // If the source locations are in the same file, just compare offsets.
  1408. if (LOffs.first == ROffs.first)
  1409. return LOffs.second < ROffs.second;
  1410. // If we are comparing a source location with multiple locations in the same
  1411. // file, we get a big win by caching the result.
  1412. if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
  1413. return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
  1414. // Okay, we missed in the cache, start updating the cache for this query.
  1415. IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
  1416. /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
  1417. // We need to find the common ancestor. The only way of doing this is to
  1418. // build the complete include chain for one and then walking up the chain
  1419. // of the other looking for a match.
  1420. // We use a map from FileID to Offset to store the chain. Easier than writing
  1421. // a custom set hash info that only depends on the first part of a pair.
  1422. typedef llvm::DenseMap<FileID, unsigned> LocSet;
  1423. LocSet LChain;
  1424. do {
  1425. LChain.insert(LOffs);
  1426. // We catch the case where LOffs is in a file included by ROffs and
  1427. // quit early. The other way round unfortunately remains suboptimal.
  1428. } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
  1429. LocSet::iterator I;
  1430. while((I = LChain.find(ROffs.first)) == LChain.end()) {
  1431. if (MoveUpIncludeHierarchy(ROffs, *this))
  1432. break; // Met at topmost file.
  1433. }
  1434. if (I != LChain.end())
  1435. LOffs = *I;
  1436. // If we exited because we found a nearest common ancestor, compare the
  1437. // locations within the common file and cache them.
  1438. if (LOffs.first == ROffs.first) {
  1439. IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
  1440. return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
  1441. }
  1442. // This can happen if a location is in a built-ins buffer.
  1443. // But see PR5662.
  1444. // Clear the lookup cache, it depends on a common location.
  1445. IsBeforeInTUCache.clear();
  1446. bool LIsBuiltins = strcmp("<built-in>",
  1447. getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
  1448. bool RIsBuiltins = strcmp("<built-in>",
  1449. getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
  1450. // built-in is before non-built-in
  1451. if (LIsBuiltins != RIsBuiltins)
  1452. return LIsBuiltins;
  1453. assert(LIsBuiltins && RIsBuiltins &&
  1454. "Non-built-in locations must be rooted in the main file");
  1455. // Both are in built-in buffers, but from different files. We just claim that
  1456. // lower IDs come first.
  1457. return LOffs.first < ROffs.first;
  1458. }
  1459. /// PrintStats - Print statistics to stderr.
  1460. ///
  1461. void SourceManager::PrintStats() const {
  1462. llvm::errs() << "\n*** Source Manager Stats:\n";
  1463. llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
  1464. << " mem buffers mapped.\n";
  1465. llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
  1466. << llvm::capacity_in_bytes(LocalSLocEntryTable)
  1467. << " bytes of capacity), "
  1468. << NextLocalOffset << "B of Sloc address space used.\n";
  1469. llvm::errs() << LoadedSLocEntryTable.size()
  1470. << " loaded SLocEntries allocated, "
  1471. << MaxLoadedOffset - CurrentLoadedOffset
  1472. << "B of Sloc address space used.\n";
  1473. unsigned NumLineNumsComputed = 0;
  1474. unsigned NumFileBytesMapped = 0;
  1475. for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
  1476. NumLineNumsComputed += I->second->SourceLineCache != 0;
  1477. NumFileBytesMapped += I->second->getSizeBytesMapped();
  1478. }
  1479. unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
  1480. llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
  1481. << NumLineNumsComputed << " files with line #'s computed, "
  1482. << NumMacroArgsComputed << " files with macro args computed.\n";
  1483. llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
  1484. << NumBinaryProbes << " binary.\n";
  1485. }
  1486. ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
  1487. /// Return the amount of memory used by memory buffers, breaking down
  1488. /// by heap-backed versus mmap'ed memory.
  1489. SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
  1490. size_t malloc_bytes = 0;
  1491. size_t mmap_bytes = 0;
  1492. for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
  1493. if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
  1494. switch (MemBufferInfos[i]->getMemoryBufferKind()) {
  1495. case llvm::MemoryBuffer::MemoryBuffer_MMap:
  1496. mmap_bytes += sized_mapped;
  1497. break;
  1498. case llvm::MemoryBuffer::MemoryBuffer_Malloc:
  1499. malloc_bytes += sized_mapped;
  1500. break;
  1501. }
  1502. return MemoryBufferSizes(malloc_bytes, mmap_bytes);
  1503. }
  1504. size_t SourceManager::getDataStructureSizes() const {
  1505. return llvm::capacity_in_bytes(MemBufferInfos)
  1506. + llvm::capacity_in_bytes(LocalSLocEntryTable)
  1507. + llvm::capacity_in_bytes(LoadedSLocEntryTable)
  1508. + llvm::capacity_in_bytes(SLocEntryLoaded)
  1509. + llvm::capacity_in_bytes(FileInfos)
  1510. + llvm::capacity_in_bytes(OverriddenFiles);
  1511. }