SourceManager.h 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- SourceManager.h - Track and cache source files -----------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. /// \file
  15. /// Defines the SourceManager interface.
  16. ///
  17. /// There are three different types of locations in a %file: a spelling
  18. /// location, an expansion location, and a presumed location.
  19. ///
  20. /// Given an example of:
  21. /// \code
  22. /// #define min(x, y) x < y ? x : y
  23. /// \endcode
  24. ///
  25. /// and then later on a use of min:
  26. /// \code
  27. /// #line 17
  28. /// return min(a, b);
  29. /// \endcode
  30. ///
  31. /// The expansion location is the line in the source code where the macro
  32. /// was expanded (the return statement), the spelling location is the
  33. /// location in the source where the macro was originally defined,
  34. /// and the presumed location is where the line directive states that
  35. /// the line is 17, or any other line.
  36. //
  37. //===----------------------------------------------------------------------===//
  38. #ifndef LLVM_CLANG_BASIC_SOURCEMANAGER_H
  39. #define LLVM_CLANG_BASIC_SOURCEMANAGER_H
  40. #include "clang/Basic/Diagnostic.h"
  41. #include "clang/Basic/FileEntry.h"
  42. #include "clang/Basic/SourceLocation.h"
  43. #include "llvm/ADT/ArrayRef.h"
  44. #include "llvm/ADT/BitVector.h"
  45. #include "llvm/ADT/DenseMap.h"
  46. #include "llvm/ADT/DenseSet.h"
  47. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  48. #include "llvm/ADT/PointerIntPair.h"
  49. #include "llvm/ADT/SmallVector.h"
  50. #include "llvm/ADT/StringRef.h"
  51. #include "llvm/Support/Allocator.h"
  52. #include "llvm/Support/Compiler.h"
  53. #include "llvm/Support/MemoryBuffer.h"
  54. #include <cassert>
  55. #include <cstddef>
  56. #include <map>
  57. #include <memory>
  58. #include <string>
  59. #include <utility>
  60. #include <vector>
  61. namespace clang {
  62. class ASTReader;
  63. class ASTWriter;
  64. class FileManager;
  65. class LineTableInfo;
  66. class SourceManager;
  67. /// Public enums and private classes that are part of the
  68. /// SourceManager implementation.
  69. namespace SrcMgr {
  70. /// Indicates whether a file or directory holds normal user code,
  71. /// system code, or system code which is implicitly 'extern "C"' in C++ mode.
  72. ///
  73. /// Entire directories can be tagged with this (this is maintained by
  74. /// DirectoryLookup and friends) as can specific FileInfos when a \#pragma
  75. /// system_header is seen or in various other cases.
  76. ///
  77. enum CharacteristicKind {
  78. C_User,
  79. C_System,
  80. C_ExternCSystem,
  81. C_User_ModuleMap,
  82. C_System_ModuleMap
  83. };
  84. /// Determine whether a file / directory characteristic is for system code.
  85. inline bool isSystem(CharacteristicKind CK) {
  86. return CK != C_User && CK != C_User_ModuleMap;
  87. }
  88. /// Determine whether a file characteristic is for a module map.
  89. inline bool isModuleMap(CharacteristicKind CK) {
  90. return CK == C_User_ModuleMap || CK == C_System_ModuleMap;
  91. }
  92. /// Mapping of line offsets into a source file. This does not own the storage
  93. /// for the line numbers.
  94. class LineOffsetMapping {
  95. public:
  96. explicit operator bool() const { return Storage; }
  97. unsigned size() const {
  98. assert(Storage);
  99. return Storage[0];
  100. }
  101. ArrayRef<unsigned> getLines() const {
  102. assert(Storage);
  103. return ArrayRef<unsigned>(Storage + 1, Storage + 1 + size());
  104. }
  105. const unsigned *begin() const { return getLines().begin(); }
  106. const unsigned *end() const { return getLines().end(); }
  107. const unsigned &operator[](int I) const { return getLines()[I]; }
  108. static LineOffsetMapping get(llvm::MemoryBufferRef Buffer,
  109. llvm::BumpPtrAllocator &Alloc);
  110. LineOffsetMapping() = default;
  111. LineOffsetMapping(ArrayRef<unsigned> LineOffsets,
  112. llvm::BumpPtrAllocator &Alloc);
  113. private:
  114. /// First element is the size, followed by elements at off-by-one indexes.
  115. unsigned *Storage = nullptr;
  116. };
  117. /// One instance of this struct is kept for every file loaded or used.
  118. ///
  119. /// This object owns the MemoryBuffer object.
  120. class alignas(8) ContentCache {
  121. /// The actual buffer containing the characters from the input
  122. /// file.
  123. mutable std::unique_ptr<llvm::MemoryBuffer> Buffer;
  124. public:
  125. /// Reference to the file entry representing this ContentCache.
  126. ///
  127. /// This reference does not own the FileEntry object.
  128. ///
  129. /// It is possible for this to be NULL if the ContentCache encapsulates
  130. /// an imaginary text buffer.
  131. ///
  132. /// FIXME: Turn this into a FileEntryRef and remove Filename.
  133. const FileEntry *OrigEntry;
  134. /// References the file which the contents were actually loaded from.
  135. ///
  136. /// Can be different from 'Entry' if we overridden the contents of one file
  137. /// with the contents of another file.
  138. const FileEntry *ContentsEntry;
  139. /// The filename that is used to access OrigEntry.
  140. ///
  141. /// FIXME: Remove this once OrigEntry is a FileEntryRef with a stable name.
  142. StringRef Filename;
  143. /// A bump pointer allocated array of offsets for each source line.
  144. ///
  145. /// This is lazily computed. The lines are owned by the SourceManager
  146. /// BumpPointerAllocator object.
  147. mutable LineOffsetMapping SourceLineCache;
  148. /// Indicates whether the buffer itself was provided to override
  149. /// the actual file contents.
  150. ///
  151. /// When true, the original entry may be a virtual file that does not
  152. /// exist.
  153. unsigned BufferOverridden : 1;
  154. /// True if this content cache was initially created for a source file
  155. /// considered to be volatile (likely to change between stat and open).
  156. unsigned IsFileVolatile : 1;
  157. /// True if this file may be transient, that is, if it might not
  158. /// exist at some later point in time when this content entry is used,
  159. /// after serialization and deserialization.
  160. unsigned IsTransient : 1;
  161. mutable unsigned IsBufferInvalid : 1;
  162. ContentCache(const FileEntry *Ent = nullptr) : ContentCache(Ent, Ent) {}
  163. ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
  164. : OrigEntry(Ent), ContentsEntry(contentEnt), BufferOverridden(false),
  165. IsFileVolatile(false), IsTransient(false), IsBufferInvalid(false) {}
  166. /// The copy ctor does not allow copies where source object has either
  167. /// a non-NULL Buffer or SourceLineCache. Ownership of allocated memory
  168. /// is not transferred, so this is a logical error.
  169. ContentCache(const ContentCache &RHS)
  170. : BufferOverridden(false), IsFileVolatile(false), IsTransient(false),
  171. IsBufferInvalid(false) {
  172. OrigEntry = RHS.OrigEntry;
  173. ContentsEntry = RHS.ContentsEntry;
  174. assert(!RHS.Buffer && !RHS.SourceLineCache &&
  175. "Passed ContentCache object cannot own a buffer.");
  176. }
  177. ContentCache &operator=(const ContentCache &RHS) = delete;
  178. /// Returns the memory buffer for the associated content.
  179. ///
  180. /// \param Diag Object through which diagnostics will be emitted if the
  181. /// buffer cannot be retrieved.
  182. ///
  183. /// \param Loc If specified, is the location that invalid file diagnostics
  184. /// will be emitted at.
  185. llvm::Optional<llvm::MemoryBufferRef>
  186. getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
  187. SourceLocation Loc = SourceLocation()) const;
  188. /// Returns the size of the content encapsulated by this
  189. /// ContentCache.
  190. ///
  191. /// This can be the size of the source file or the size of an
  192. /// arbitrary scratch buffer. If the ContentCache encapsulates a source
  193. /// file this size is retrieved from the file's FileEntry.
  194. unsigned getSize() const;
  195. /// Returns the number of bytes actually mapped for this
  196. /// ContentCache.
  197. ///
  198. /// This can be 0 if the MemBuffer was not actually expanded.
  199. unsigned getSizeBytesMapped() const;
  200. /// Returns the kind of memory used to back the memory buffer for
  201. /// this content cache. This is used for performance analysis.
  202. llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const;
  203. /// Return the buffer, only if it has been loaded.
  204. llvm::Optional<llvm::MemoryBufferRef> getBufferIfLoaded() const {
  205. if (Buffer)
  206. return Buffer->getMemBufferRef();
  207. return None;
  208. }
  209. /// Return a StringRef to the source buffer data, only if it has already
  210. /// been loaded.
  211. llvm::Optional<StringRef> getBufferDataIfLoaded() const {
  212. if (Buffer)
  213. return Buffer->getBuffer();
  214. return None;
  215. }
  216. /// Set the buffer.
  217. void setBuffer(std::unique_ptr<llvm::MemoryBuffer> B) {
  218. IsBufferInvalid = false;
  219. Buffer = std::move(B);
  220. }
  221. /// Set the buffer to one that's not owned (or to nullptr).
  222. ///
  223. /// \pre Buffer cannot already be set.
  224. void setUnownedBuffer(llvm::Optional<llvm::MemoryBufferRef> B) {
  225. assert(!Buffer && "Expected to be called right after construction");
  226. if (B)
  227. setBuffer(llvm::MemoryBuffer::getMemBuffer(*B));
  228. }
  229. // If BufStr has an invalid BOM, returns the BOM name; otherwise, returns
  230. // nullptr
  231. static const char *getInvalidBOM(StringRef BufStr);
  232. };
  233. // Assert that the \c ContentCache objects will always be 8-byte aligned so
  234. // that we can pack 3 bits of integer into pointers to such objects.
  235. static_assert(alignof(ContentCache) >= 8,
  236. "ContentCache must be 8-byte aligned.");
  237. /// Information about a FileID, basically just the logical file
  238. /// that it represents and include stack information.
  239. ///
  240. /// Each FileInfo has include stack information, indicating where it came
  241. /// from. This information encodes the \#include chain that a token was
  242. /// expanded from. The main include file has an invalid IncludeLoc.
  243. ///
  244. /// FileInfo should not grow larger than ExpansionInfo. Doing so will
  245. /// cause memory to bloat in compilations with many unloaded macro
  246. /// expansions, since the two data structurs are stored in a union in
  247. /// SLocEntry. Extra fields should instead go in "ContentCache *", which
  248. /// stores file contents and other bits on the side.
  249. ///
  250. class FileInfo {
  251. friend class clang::SourceManager;
  252. friend class clang::ASTWriter;
  253. friend class clang::ASTReader;
  254. /// The location of the \#include that brought in this file.
  255. ///
  256. /// This is an invalid SLOC for the main file (top of the \#include chain).
  257. SourceLocation IncludeLoc;
  258. /// Number of FileIDs (files and macros) that were created during
  259. /// preprocessing of this \#include, including this SLocEntry.
  260. ///
  261. /// Zero means the preprocessor didn't provide such info for this SLocEntry.
  262. unsigned NumCreatedFIDs : 31;
  263. /// Whether this FileInfo has any \#line directives.
  264. unsigned HasLineDirectives : 1;
  265. /// The content cache and the characteristic of the file.
  266. llvm::PointerIntPair<const ContentCache *, 3, CharacteristicKind>
  267. ContentAndKind;
  268. public:
  269. /// Return a FileInfo object.
  270. static FileInfo get(SourceLocation IL, ContentCache &Con,
  271. CharacteristicKind FileCharacter, StringRef Filename) {
  272. FileInfo X;
  273. X.IncludeLoc = IL;
  274. X.NumCreatedFIDs = 0;
  275. X.HasLineDirectives = false;
  276. X.ContentAndKind.setPointer(&Con);
  277. X.ContentAndKind.setInt(FileCharacter);
  278. Con.Filename = Filename;
  279. return X;
  280. }
  281. SourceLocation getIncludeLoc() const {
  282. return IncludeLoc;
  283. }
  284. const ContentCache &getContentCache() const {
  285. return *ContentAndKind.getPointer();
  286. }
  287. /// Return whether this is a system header or not.
  288. CharacteristicKind getFileCharacteristic() const {
  289. return ContentAndKind.getInt();
  290. }
  291. /// Return true if this FileID has \#line directives in it.
  292. bool hasLineDirectives() const { return HasLineDirectives; }
  293. /// Set the flag that indicates that this FileID has
  294. /// line table entries associated with it.
  295. void setHasLineDirectives() { HasLineDirectives = true; }
  296. /// Returns the name of the file that was used when the file was loaded from
  297. /// the underlying file system.
  298. StringRef getName() const { return getContentCache().Filename; }
  299. };
  300. /// Each ExpansionInfo encodes the expansion location - where
  301. /// the token was ultimately expanded, and the SpellingLoc - where the actual
  302. /// character data for the token came from.
  303. class ExpansionInfo {
  304. // Really these are all SourceLocations.
  305. /// Where the spelling for the token can be found.
  306. SourceLocation SpellingLoc;
  307. /// In a macro expansion, ExpansionLocStart and ExpansionLocEnd
  308. /// indicate the start and end of the expansion. In object-like macros,
  309. /// they will be the same. In a function-like macro expansion, the start
  310. /// will be the identifier and the end will be the ')'. Finally, in
  311. /// macro-argument instantiations, the end will be 'SourceLocation()', an
  312. /// invalid location.
  313. SourceLocation ExpansionLocStart, ExpansionLocEnd;
  314. /// Whether the expansion range is a token range.
  315. bool ExpansionIsTokenRange;
  316. public:
  317. SourceLocation getSpellingLoc() const {
  318. return SpellingLoc.isInvalid() ? getExpansionLocStart() : SpellingLoc;
  319. }
  320. SourceLocation getExpansionLocStart() const {
  321. return ExpansionLocStart;
  322. }
  323. SourceLocation getExpansionLocEnd() const {
  324. return ExpansionLocEnd.isInvalid() ? getExpansionLocStart()
  325. : ExpansionLocEnd;
  326. }
  327. bool isExpansionTokenRange() const { return ExpansionIsTokenRange; }
  328. CharSourceRange getExpansionLocRange() const {
  329. return CharSourceRange(
  330. SourceRange(getExpansionLocStart(), getExpansionLocEnd()),
  331. isExpansionTokenRange());
  332. }
  333. bool isMacroArgExpansion() const {
  334. // Note that this needs to return false for default constructed objects.
  335. return getExpansionLocStart().isValid() && ExpansionLocEnd.isInvalid();
  336. }
  337. bool isMacroBodyExpansion() const {
  338. return getExpansionLocStart().isValid() && ExpansionLocEnd.isValid();
  339. }
  340. bool isFunctionMacroExpansion() const {
  341. return getExpansionLocStart().isValid() &&
  342. getExpansionLocStart() != getExpansionLocEnd();
  343. }
  344. /// Return a ExpansionInfo for an expansion.
  345. ///
  346. /// Start and End specify the expansion range (where the macro is
  347. /// expanded), and SpellingLoc specifies the spelling location (where
  348. /// the characters from the token come from). All three can refer to
  349. /// normal File SLocs or expansion locations.
  350. static ExpansionInfo create(SourceLocation SpellingLoc, SourceLocation Start,
  351. SourceLocation End,
  352. bool ExpansionIsTokenRange = true) {
  353. ExpansionInfo X;
  354. X.SpellingLoc = SpellingLoc;
  355. X.ExpansionLocStart = Start;
  356. X.ExpansionLocEnd = End;
  357. X.ExpansionIsTokenRange = ExpansionIsTokenRange;
  358. return X;
  359. }
  360. /// Return a special ExpansionInfo for the expansion of
  361. /// a macro argument into a function-like macro's body.
  362. ///
  363. /// ExpansionLoc specifies the expansion location (where the macro is
  364. /// expanded). This doesn't need to be a range because a macro is always
  365. /// expanded at a macro parameter reference, and macro parameters are
  366. /// always exactly one token. SpellingLoc specifies the spelling location
  367. /// (where the characters from the token come from). ExpansionLoc and
  368. /// SpellingLoc can both refer to normal File SLocs or expansion locations.
  369. ///
  370. /// Given the code:
  371. /// \code
  372. /// #define F(x) f(x)
  373. /// F(42);
  374. /// \endcode
  375. ///
  376. /// When expanding '\c F(42)', the '\c x' would call this with an
  377. /// SpellingLoc pointing at '\c 42' and an ExpansionLoc pointing at its
  378. /// location in the definition of '\c F'.
  379. static ExpansionInfo createForMacroArg(SourceLocation SpellingLoc,
  380. SourceLocation ExpansionLoc) {
  381. // We store an intentionally invalid source location for the end of the
  382. // expansion range to mark that this is a macro argument location rather
  383. // than a normal one.
  384. return create(SpellingLoc, ExpansionLoc, SourceLocation());
  385. }
  386. /// Return a special ExpansionInfo representing a token that ends
  387. /// prematurely. This is used to model a '>>' token that has been split
  388. /// into '>' tokens and similar cases. Unlike for the other forms of
  389. /// expansion, the expansion range in this case is a character range, not
  390. /// a token range.
  391. static ExpansionInfo createForTokenSplit(SourceLocation SpellingLoc,
  392. SourceLocation Start,
  393. SourceLocation End) {
  394. return create(SpellingLoc, Start, End, false);
  395. }
  396. };
  397. // Assert that the \c FileInfo objects are no bigger than \c ExpansionInfo
  398. // objects. This controls the size of \c SLocEntry, of which we have one for
  399. // each macro expansion. The number of (unloaded) macro expansions can be
  400. // very large. Any other fields needed in FileInfo should go in ContentCache.
  401. static_assert(sizeof(FileInfo) <= sizeof(ExpansionInfo),
  402. "FileInfo must be no larger than ExpansionInfo.");
  403. /// This is a discriminated union of FileInfo and ExpansionInfo.
  404. ///
  405. /// SourceManager keeps an array of these objects, and they are uniquely
  406. /// identified by the FileID datatype.
  407. class SLocEntry {
  408. static constexpr int OffsetBits = 8 * sizeof(SourceLocation::UIntTy) - 1;
  409. SourceLocation::UIntTy Offset : OffsetBits;
  410. SourceLocation::UIntTy IsExpansion : 1;
  411. union {
  412. FileInfo File;
  413. ExpansionInfo Expansion;
  414. };
  415. public:
  416. SLocEntry() : Offset(), IsExpansion(), File() {}
  417. SourceLocation::UIntTy getOffset() const { return Offset; }
  418. bool isExpansion() const { return IsExpansion; }
  419. bool isFile() const { return !isExpansion(); }
  420. const FileInfo &getFile() const {
  421. assert(isFile() && "Not a file SLocEntry!");
  422. return File;
  423. }
  424. const ExpansionInfo &getExpansion() const {
  425. assert(isExpansion() && "Not a macro expansion SLocEntry!");
  426. return Expansion;
  427. }
  428. static SLocEntry get(SourceLocation::UIntTy Offset, const FileInfo &FI) {
  429. assert(!(Offset & (1ULL << OffsetBits)) && "Offset is too large");
  430. SLocEntry E;
  431. E.Offset = Offset;
  432. E.IsExpansion = false;
  433. E.File = FI;
  434. return E;
  435. }
  436. static SLocEntry get(SourceLocation::UIntTy Offset,
  437. const ExpansionInfo &Expansion) {
  438. assert(!(Offset & (1ULL << OffsetBits)) && "Offset is too large");
  439. SLocEntry E;
  440. E.Offset = Offset;
  441. E.IsExpansion = true;
  442. new (&E.Expansion) ExpansionInfo(Expansion);
  443. return E;
  444. }
  445. };
  446. } // namespace SrcMgr
  447. /// External source of source location entries.
  448. class ExternalSLocEntrySource {
  449. public:
  450. virtual ~ExternalSLocEntrySource();
  451. /// Read the source location entry with index ID, which will always be
  452. /// less than -1.
  453. ///
  454. /// \returns true if an error occurred that prevented the source-location
  455. /// entry from being loaded.
  456. virtual bool ReadSLocEntry(int ID) = 0;
  457. /// Retrieve the module import location and name for the given ID, if
  458. /// in fact it was loaded from a module (rather than, say, a precompiled
  459. /// header).
  460. virtual std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) = 0;
  461. };
  462. /// Holds the cache used by isBeforeInTranslationUnit.
  463. ///
  464. /// The cache structure is complex enough to be worth breaking out of
  465. /// SourceManager.
  466. class InBeforeInTUCacheEntry {
  467. /// The FileID's of the cached query.
  468. ///
  469. /// If these match up with a subsequent query, the result can be reused.
  470. FileID LQueryFID, RQueryFID;
  471. /// True if LQueryFID was created before RQueryFID.
  472. ///
  473. /// This is used to compare macro expansion locations.
  474. bool IsLQFIDBeforeRQFID;
  475. /// The file found in common between the two \#include traces, i.e.,
  476. /// the nearest common ancestor of the \#include tree.
  477. FileID CommonFID;
  478. /// The offset of the previous query in CommonFID.
  479. ///
  480. /// Usually, this represents the location of the \#include for QueryFID, but
  481. /// if LQueryFID is a parent of RQueryFID (or vice versa) then these can be a
  482. /// random token in the parent.
  483. unsigned LCommonOffset, RCommonOffset;
  484. public:
  485. /// Return true if the currently cached values match up with
  486. /// the specified LHS/RHS query.
  487. ///
  488. /// If not, we can't use the cache.
  489. bool isCacheValid(FileID LHS, FileID RHS) const {
  490. return LQueryFID == LHS && RQueryFID == RHS;
  491. }
  492. /// If the cache is valid, compute the result given the
  493. /// specified offsets in the LHS/RHS FileID's.
  494. bool getCachedResult(unsigned LOffset, unsigned ROffset) const {
  495. // If one of the query files is the common file, use the offset. Otherwise,
  496. // use the #include loc in the common file.
  497. if (LQueryFID != CommonFID) LOffset = LCommonOffset;
  498. if (RQueryFID != CommonFID) ROffset = RCommonOffset;
  499. // It is common for multiple macro expansions to be "included" from the same
  500. // location (expansion location), in which case use the order of the FileIDs
  501. // to determine which came first. This will also take care the case where
  502. // one of the locations points at the inclusion/expansion point of the other
  503. // in which case its FileID will come before the other.
  504. if (LOffset == ROffset)
  505. return IsLQFIDBeforeRQFID;
  506. return LOffset < ROffset;
  507. }
  508. /// Set up a new query.
  509. void setQueryFIDs(FileID LHS, FileID RHS, bool isLFIDBeforeRFID) {
  510. assert(LHS != RHS);
  511. LQueryFID = LHS;
  512. RQueryFID = RHS;
  513. IsLQFIDBeforeRQFID = isLFIDBeforeRFID;
  514. }
  515. void clear() {
  516. LQueryFID = RQueryFID = FileID();
  517. IsLQFIDBeforeRQFID = false;
  518. }
  519. void setCommonLoc(FileID commonFID, unsigned lCommonOffset,
  520. unsigned rCommonOffset) {
  521. CommonFID = commonFID;
  522. LCommonOffset = lCommonOffset;
  523. RCommonOffset = rCommonOffset;
  524. }
  525. };
  526. /// The stack used when building modules on demand, which is used
  527. /// to provide a link between the source managers of the different compiler
  528. /// instances.
  529. using ModuleBuildStack = ArrayRef<std::pair<std::string, FullSourceLoc>>;
  530. /// This class handles loading and caching of source files into memory.
  531. ///
  532. /// This object owns the MemoryBuffer objects for all of the loaded
  533. /// files and assigns unique FileID's for each unique \#include chain.
  534. ///
  535. /// The SourceManager can be queried for information about SourceLocation
  536. /// objects, turning them into either spelling or expansion locations. Spelling
  537. /// locations represent where the bytes corresponding to a token came from and
  538. /// expansion locations represent where the location is in the user's view. In
  539. /// the case of a macro expansion, for example, the spelling location indicates
  540. /// where the expanded token came from and the expansion location specifies
  541. /// where it was expanded.
  542. class SourceManager : public RefCountedBase<SourceManager> {
  543. /// DiagnosticsEngine object.
  544. DiagnosticsEngine &Diag;
  545. FileManager &FileMgr;
  546. mutable llvm::BumpPtrAllocator ContentCacheAlloc;
  547. /// Memoized information about all of the files tracked by this
  548. /// SourceManager.
  549. ///
  550. /// This map allows us to merge ContentCache entries based
  551. /// on their FileEntry*. All ContentCache objects will thus have unique,
  552. /// non-null, FileEntry pointers.
  553. llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*> FileInfos;
  554. /// True if the ContentCache for files that are overridden by other
  555. /// files, should report the original file name. Defaults to true.
  556. bool OverridenFilesKeepOriginalName = true;
  557. /// True if non-system source files should be treated as volatile
  558. /// (likely to change while trying to use them). Defaults to false.
  559. bool UserFilesAreVolatile;
  560. /// True if all files read during this compilation should be treated
  561. /// as transient (may not be present in later compilations using a module
  562. /// file created from this compilation). Defaults to false.
  563. bool FilesAreTransient = false;
  564. struct OverriddenFilesInfoTy {
  565. /// Files that have been overridden with the contents from another
  566. /// file.
  567. llvm::DenseMap<const FileEntry *, const FileEntry *> OverriddenFiles;
  568. /// Files that were overridden with a memory buffer.
  569. llvm::DenseSet<const FileEntry *> OverriddenFilesWithBuffer;
  570. };
  571. /// Lazily create the object keeping overridden files info, since
  572. /// it is uncommonly used.
  573. std::unique_ptr<OverriddenFilesInfoTy> OverriddenFilesInfo;
  574. OverriddenFilesInfoTy &getOverriddenFilesInfo() {
  575. if (!OverriddenFilesInfo)
  576. OverriddenFilesInfo.reset(new OverriddenFilesInfoTy);
  577. return *OverriddenFilesInfo;
  578. }
  579. /// Information about various memory buffers that we have read in.
  580. ///
  581. /// All FileEntry* within the stored ContentCache objects are NULL,
  582. /// as they do not refer to a file.
  583. std::vector<SrcMgr::ContentCache*> MemBufferInfos;
  584. /// The table of SLocEntries that are local to this module.
  585. ///
  586. /// Positive FileIDs are indexes into this table. Entry 0 indicates an invalid
  587. /// expansion.
  588. SmallVector<SrcMgr::SLocEntry, 0> LocalSLocEntryTable;
  589. /// The table of SLocEntries that are loaded from other modules.
  590. ///
  591. /// Negative FileIDs are indexes into this table. To get from ID to an index,
  592. /// use (-ID - 2).
  593. SmallVector<SrcMgr::SLocEntry, 0> LoadedSLocEntryTable;
  594. /// The starting offset of the next local SLocEntry.
  595. ///
  596. /// This is LocalSLocEntryTable.back().Offset + the size of that entry.
  597. SourceLocation::UIntTy NextLocalOffset;
  598. /// The starting offset of the latest batch of loaded SLocEntries.
  599. ///
  600. /// This is LoadedSLocEntryTable.back().Offset, except that that entry might
  601. /// not have been loaded, so that value would be unknown.
  602. SourceLocation::UIntTy CurrentLoadedOffset;
  603. /// The highest possible offset is 2^32-1 (2^63-1 for 64-bit source
  604. /// locations), so CurrentLoadedOffset starts at 2^31 (2^63 resp.).
  605. static const SourceLocation::UIntTy MaxLoadedOffset =
  606. 1ULL << (8 * sizeof(SourceLocation::UIntTy) - 1);
  607. /// A bitmap that indicates whether the entries of LoadedSLocEntryTable
  608. /// have already been loaded from the external source.
  609. ///
  610. /// Same indexing as LoadedSLocEntryTable.
  611. llvm::BitVector SLocEntryLoaded;
  612. /// An external source for source location entries.
  613. ExternalSLocEntrySource *ExternalSLocEntries = nullptr;
  614. /// A one-entry cache to speed up getFileID.
  615. ///
  616. /// LastFileIDLookup records the last FileID looked up or created, because it
  617. /// is very common to look up many tokens from the same file.
  618. mutable FileID LastFileIDLookup;
  619. /// Holds information for \#line directives.
  620. ///
  621. /// This is referenced by indices from SLocEntryTable.
  622. std::unique_ptr<LineTableInfo> LineTable;
  623. /// These ivars serve as a cache used in the getLineNumber
  624. /// method which is used to speedup getLineNumber calls to nearby locations.
  625. mutable FileID LastLineNoFileIDQuery;
  626. mutable const SrcMgr::ContentCache *LastLineNoContentCache;
  627. mutable unsigned LastLineNoFilePos;
  628. mutable unsigned LastLineNoResult;
  629. /// The file ID for the main source file of the translation unit.
  630. FileID MainFileID;
  631. /// The file ID for the precompiled preamble there is one.
  632. FileID PreambleFileID;
  633. // Statistics for -print-stats.
  634. mutable unsigned NumLinearScans = 0;
  635. mutable unsigned NumBinaryProbes = 0;
  636. /// Associates a FileID with its "included/expanded in" decomposed
  637. /// location.
  638. ///
  639. /// Used to cache results from and speed-up \c getDecomposedIncludedLoc
  640. /// function.
  641. mutable llvm::DenseMap<FileID, std::pair<FileID, unsigned>> IncludedLocMap;
  642. /// The key value into the IsBeforeInTUCache table.
  643. using IsBeforeInTUCacheKey = std::pair<FileID, FileID>;
  644. /// The IsBeforeInTranslationUnitCache is a mapping from FileID pairs
  645. /// to cache results.
  646. using InBeforeInTUCache =
  647. llvm::DenseMap<IsBeforeInTUCacheKey, InBeforeInTUCacheEntry>;
  648. /// Cache results for the isBeforeInTranslationUnit method.
  649. mutable InBeforeInTUCache IBTUCache;
  650. mutable InBeforeInTUCacheEntry IBTUCacheOverflow;
  651. /// Return the cache entry for comparing the given file IDs
  652. /// for isBeforeInTranslationUnit.
  653. InBeforeInTUCacheEntry &getInBeforeInTUCache(FileID LFID, FileID RFID) const;
  654. // Cache for the "fake" buffer used for error-recovery purposes.
  655. mutable std::unique_ptr<llvm::MemoryBuffer> FakeBufferForRecovery;
  656. mutable std::unique_ptr<SrcMgr::ContentCache> FakeContentCacheForRecovery;
  657. mutable std::unique_ptr<SrcMgr::SLocEntry> FakeSLocEntryForRecovery;
  658. /// Lazily computed map of macro argument chunks to their expanded
  659. /// source location.
  660. using MacroArgsMap = std::map<unsigned, SourceLocation>;
  661. mutable llvm::DenseMap<FileID, std::unique_ptr<MacroArgsMap>>
  662. MacroArgsCacheMap;
  663. /// The stack of modules being built, which is used to detect
  664. /// cycles in the module dependency graph as modules are being built, as
  665. /// well as to describe why we're rebuilding a particular module.
  666. ///
  667. /// There is no way to set this value from the command line. If we ever need
  668. /// to do so (e.g., if on-demand module construction moves out-of-process),
  669. /// we can add a cc1-level option to do so.
  670. SmallVector<std::pair<std::string, FullSourceLoc>, 2> StoredModuleBuildStack;
  671. public:
  672. SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
  673. bool UserFilesAreVolatile = false);
  674. explicit SourceManager(const SourceManager &) = delete;
  675. SourceManager &operator=(const SourceManager &) = delete;
  676. ~SourceManager();
  677. void clearIDTables();
  678. /// Initialize this source manager suitably to replay the compilation
  679. /// described by \p Old. Requires that \p Old outlive \p *this.
  680. void initializeForReplay(const SourceManager &Old);
  681. DiagnosticsEngine &getDiagnostics() const { return Diag; }
  682. FileManager &getFileManager() const { return FileMgr; }
  683. /// Set true if the SourceManager should report the original file name
  684. /// for contents of files that were overridden by other files. Defaults to
  685. /// true.
  686. void setOverridenFilesKeepOriginalName(bool value) {
  687. OverridenFilesKeepOriginalName = value;
  688. }
  689. /// True if non-system source files should be treated as volatile
  690. /// (likely to change while trying to use them).
  691. bool userFilesAreVolatile() const { return UserFilesAreVolatile; }
  692. /// Retrieve the module build stack.
  693. ModuleBuildStack getModuleBuildStack() const {
  694. return StoredModuleBuildStack;
  695. }
  696. /// Set the module build stack.
  697. void setModuleBuildStack(ModuleBuildStack stack) {
  698. StoredModuleBuildStack.clear();
  699. StoredModuleBuildStack.append(stack.begin(), stack.end());
  700. }
  701. /// Push an entry to the module build stack.
  702. void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc) {
  703. StoredModuleBuildStack.push_back(std::make_pair(moduleName.str(),importLoc));
  704. }
  705. //===--------------------------------------------------------------------===//
  706. // MainFileID creation and querying methods.
  707. //===--------------------------------------------------------------------===//
  708. /// Returns the FileID of the main source file.
  709. FileID getMainFileID() const { return MainFileID; }
  710. /// Set the file ID for the main source file.
  711. void setMainFileID(FileID FID) {
  712. MainFileID = FID;
  713. }
  714. /// Returns true when the given FileEntry corresponds to the main file.
  715. ///
  716. /// The main file should be set prior to calling this function.
  717. bool isMainFile(const FileEntry &SourceFile);
  718. /// Set the file ID for the precompiled preamble.
  719. void setPreambleFileID(FileID Preamble) {
  720. assert(PreambleFileID.isInvalid() && "PreambleFileID already set!");
  721. PreambleFileID = Preamble;
  722. }
  723. /// Get the file ID for the precompiled preamble if there is one.
  724. FileID getPreambleFileID() const { return PreambleFileID; }
  725. //===--------------------------------------------------------------------===//
  726. // Methods to create new FileID's and macro expansions.
  727. //===--------------------------------------------------------------------===//
  728. /// Create a new FileID that represents the specified file
  729. /// being \#included from the specified IncludePosition.
  730. ///
  731. /// This translates NULL into standard input.
  732. FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos,
  733. SrcMgr::CharacteristicKind FileCharacter,
  734. int LoadedID = 0,
  735. SourceLocation::UIntTy LoadedOffset = 0);
  736. FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos,
  737. SrcMgr::CharacteristicKind FileCharacter,
  738. int LoadedID = 0,
  739. SourceLocation::UIntTy LoadedOffset = 0);
  740. /// Create a new FileID that represents the specified memory buffer.
  741. ///
  742. /// This does no caching of the buffer and takes ownership of the
  743. /// MemoryBuffer, so only pass a MemoryBuffer to this once.
  744. FileID createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
  745. SrcMgr::CharacteristicKind FileCharacter = SrcMgr::C_User,
  746. int LoadedID = 0, SourceLocation::UIntTy LoadedOffset = 0,
  747. SourceLocation IncludeLoc = SourceLocation());
  748. /// Create a new FileID that represents the specified memory buffer.
  749. ///
  750. /// This does not take ownership of the MemoryBuffer. The memory buffer must
  751. /// outlive the SourceManager.
  752. FileID createFileID(const llvm::MemoryBufferRef &Buffer,
  753. SrcMgr::CharacteristicKind FileCharacter = SrcMgr::C_User,
  754. int LoadedID = 0, SourceLocation::UIntTy LoadedOffset = 0,
  755. SourceLocation IncludeLoc = SourceLocation());
  756. /// Get the FileID for \p SourceFile if it exists. Otherwise, create a
  757. /// new FileID for the \p SourceFile.
  758. FileID getOrCreateFileID(const FileEntry *SourceFile,
  759. SrcMgr::CharacteristicKind FileCharacter);
  760. /// Return a new SourceLocation that encodes the
  761. /// fact that a token from SpellingLoc should actually be referenced from
  762. /// ExpansionLoc, and that it represents the expansion of a macro argument
  763. /// into the function-like macro body.
  764. SourceLocation createMacroArgExpansionLoc(SourceLocation Loc,
  765. SourceLocation ExpansionLoc,
  766. unsigned TokLength);
  767. /// Return a new SourceLocation that encodes the fact
  768. /// that a token from SpellingLoc should actually be referenced from
  769. /// ExpansionLoc.
  770. SourceLocation
  771. createExpansionLoc(SourceLocation Loc, SourceLocation ExpansionLocStart,
  772. SourceLocation ExpansionLocEnd, unsigned TokLength,
  773. bool ExpansionIsTokenRange = true, int LoadedID = 0,
  774. SourceLocation::UIntTy LoadedOffset = 0);
  775. /// Return a new SourceLocation that encodes that the token starting
  776. /// at \p TokenStart ends prematurely at \p TokenEnd.
  777. SourceLocation createTokenSplitLoc(SourceLocation SpellingLoc,
  778. SourceLocation TokenStart,
  779. SourceLocation TokenEnd);
  780. /// Retrieve the memory buffer associated with the given file.
  781. ///
  782. /// Returns None if the buffer is not valid.
  783. llvm::Optional<llvm::MemoryBufferRef>
  784. getMemoryBufferForFileOrNone(const FileEntry *File);
  785. /// Retrieve the memory buffer associated with the given file.
  786. ///
  787. /// Returns a fake buffer if there isn't a real one.
  788. llvm::MemoryBufferRef getMemoryBufferForFileOrFake(const FileEntry *File) {
  789. if (auto B = getMemoryBufferForFileOrNone(File))
  790. return *B;
  791. return getFakeBufferForRecovery();
  792. }
  793. /// Override the contents of the given source file by providing an
  794. /// already-allocated buffer.
  795. ///
  796. /// \param SourceFile the source file whose contents will be overridden.
  797. ///
  798. /// \param Buffer the memory buffer whose contents will be used as the
  799. /// data in the given source file.
  800. void overrideFileContents(const FileEntry *SourceFile,
  801. const llvm::MemoryBufferRef &Buffer) {
  802. overrideFileContents(SourceFile, llvm::MemoryBuffer::getMemBuffer(Buffer));
  803. }
  804. /// Override the contents of the given source file by providing an
  805. /// already-allocated buffer.
  806. ///
  807. /// \param SourceFile the source file whose contents will be overridden.
  808. ///
  809. /// \param Buffer the memory buffer whose contents will be used as the
  810. /// data in the given source file.
  811. void overrideFileContents(const FileEntry *SourceFile,
  812. std::unique_ptr<llvm::MemoryBuffer> Buffer);
  813. void overrideFileContents(FileEntryRef SourceFile,
  814. std::unique_ptr<llvm::MemoryBuffer> Buffer) {
  815. overrideFileContents(&SourceFile.getFileEntry(), std::move(Buffer));
  816. }
  817. /// Override the given source file with another one.
  818. ///
  819. /// \param SourceFile the source file which will be overridden.
  820. ///
  821. /// \param NewFile the file whose contents will be used as the
  822. /// data instead of the contents of the given source file.
  823. void overrideFileContents(const FileEntry *SourceFile,
  824. const FileEntry *NewFile);
  825. /// Returns true if the file contents have been overridden.
  826. bool isFileOverridden(const FileEntry *File) const {
  827. if (OverriddenFilesInfo) {
  828. if (OverriddenFilesInfo->OverriddenFilesWithBuffer.count(File))
  829. return true;
  830. if (OverriddenFilesInfo->OverriddenFiles.find(File) !=
  831. OverriddenFilesInfo->OverriddenFiles.end())
  832. return true;
  833. }
  834. return false;
  835. }
  836. /// Bypass the overridden contents of a file. This creates a new FileEntry
  837. /// and initializes the content cache for it. Returns None if there is no
  838. /// such file in the filesystem.
  839. ///
  840. /// This should be called before parsing has begun.
  841. Optional<FileEntryRef> bypassFileContentsOverride(FileEntryRef File);
  842. /// Specify that a file is transient.
  843. void setFileIsTransient(const FileEntry *SourceFile);
  844. /// Specify that all files that are read during this compilation are
  845. /// transient.
  846. void setAllFilesAreTransient(bool Transient) {
  847. FilesAreTransient = Transient;
  848. }
  849. //===--------------------------------------------------------------------===//
  850. // FileID manipulation methods.
  851. //===--------------------------------------------------------------------===//
  852. /// Return the buffer for the specified FileID.
  853. ///
  854. /// If there is an error opening this buffer the first time, return None.
  855. llvm::Optional<llvm::MemoryBufferRef>
  856. getBufferOrNone(FileID FID, SourceLocation Loc = SourceLocation()) const {
  857. if (auto *Entry = getSLocEntryForFile(FID))
  858. return Entry->getFile().getContentCache().getBufferOrNone(
  859. Diag, getFileManager(), Loc);
  860. return None;
  861. }
  862. /// Return the buffer for the specified FileID.
  863. ///
  864. /// If there is an error opening this buffer the first time, this
  865. /// manufactures a temporary buffer and returns it.
  866. llvm::MemoryBufferRef
  867. getBufferOrFake(FileID FID, SourceLocation Loc = SourceLocation()) const {
  868. if (auto B = getBufferOrNone(FID, Loc))
  869. return *B;
  870. return getFakeBufferForRecovery();
  871. }
  872. /// Returns the FileEntry record for the provided FileID.
  873. const FileEntry *getFileEntryForID(FileID FID) const {
  874. if (auto *Entry = getSLocEntryForFile(FID))
  875. return Entry->getFile().getContentCache().OrigEntry;
  876. return nullptr;
  877. }
  878. /// Returns the FileEntryRef for the provided FileID.
  879. Optional<FileEntryRef> getFileEntryRefForID(FileID FID) const {
  880. if (auto *Entry = getFileEntryForID(FID))
  881. return Entry->getLastRef();
  882. return None;
  883. }
  884. /// Returns the filename for the provided FileID, unless it's a built-in
  885. /// buffer that's not represented by a filename.
  886. ///
  887. /// Returns None for non-files and built-in files.
  888. Optional<StringRef> getNonBuiltinFilenameForID(FileID FID) const;
  889. /// Returns the FileEntry record for the provided SLocEntry.
  890. const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const
  891. {
  892. return sloc.getFile().getContentCache().OrigEntry;
  893. }
  894. /// Return a StringRef to the source buffer data for the
  895. /// specified FileID.
  896. ///
  897. /// \param FID The file ID whose contents will be returned.
  898. /// \param Invalid If non-NULL, will be set true if an error occurred.
  899. StringRef getBufferData(FileID FID, bool *Invalid = nullptr) const;
  900. /// Return a StringRef to the source buffer data for the
  901. /// specified FileID, returning None if invalid.
  902. ///
  903. /// \param FID The file ID whose contents will be returned.
  904. llvm::Optional<StringRef> getBufferDataOrNone(FileID FID) const;
  905. /// Return a StringRef to the source buffer data for the
  906. /// specified FileID, returning None if it's not yet loaded.
  907. ///
  908. /// \param FID The file ID whose contents will be returned.
  909. llvm::Optional<StringRef> getBufferDataIfLoaded(FileID FID) const;
  910. /// Get the number of FileIDs (files and macros) that were created
  911. /// during preprocessing of \p FID, including it.
  912. unsigned getNumCreatedFIDsForFileID(FileID FID) const {
  913. if (auto *Entry = getSLocEntryForFile(FID))
  914. return Entry->getFile().NumCreatedFIDs;
  915. return 0;
  916. }
  917. /// Set the number of FileIDs (files and macros) that were created
  918. /// during preprocessing of \p FID, including it.
  919. void setNumCreatedFIDsForFileID(FileID FID, unsigned NumFIDs,
  920. bool Force = false) const {
  921. auto *Entry = getSLocEntryForFile(FID);
  922. if (!Entry)
  923. return;
  924. assert((Force || Entry->getFile().NumCreatedFIDs == 0) && "Already set!");
  925. const_cast<SrcMgr::FileInfo &>(Entry->getFile()).NumCreatedFIDs = NumFIDs;
  926. }
  927. //===--------------------------------------------------------------------===//
  928. // SourceLocation manipulation methods.
  929. //===--------------------------------------------------------------------===//
  930. /// Return the FileID for a SourceLocation.
  931. ///
  932. /// This is a very hot method that is used for all SourceManager queries
  933. /// that start with a SourceLocation object. It is responsible for finding
  934. /// the entry in SLocEntryTable which contains the specified location.
  935. ///
  936. FileID getFileID(SourceLocation SpellingLoc) const {
  937. SourceLocation::UIntTy SLocOffset = SpellingLoc.getOffset();
  938. // If our one-entry cache covers this offset, just return it.
  939. if (isOffsetInFileID(LastFileIDLookup, SLocOffset))
  940. return LastFileIDLookup;
  941. return getFileIDSlow(SLocOffset);
  942. }
  943. /// Return the filename of the file containing a SourceLocation.
  944. StringRef getFilename(SourceLocation SpellingLoc) const;
  945. /// Return the source location corresponding to the first byte of
  946. /// the specified file.
  947. SourceLocation getLocForStartOfFile(FileID FID) const {
  948. if (auto *Entry = getSLocEntryForFile(FID))
  949. return SourceLocation::getFileLoc(Entry->getOffset());
  950. return SourceLocation();
  951. }
  952. /// Return the source location corresponding to the last byte of the
  953. /// specified file.
  954. SourceLocation getLocForEndOfFile(FileID FID) const {
  955. if (auto *Entry = getSLocEntryForFile(FID))
  956. return SourceLocation::getFileLoc(Entry->getOffset() +
  957. getFileIDSize(FID));
  958. return SourceLocation();
  959. }
  960. /// Returns the include location if \p FID is a \#include'd file
  961. /// otherwise it returns an invalid location.
  962. SourceLocation getIncludeLoc(FileID FID) const {
  963. if (auto *Entry = getSLocEntryForFile(FID))
  964. return Entry->getFile().getIncludeLoc();
  965. return SourceLocation();
  966. }
  967. // Returns the import location if the given source location is
  968. // located within a module, or an invalid location if the source location
  969. // is within the current translation unit.
  970. std::pair<SourceLocation, StringRef>
  971. getModuleImportLoc(SourceLocation Loc) const {
  972. FileID FID = getFileID(Loc);
  973. // Positive file IDs are in the current translation unit, and -1 is a
  974. // placeholder.
  975. if (FID.ID >= -1)
  976. return std::make_pair(SourceLocation(), "");
  977. return ExternalSLocEntries->getModuleImportLoc(FID.ID);
  978. }
  979. /// Given a SourceLocation object \p Loc, return the expansion
  980. /// location referenced by the ID.
  981. SourceLocation getExpansionLoc(SourceLocation Loc) const {
  982. // Handle the non-mapped case inline, defer to out of line code to handle
  983. // expansions.
  984. if (Loc.isFileID()) return Loc;
  985. return getExpansionLocSlowCase(Loc);
  986. }
  987. /// Given \p Loc, if it is a macro location return the expansion
  988. /// location or the spelling location, depending on if it comes from a
  989. /// macro argument or not.
  990. SourceLocation getFileLoc(SourceLocation Loc) const {
  991. if (Loc.isFileID()) return Loc;
  992. return getFileLocSlowCase(Loc);
  993. }
  994. /// Return the start/end of the expansion information for an
  995. /// expansion location.
  996. ///
  997. /// \pre \p Loc is required to be an expansion location.
  998. CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const;
  999. /// Given a SourceLocation object, return the range of
  1000. /// tokens covered by the expansion in the ultimate file.
  1001. CharSourceRange getExpansionRange(SourceLocation Loc) const;
  1002. /// Given a SourceRange object, return the range of
  1003. /// tokens or characters covered by the expansion in the ultimate file.
  1004. CharSourceRange getExpansionRange(SourceRange Range) const {
  1005. SourceLocation Begin = getExpansionRange(Range.getBegin()).getBegin();
  1006. CharSourceRange End = getExpansionRange(Range.getEnd());
  1007. return CharSourceRange(SourceRange(Begin, End.getEnd()),
  1008. End.isTokenRange());
  1009. }
  1010. /// Given a CharSourceRange object, return the range of
  1011. /// tokens or characters covered by the expansion in the ultimate file.
  1012. CharSourceRange getExpansionRange(CharSourceRange Range) const {
  1013. CharSourceRange Expansion = getExpansionRange(Range.getAsRange());
  1014. if (Expansion.getEnd() == Range.getEnd())
  1015. Expansion.setTokenRange(Range.isTokenRange());
  1016. return Expansion;
  1017. }
  1018. /// Given a SourceLocation object, return the spelling
  1019. /// location referenced by the ID.
  1020. ///
  1021. /// This is the place where the characters that make up the lexed token
  1022. /// can be found.
  1023. SourceLocation getSpellingLoc(SourceLocation Loc) const {
  1024. // Handle the non-mapped case inline, defer to out of line code to handle
  1025. // expansions.
  1026. if (Loc.isFileID()) return Loc;
  1027. return getSpellingLocSlowCase(Loc);
  1028. }
  1029. /// Given a SourceLocation object, return the spelling location
  1030. /// referenced by the ID.
  1031. ///
  1032. /// This is the first level down towards the place where the characters
  1033. /// that make up the lexed token can be found. This should not generally
  1034. /// be used by clients.
  1035. SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const;
  1036. /// Form a SourceLocation from a FileID and Offset pair.
  1037. SourceLocation getComposedLoc(FileID FID, unsigned Offset) const {
  1038. auto *Entry = getSLocEntryOrNull(FID);
  1039. if (!Entry)
  1040. return SourceLocation();
  1041. SourceLocation::UIntTy GlobalOffset = Entry->getOffset() + Offset;
  1042. return Entry->isFile() ? SourceLocation::getFileLoc(GlobalOffset)
  1043. : SourceLocation::getMacroLoc(GlobalOffset);
  1044. }
  1045. /// Decompose the specified location into a raw FileID + Offset pair.
  1046. ///
  1047. /// The first element is the FileID, the second is the offset from the
  1048. /// start of the buffer of the location.
  1049. std::pair<FileID, unsigned> getDecomposedLoc(SourceLocation Loc) const {
  1050. FileID FID = getFileID(Loc);
  1051. auto *Entry = getSLocEntryOrNull(FID);
  1052. if (!Entry)
  1053. return std::make_pair(FileID(), 0);
  1054. return std::make_pair(FID, Loc.getOffset() - Entry->getOffset());
  1055. }
  1056. /// Decompose the specified location into a raw FileID + Offset pair.
  1057. ///
  1058. /// If the location is an expansion record, walk through it until we find
  1059. /// the final location expanded.
  1060. std::pair<FileID, unsigned>
  1061. getDecomposedExpansionLoc(SourceLocation Loc) const {
  1062. FileID FID = getFileID(Loc);
  1063. auto *E = getSLocEntryOrNull(FID);
  1064. if (!E)
  1065. return std::make_pair(FileID(), 0);
  1066. unsigned Offset = Loc.getOffset()-E->getOffset();
  1067. if (Loc.isFileID())
  1068. return std::make_pair(FID, Offset);
  1069. return getDecomposedExpansionLocSlowCase(E);
  1070. }
  1071. /// Decompose the specified location into a raw FileID + Offset pair.
  1072. ///
  1073. /// If the location is an expansion record, walk through it until we find
  1074. /// its spelling record.
  1075. std::pair<FileID, unsigned>
  1076. getDecomposedSpellingLoc(SourceLocation Loc) const {
  1077. FileID FID = getFileID(Loc);
  1078. auto *E = getSLocEntryOrNull(FID);
  1079. if (!E)
  1080. return std::make_pair(FileID(), 0);
  1081. unsigned Offset = Loc.getOffset()-E->getOffset();
  1082. if (Loc.isFileID())
  1083. return std::make_pair(FID, Offset);
  1084. return getDecomposedSpellingLocSlowCase(E, Offset);
  1085. }
  1086. /// Returns the "included/expanded in" decomposed location of the given
  1087. /// FileID.
  1088. std::pair<FileID, unsigned> getDecomposedIncludedLoc(FileID FID) const;
  1089. /// Returns the offset from the start of the file that the
  1090. /// specified SourceLocation represents.
  1091. ///
  1092. /// This is not very meaningful for a macro ID.
  1093. unsigned getFileOffset(SourceLocation SpellingLoc) const {
  1094. return getDecomposedLoc(SpellingLoc).second;
  1095. }
  1096. /// Tests whether the given source location represents a macro
  1097. /// argument's expansion into the function-like macro definition.
  1098. ///
  1099. /// \param StartLoc If non-null and function returns true, it is set to the
  1100. /// start location of the macro argument expansion.
  1101. ///
  1102. /// Such source locations only appear inside of the expansion
  1103. /// locations representing where a particular function-like macro was
  1104. /// expanded.
  1105. bool isMacroArgExpansion(SourceLocation Loc,
  1106. SourceLocation *StartLoc = nullptr) const;
  1107. /// Tests whether the given source location represents the expansion of
  1108. /// a macro body.
  1109. ///
  1110. /// This is equivalent to testing whether the location is part of a macro
  1111. /// expansion but not the expansion of an argument to a function-like macro.
  1112. bool isMacroBodyExpansion(SourceLocation Loc) const;
  1113. /// Returns true if the given MacroID location points at the beginning
  1114. /// of the immediate macro expansion.
  1115. ///
  1116. /// \param MacroBegin If non-null and function returns true, it is set to the
  1117. /// begin location of the immediate macro expansion.
  1118. bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
  1119. SourceLocation *MacroBegin = nullptr) const;
  1120. /// Returns true if the given MacroID location points at the character
  1121. /// end of the immediate macro expansion.
  1122. ///
  1123. /// \param MacroEnd If non-null and function returns true, it is set to the
  1124. /// character end location of the immediate macro expansion.
  1125. bool
  1126. isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
  1127. SourceLocation *MacroEnd = nullptr) const;
  1128. /// Returns true if \p Loc is inside the [\p Start, +\p Length)
  1129. /// chunk of the source location address space.
  1130. ///
  1131. /// If it's true and \p RelativeOffset is non-null, it will be set to the
  1132. /// relative offset of \p Loc inside the chunk.
  1133. bool
  1134. isInSLocAddrSpace(SourceLocation Loc, SourceLocation Start, unsigned Length,
  1135. SourceLocation::UIntTy *RelativeOffset = nullptr) const {
  1136. assert(((Start.getOffset() < NextLocalOffset &&
  1137. Start.getOffset()+Length <= NextLocalOffset) ||
  1138. (Start.getOffset() >= CurrentLoadedOffset &&
  1139. Start.getOffset()+Length < MaxLoadedOffset)) &&
  1140. "Chunk is not valid SLoc address space");
  1141. SourceLocation::UIntTy LocOffs = Loc.getOffset();
  1142. SourceLocation::UIntTy BeginOffs = Start.getOffset();
  1143. SourceLocation::UIntTy EndOffs = BeginOffs + Length;
  1144. if (LocOffs >= BeginOffs && LocOffs < EndOffs) {
  1145. if (RelativeOffset)
  1146. *RelativeOffset = LocOffs - BeginOffs;
  1147. return true;
  1148. }
  1149. return false;
  1150. }
  1151. /// Return true if both \p LHS and \p RHS are in the local source
  1152. /// location address space or the loaded one.
  1153. ///
  1154. /// If it's true and \p RelativeOffset is non-null, it will be set to the
  1155. /// offset of \p RHS relative to \p LHS.
  1156. bool isInSameSLocAddrSpace(SourceLocation LHS, SourceLocation RHS,
  1157. SourceLocation::IntTy *RelativeOffset) const {
  1158. SourceLocation::UIntTy LHSOffs = LHS.getOffset(), RHSOffs = RHS.getOffset();
  1159. bool LHSLoaded = LHSOffs >= CurrentLoadedOffset;
  1160. bool RHSLoaded = RHSOffs >= CurrentLoadedOffset;
  1161. if (LHSLoaded == RHSLoaded) {
  1162. if (RelativeOffset)
  1163. *RelativeOffset = RHSOffs - LHSOffs;
  1164. return true;
  1165. }
  1166. return false;
  1167. }
  1168. //===--------------------------------------------------------------------===//
  1169. // Queries about the code at a SourceLocation.
  1170. //===--------------------------------------------------------------------===//
  1171. /// Return a pointer to the start of the specified location
  1172. /// in the appropriate spelling MemoryBuffer.
  1173. ///
  1174. /// \param Invalid If non-NULL, will be set \c true if an error occurs.
  1175. const char *getCharacterData(SourceLocation SL,
  1176. bool *Invalid = nullptr) const;
  1177. /// Return the column # for the specified file position.
  1178. ///
  1179. /// This is significantly cheaper to compute than the line number. This
  1180. /// returns zero if the column number isn't known. This may only be called
  1181. /// on a file sloc, so you must choose a spelling or expansion location
  1182. /// before calling this method.
  1183. unsigned getColumnNumber(FileID FID, unsigned FilePos,
  1184. bool *Invalid = nullptr) const;
  1185. unsigned getSpellingColumnNumber(SourceLocation Loc,
  1186. bool *Invalid = nullptr) const;
  1187. unsigned getExpansionColumnNumber(SourceLocation Loc,
  1188. bool *Invalid = nullptr) const;
  1189. unsigned getPresumedColumnNumber(SourceLocation Loc,
  1190. bool *Invalid = nullptr) const;
  1191. /// Given a SourceLocation, return the spelling line number
  1192. /// for the position indicated.
  1193. ///
  1194. /// This requires building and caching a table of line offsets for the
  1195. /// MemoryBuffer, so this is not cheap: use only when about to emit a
  1196. /// diagnostic.
  1197. unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid = nullptr) const;
  1198. unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
  1199. unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
  1200. unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid = nullptr) const;
  1201. /// Return the filename or buffer identifier of the buffer the
  1202. /// location is in.
  1203. ///
  1204. /// Note that this name does not respect \#line directives. Use
  1205. /// getPresumedLoc for normal clients.
  1206. StringRef getBufferName(SourceLocation Loc, bool *Invalid = nullptr) const;
  1207. /// Return the file characteristic of the specified source
  1208. /// location, indicating whether this is a normal file, a system
  1209. /// header, or an "implicit extern C" system header.
  1210. ///
  1211. /// This state can be modified with flags on GNU linemarker directives like:
  1212. /// \code
  1213. /// # 4 "foo.h" 3
  1214. /// \endcode
  1215. /// which changes all source locations in the current file after that to be
  1216. /// considered to be from a system header.
  1217. SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const;
  1218. /// Returns the "presumed" location of a SourceLocation specifies.
  1219. ///
  1220. /// A "presumed location" can be modified by \#line or GNU line marker
  1221. /// directives. This provides a view on the data that a user should see
  1222. /// in diagnostics, for example.
  1223. ///
  1224. /// Note that a presumed location is always given as the expansion point of
  1225. /// an expansion location, not at the spelling location.
  1226. ///
  1227. /// \returns The presumed location of the specified SourceLocation. If the
  1228. /// presumed location cannot be calculated (e.g., because \p Loc is invalid
  1229. /// or the file containing \p Loc has changed on disk), returns an invalid
  1230. /// presumed location.
  1231. PresumedLoc getPresumedLoc(SourceLocation Loc,
  1232. bool UseLineDirectives = true) const;
  1233. /// Returns whether the PresumedLoc for a given SourceLocation is
  1234. /// in the main file.
  1235. ///
  1236. /// This computes the "presumed" location for a SourceLocation, then checks
  1237. /// whether it came from a file other than the main file. This is different
  1238. /// from isWrittenInMainFile() because it takes line marker directives into
  1239. /// account.
  1240. bool isInMainFile(SourceLocation Loc) const;
  1241. /// Returns true if the spelling locations for both SourceLocations
  1242. /// are part of the same file buffer.
  1243. ///
  1244. /// This check ignores line marker directives.
  1245. bool isWrittenInSameFile(SourceLocation Loc1, SourceLocation Loc2) const {
  1246. return getFileID(Loc1) == getFileID(Loc2);
  1247. }
  1248. /// Returns true if the spelling location for the given location
  1249. /// is in the main file buffer.
  1250. ///
  1251. /// This check ignores line marker directives.
  1252. bool isWrittenInMainFile(SourceLocation Loc) const {
  1253. return getFileID(Loc) == getMainFileID();
  1254. }
  1255. /// Returns whether \p Loc is located in a <built-in> file.
  1256. bool isWrittenInBuiltinFile(SourceLocation Loc) const {
  1257. StringRef Filename(getPresumedLoc(Loc).getFilename());
  1258. return Filename.equals("<built-in>");
  1259. }
  1260. /// Returns whether \p Loc is located in a <command line> file.
  1261. bool isWrittenInCommandLineFile(SourceLocation Loc) const {
  1262. StringRef Filename(getPresumedLoc(Loc).getFilename());
  1263. return Filename.equals("<command line>");
  1264. }
  1265. /// Returns whether \p Loc is located in a <scratch space> file.
  1266. bool isWrittenInScratchSpace(SourceLocation Loc) const {
  1267. StringRef Filename(getPresumedLoc(Loc).getFilename());
  1268. return Filename.equals("<scratch space>");
  1269. }
  1270. /// Returns if a SourceLocation is in a system header.
  1271. bool isInSystemHeader(SourceLocation Loc) const {
  1272. return isSystem(getFileCharacteristic(Loc));
  1273. }
  1274. /// Returns if a SourceLocation is in an "extern C" system header.
  1275. bool isInExternCSystemHeader(SourceLocation Loc) const {
  1276. return getFileCharacteristic(Loc) == SrcMgr::C_ExternCSystem;
  1277. }
  1278. /// Returns whether \p Loc is expanded from a macro in a system header.
  1279. bool isInSystemMacro(SourceLocation loc) const {
  1280. if (!loc.isMacroID())
  1281. return false;
  1282. // This happens when the macro is the result of a paste, in that case
  1283. // its spelling is the scratch memory, so we take the parent context.
  1284. // There can be several level of token pasting.
  1285. if (isWrittenInScratchSpace(getSpellingLoc(loc))) {
  1286. do {
  1287. loc = getImmediateMacroCallerLoc(loc);
  1288. } while (isWrittenInScratchSpace(getSpellingLoc(loc)));
  1289. return isInSystemMacro(loc);
  1290. }
  1291. return isInSystemHeader(getSpellingLoc(loc));
  1292. }
  1293. /// The size of the SLocEntry that \p FID represents.
  1294. unsigned getFileIDSize(FileID FID) const;
  1295. /// Given a specific FileID, returns true if \p Loc is inside that
  1296. /// FileID chunk and sets relative offset (offset of \p Loc from beginning
  1297. /// of FileID) to \p relativeOffset.
  1298. bool isInFileID(SourceLocation Loc, FileID FID,
  1299. unsigned *RelativeOffset = nullptr) const {
  1300. SourceLocation::UIntTy Offs = Loc.getOffset();
  1301. if (isOffsetInFileID(FID, Offs)) {
  1302. if (RelativeOffset)
  1303. *RelativeOffset = Offs - getSLocEntry(FID).getOffset();
  1304. return true;
  1305. }
  1306. return false;
  1307. }
  1308. //===--------------------------------------------------------------------===//
  1309. // Line Table Manipulation Routines
  1310. //===--------------------------------------------------------------------===//
  1311. /// Return the uniqued ID for the specified filename.
  1312. unsigned getLineTableFilenameID(StringRef Str);
  1313. /// Add a line note to the line table for the FileID and offset
  1314. /// specified by Loc.
  1315. ///
  1316. /// If FilenameID is -1, it is considered to be unspecified.
  1317. void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID,
  1318. bool IsFileEntry, bool IsFileExit,
  1319. SrcMgr::CharacteristicKind FileKind);
  1320. /// Determine if the source manager has a line table.
  1321. bool hasLineTable() const { return LineTable != nullptr; }
  1322. /// Retrieve the stored line table.
  1323. LineTableInfo &getLineTable();
  1324. //===--------------------------------------------------------------------===//
  1325. // Queries for performance analysis.
  1326. //===--------------------------------------------------------------------===//
  1327. /// Return the total amount of physical memory allocated by the
  1328. /// ContentCache allocator.
  1329. size_t getContentCacheSize() const {
  1330. return ContentCacheAlloc.getTotalMemory();
  1331. }
  1332. struct MemoryBufferSizes {
  1333. const size_t malloc_bytes;
  1334. const size_t mmap_bytes;
  1335. MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
  1336. : malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
  1337. };
  1338. /// Return the amount of memory used by memory buffers, breaking down
  1339. /// by heap-backed versus mmap'ed memory.
  1340. MemoryBufferSizes getMemoryBufferSizes() const;
  1341. /// Return the amount of memory used for various side tables and
  1342. /// data structures in the SourceManager.
  1343. size_t getDataStructureSizes() const;
  1344. //===--------------------------------------------------------------------===//
  1345. // Other miscellaneous methods.
  1346. //===--------------------------------------------------------------------===//
  1347. /// Get the source location for the given file:line:col triplet.
  1348. ///
  1349. /// If the source file is included multiple times, the source location will
  1350. /// be based upon the first inclusion.
  1351. SourceLocation translateFileLineCol(const FileEntry *SourceFile,
  1352. unsigned Line, unsigned Col) const;
  1353. /// Get the FileID for the given file.
  1354. ///
  1355. /// If the source file is included multiple times, the FileID will be the
  1356. /// first inclusion.
  1357. FileID translateFile(const FileEntry *SourceFile) const;
  1358. FileID translateFile(FileEntryRef SourceFile) const {
  1359. return translateFile(&SourceFile.getFileEntry());
  1360. }
  1361. /// Get the source location in \p FID for the given line:col.
  1362. /// Returns null location if \p FID is not a file SLocEntry.
  1363. SourceLocation translateLineCol(FileID FID,
  1364. unsigned Line, unsigned Col) const;
  1365. /// If \p Loc points inside a function macro argument, the returned
  1366. /// location will be the macro location in which the argument was expanded.
  1367. /// If a macro argument is used multiple times, the expanded location will
  1368. /// be at the first expansion of the argument.
  1369. /// e.g.
  1370. /// MY_MACRO(foo);
  1371. /// ^
  1372. /// Passing a file location pointing at 'foo', will yield a macro location
  1373. /// where 'foo' was expanded into.
  1374. SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const;
  1375. /// Determines the order of 2 source locations in the translation unit.
  1376. ///
  1377. /// \returns true if LHS source location comes before RHS, false otherwise.
  1378. bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const;
  1379. /// Determines whether the two decomposed source location is in the
  1380. /// same translation unit. As a byproduct, it also calculates the order
  1381. /// of the source locations in case they are in the same TU.
  1382. ///
  1383. /// \returns Pair of bools the first component is true if the two locations
  1384. /// are in the same TU. The second bool is true if the first is true
  1385. /// and \p LOffs is before \p ROffs.
  1386. std::pair<bool, bool>
  1387. isInTheSameTranslationUnit(std::pair<FileID, unsigned> &LOffs,
  1388. std::pair<FileID, unsigned> &ROffs) const;
  1389. /// Determines the order of 2 source locations in the "source location
  1390. /// address space".
  1391. bool isBeforeInSLocAddrSpace(SourceLocation LHS, SourceLocation RHS) const {
  1392. return isBeforeInSLocAddrSpace(LHS, RHS.getOffset());
  1393. }
  1394. /// Determines the order of a source location and a source location
  1395. /// offset in the "source location address space".
  1396. ///
  1397. /// Note that we always consider source locations loaded from
  1398. bool isBeforeInSLocAddrSpace(SourceLocation LHS,
  1399. SourceLocation::UIntTy RHS) const {
  1400. SourceLocation::UIntTy LHSOffset = LHS.getOffset();
  1401. bool LHSLoaded = LHSOffset >= CurrentLoadedOffset;
  1402. bool RHSLoaded = RHS >= CurrentLoadedOffset;
  1403. if (LHSLoaded == RHSLoaded)
  1404. return LHSOffset < RHS;
  1405. return LHSLoaded;
  1406. }
  1407. /// Return true if the Point is within Start and End.
  1408. bool isPointWithin(SourceLocation Location, SourceLocation Start,
  1409. SourceLocation End) const {
  1410. return Location == Start || Location == End ||
  1411. (isBeforeInTranslationUnit(Start, Location) &&
  1412. isBeforeInTranslationUnit(Location, End));
  1413. }
  1414. // Iterators over FileInfos.
  1415. using fileinfo_iterator =
  1416. llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::const_iterator;
  1417. fileinfo_iterator fileinfo_begin() const { return FileInfos.begin(); }
  1418. fileinfo_iterator fileinfo_end() const { return FileInfos.end(); }
  1419. bool hasFileInfo(const FileEntry *File) const {
  1420. return FileInfos.find(File) != FileInfos.end();
  1421. }
  1422. /// Print statistics to stderr.
  1423. void PrintStats() const;
  1424. void dump() const;
  1425. /// Get the number of local SLocEntries we have.
  1426. unsigned local_sloc_entry_size() const { return LocalSLocEntryTable.size(); }
  1427. /// Get a local SLocEntry. This is exposed for indexing.
  1428. const SrcMgr::SLocEntry &getLocalSLocEntry(unsigned Index) const {
  1429. assert(Index < LocalSLocEntryTable.size() && "Invalid index");
  1430. return LocalSLocEntryTable[Index];
  1431. }
  1432. /// Get the number of loaded SLocEntries we have.
  1433. unsigned loaded_sloc_entry_size() const { return LoadedSLocEntryTable.size();}
  1434. /// Get a loaded SLocEntry. This is exposed for indexing.
  1435. const SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index,
  1436. bool *Invalid = nullptr) const {
  1437. assert(Index < LoadedSLocEntryTable.size() && "Invalid index");
  1438. if (SLocEntryLoaded[Index])
  1439. return LoadedSLocEntryTable[Index];
  1440. return loadSLocEntry(Index, Invalid);
  1441. }
  1442. const SrcMgr::SLocEntry &getSLocEntry(FileID FID,
  1443. bool *Invalid = nullptr) const {
  1444. if (FID.ID == 0 || FID.ID == -1) {
  1445. if (Invalid) *Invalid = true;
  1446. return LocalSLocEntryTable[0];
  1447. }
  1448. return getSLocEntryByID(FID.ID, Invalid);
  1449. }
  1450. SourceLocation::UIntTy getNextLocalOffset() const { return NextLocalOffset; }
  1451. void setExternalSLocEntrySource(ExternalSLocEntrySource *Source) {
  1452. assert(LoadedSLocEntryTable.empty() &&
  1453. "Invalidating existing loaded entries");
  1454. ExternalSLocEntries = Source;
  1455. }
  1456. /// Allocate a number of loaded SLocEntries, which will be actually
  1457. /// loaded on demand from the external source.
  1458. ///
  1459. /// NumSLocEntries will be allocated, which occupy a total of TotalSize space
  1460. /// in the global source view. The lowest ID and the base offset of the
  1461. /// entries will be returned.
  1462. std::pair<int, SourceLocation::UIntTy>
  1463. AllocateLoadedSLocEntries(unsigned NumSLocEntries,
  1464. SourceLocation::UIntTy TotalSize);
  1465. /// Returns true if \p Loc came from a PCH/Module.
  1466. bool isLoadedSourceLocation(SourceLocation Loc) const {
  1467. return Loc.getOffset() >= CurrentLoadedOffset;
  1468. }
  1469. /// Returns true if \p Loc did not come from a PCH/Module.
  1470. bool isLocalSourceLocation(SourceLocation Loc) const {
  1471. return Loc.getOffset() < NextLocalOffset;
  1472. }
  1473. /// Returns true if \p FID came from a PCH/Module.
  1474. bool isLoadedFileID(FileID FID) const {
  1475. assert(FID.ID != -1 && "Using FileID sentinel value");
  1476. return FID.ID < 0;
  1477. }
  1478. /// Returns true if \p FID did not come from a PCH/Module.
  1479. bool isLocalFileID(FileID FID) const {
  1480. return !isLoadedFileID(FID);
  1481. }
  1482. /// Gets the location of the immediate macro caller, one level up the stack
  1483. /// toward the initial macro typed into the source.
  1484. SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const {
  1485. if (!Loc.isMacroID()) return Loc;
  1486. // When we have the location of (part of) an expanded parameter, its
  1487. // spelling location points to the argument as expanded in the macro call,
  1488. // and therefore is used to locate the macro caller.
  1489. if (isMacroArgExpansion(Loc))
  1490. return getImmediateSpellingLoc(Loc);
  1491. // Otherwise, the caller of the macro is located where this macro is
  1492. // expanded (while the spelling is part of the macro definition).
  1493. return getImmediateExpansionRange(Loc).getBegin();
  1494. }
  1495. /// \return Location of the top-level macro caller.
  1496. SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const;
  1497. private:
  1498. friend class ASTReader;
  1499. friend class ASTWriter;
  1500. llvm::MemoryBufferRef getFakeBufferForRecovery() const;
  1501. SrcMgr::ContentCache &getFakeContentCacheForRecovery() const;
  1502. const SrcMgr::SLocEntry &loadSLocEntry(unsigned Index, bool *Invalid) const;
  1503. const SrcMgr::SLocEntry *getSLocEntryOrNull(FileID FID) const {
  1504. bool Invalid = false;
  1505. const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
  1506. return Invalid ? nullptr : &Entry;
  1507. }
  1508. const SrcMgr::SLocEntry *getSLocEntryForFile(FileID FID) const {
  1509. if (auto *Entry = getSLocEntryOrNull(FID))
  1510. if (Entry->isFile())
  1511. return Entry;
  1512. return nullptr;
  1513. }
  1514. /// Get the entry with the given unwrapped FileID.
  1515. /// Invalid will not be modified for Local IDs.
  1516. const SrcMgr::SLocEntry &getSLocEntryByID(int ID,
  1517. bool *Invalid = nullptr) const {
  1518. assert(ID != -1 && "Using FileID sentinel value");
  1519. if (ID < 0)
  1520. return getLoadedSLocEntryByID(ID, Invalid);
  1521. return getLocalSLocEntry(static_cast<unsigned>(ID));
  1522. }
  1523. const SrcMgr::SLocEntry &
  1524. getLoadedSLocEntryByID(int ID, bool *Invalid = nullptr) const {
  1525. return getLoadedSLocEntry(static_cast<unsigned>(-ID - 2), Invalid);
  1526. }
  1527. /// Implements the common elements of storing an expansion info struct into
  1528. /// the SLocEntry table and producing a source location that refers to it.
  1529. SourceLocation
  1530. createExpansionLocImpl(const SrcMgr::ExpansionInfo &Expansion,
  1531. unsigned TokLength, int LoadedID = 0,
  1532. SourceLocation::UIntTy LoadedOffset = 0);
  1533. /// Return true if the specified FileID contains the
  1534. /// specified SourceLocation offset. This is a very hot method.
  1535. inline bool isOffsetInFileID(FileID FID,
  1536. SourceLocation::UIntTy SLocOffset) const {
  1537. const SrcMgr::SLocEntry &Entry = getSLocEntry(FID);
  1538. // If the entry is after the offset, it can't contain it.
  1539. if (SLocOffset < Entry.getOffset()) return false;
  1540. // If this is the very last entry then it does.
  1541. if (FID.ID == -2)
  1542. return true;
  1543. // If it is the last local entry, then it does if the location is local.
  1544. if (FID.ID+1 == static_cast<int>(LocalSLocEntryTable.size()))
  1545. return SLocOffset < NextLocalOffset;
  1546. // Otherwise, the entry after it has to not include it. This works for both
  1547. // local and loaded entries.
  1548. return SLocOffset < getSLocEntryByID(FID.ID+1).getOffset();
  1549. }
  1550. /// Returns the previous in-order FileID or an invalid FileID if there
  1551. /// is no previous one.
  1552. FileID getPreviousFileID(FileID FID) const;
  1553. /// Returns the next in-order FileID or an invalid FileID if there is
  1554. /// no next one.
  1555. FileID getNextFileID(FileID FID) const;
  1556. /// Create a new fileID for the specified ContentCache and
  1557. /// include position.
  1558. ///
  1559. /// This works regardless of whether the ContentCache corresponds to a
  1560. /// file or some other input source.
  1561. FileID createFileIDImpl(SrcMgr::ContentCache &File, StringRef Filename,
  1562. SourceLocation IncludePos,
  1563. SrcMgr::CharacteristicKind DirCharacter, int LoadedID,
  1564. SourceLocation::UIntTy LoadedOffset);
  1565. SrcMgr::ContentCache &getOrCreateContentCache(FileEntryRef SourceFile,
  1566. bool isSystemFile = false);
  1567. /// Create a new ContentCache for the specified memory buffer.
  1568. SrcMgr::ContentCache &
  1569. createMemBufferContentCache(std::unique_ptr<llvm::MemoryBuffer> Buf);
  1570. FileID getFileIDSlow(SourceLocation::UIntTy SLocOffset) const;
  1571. FileID getFileIDLocal(SourceLocation::UIntTy SLocOffset) const;
  1572. FileID getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const;
  1573. SourceLocation getExpansionLocSlowCase(SourceLocation Loc) const;
  1574. SourceLocation getSpellingLocSlowCase(SourceLocation Loc) const;
  1575. SourceLocation getFileLocSlowCase(SourceLocation Loc) const;
  1576. std::pair<FileID, unsigned>
  1577. getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry *E) const;
  1578. std::pair<FileID, unsigned>
  1579. getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
  1580. unsigned Offset) const;
  1581. void computeMacroArgsCache(MacroArgsMap &MacroArgsCache, FileID FID) const;
  1582. void associateFileChunkWithMacroArgExp(MacroArgsMap &MacroArgsCache,
  1583. FileID FID,
  1584. SourceLocation SpellLoc,
  1585. SourceLocation ExpansionLoc,
  1586. unsigned ExpansionLength) const;
  1587. };
  1588. /// Comparison function object.
  1589. template<typename T>
  1590. class BeforeThanCompare;
  1591. /// Compare two source locations.
  1592. template<>
  1593. class BeforeThanCompare<SourceLocation> {
  1594. SourceManager &SM;
  1595. public:
  1596. explicit BeforeThanCompare(SourceManager &SM) : SM(SM) {}
  1597. bool operator()(SourceLocation LHS, SourceLocation RHS) const {
  1598. return SM.isBeforeInTranslationUnit(LHS, RHS);
  1599. }
  1600. };
  1601. /// Compare two non-overlapping source ranges.
  1602. template<>
  1603. class BeforeThanCompare<SourceRange> {
  1604. SourceManager &SM;
  1605. public:
  1606. explicit BeforeThanCompare(SourceManager &SM) : SM(SM) {}
  1607. bool operator()(SourceRange LHS, SourceRange RHS) const {
  1608. return SM.isBeforeInTranslationUnit(LHS.getBegin(), RHS.getBegin());
  1609. }
  1610. };
  1611. /// SourceManager and necessary depdencies (e.g. VFS, FileManager) for a single
  1612. /// in-memorty file.
  1613. class SourceManagerForFile {
  1614. public:
  1615. /// Creates SourceManager and necessary depdencies (e.g. VFS, FileManager).
  1616. /// The main file in the SourceManager will be \p FileName with \p Content.
  1617. SourceManagerForFile(StringRef FileName, StringRef Content);
  1618. SourceManager &get() {
  1619. assert(SourceMgr);
  1620. return *SourceMgr;
  1621. }
  1622. private:
  1623. // The order of these fields are important - they should be in the same order
  1624. // as they are created in `createSourceManagerForFile` so that they can be
  1625. // deleted in the reverse order as they are created.
  1626. std::unique_ptr<FileManager> FileMgr;
  1627. std::unique_ptr<DiagnosticsEngine> Diagnostics;
  1628. std::unique_ptr<SourceManager> SourceMgr;
  1629. };
  1630. } // namespace clang
  1631. #endif // LLVM_CLANG_BASIC_SOURCEMANAGER_H
  1632. #ifdef __GNUC__
  1633. #pragma GCC diagnostic pop
  1634. #endif