SourceManager.cpp 71 KB

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