ASTUnit.cpp 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678
  1. //===- ASTUnit.cpp - ASTUnit utility --------------------------------------===//
  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. // ASTUnit Implementation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Frontend/ASTUnit.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/CommentCommandTraits.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclBase.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclGroup.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclTemplate.h"
  23. #include "clang/AST/DeclarationName.h"
  24. #include "clang/AST/ExternalASTSource.h"
  25. #include "clang/AST/PrettyPrinter.h"
  26. #include "clang/AST/Type.h"
  27. #include "clang/AST/TypeOrdering.h"
  28. #include "clang/Basic/Diagnostic.h"
  29. #include "clang/Basic/FileManager.h"
  30. #include "clang/Basic/IdentifierTable.h"
  31. #include "clang/Basic/LLVM.h"
  32. #include "clang/Basic/LangOptions.h"
  33. #include "clang/Basic/MemoryBufferCache.h"
  34. #include "clang/Basic/Module.h"
  35. #include "clang/Basic/SourceLocation.h"
  36. #include "clang/Basic/SourceManager.h"
  37. #include "clang/Basic/TargetInfo.h"
  38. #include "clang/Basic/TargetOptions.h"
  39. #include "clang/Basic/VirtualFileSystem.h"
  40. #include "clang/Frontend/CompilerInstance.h"
  41. #include "clang/Frontend/CompilerInvocation.h"
  42. #include "clang/Frontend/FrontendAction.h"
  43. #include "clang/Frontend/FrontendActions.h"
  44. #include "clang/Frontend/FrontendDiagnostic.h"
  45. #include "clang/Frontend/FrontendOptions.h"
  46. #include "clang/Frontend/MultiplexConsumer.h"
  47. #include "clang/Frontend/PCHContainerOperations.h"
  48. #include "clang/Frontend/PrecompiledPreamble.h"
  49. #include "clang/Frontend/Utils.h"
  50. #include "clang/Lex/HeaderSearch.h"
  51. #include "clang/Lex/HeaderSearchOptions.h"
  52. #include "clang/Lex/Lexer.h"
  53. #include "clang/Lex/PPCallbacks.h"
  54. #include "clang/Lex/PreprocessingRecord.h"
  55. #include "clang/Lex/Preprocessor.h"
  56. #include "clang/Lex/PreprocessorOptions.h"
  57. #include "clang/Lex/Token.h"
  58. #include "clang/Sema/CodeCompleteConsumer.h"
  59. #include "clang/Sema/CodeCompleteOptions.h"
  60. #include "clang/Sema/Sema.h"
  61. #include "clang/Serialization/ASTBitCodes.h"
  62. #include "clang/Serialization/ASTReader.h"
  63. #include "clang/Serialization/ASTWriter.h"
  64. #include "clang/Serialization/ContinuousRangeMap.h"
  65. #include "clang/Serialization/Module.h"
  66. #include "llvm/ADT/ArrayRef.h"
  67. #include "llvm/ADT/DenseMap.h"
  68. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  69. #include "llvm/ADT/None.h"
  70. #include "llvm/ADT/Optional.h"
  71. #include "llvm/ADT/STLExtras.h"
  72. #include "llvm/ADT/SmallString.h"
  73. #include "llvm/ADT/SmallVector.h"
  74. #include "llvm/ADT/StringMap.h"
  75. #include "llvm/ADT/StringRef.h"
  76. #include "llvm/ADT/StringSet.h"
  77. #include "llvm/ADT/Twine.h"
  78. #include "llvm/ADT/iterator_range.h"
  79. #include "llvm/Bitcode/BitstreamWriter.h"
  80. #include "llvm/Support/Allocator.h"
  81. #include "llvm/Support/Casting.h"
  82. #include "llvm/Support/CrashRecoveryContext.h"
  83. #include "llvm/Support/DJB.h"
  84. #include "llvm/Support/ErrorHandling.h"
  85. #include "llvm/Support/ErrorOr.h"
  86. #include "llvm/Support/FileSystem.h"
  87. #include "llvm/Support/MemoryBuffer.h"
  88. #include "llvm/Support/Mutex.h"
  89. #include "llvm/Support/Timer.h"
  90. #include "llvm/Support/raw_ostream.h"
  91. #include <algorithm>
  92. #include <atomic>
  93. #include <cassert>
  94. #include <cstdint>
  95. #include <cstdio>
  96. #include <cstdlib>
  97. #include <memory>
  98. #include <string>
  99. #include <tuple>
  100. #include <utility>
  101. #include <vector>
  102. using namespace clang;
  103. using llvm::TimeRecord;
  104. namespace {
  105. class SimpleTimer {
  106. bool WantTiming;
  107. TimeRecord Start;
  108. std::string Output;
  109. public:
  110. explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
  111. if (WantTiming)
  112. Start = TimeRecord::getCurrentTime();
  113. }
  114. ~SimpleTimer() {
  115. if (WantTiming) {
  116. TimeRecord Elapsed = TimeRecord::getCurrentTime();
  117. Elapsed -= Start;
  118. llvm::errs() << Output << ':';
  119. Elapsed.print(Elapsed, llvm::errs());
  120. llvm::errs() << '\n';
  121. }
  122. }
  123. void setOutput(const Twine &Output) {
  124. if (WantTiming)
  125. this->Output = Output.str();
  126. }
  127. };
  128. } // namespace
  129. template <class T>
  130. static std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
  131. if (!Val)
  132. return nullptr;
  133. return std::move(*Val);
  134. }
  135. template <class T>
  136. static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
  137. if (!Val)
  138. return false;
  139. Output = std::move(*Val);
  140. return true;
  141. }
  142. /// Get a source buffer for \p MainFilePath, handling all file-to-file
  143. /// and file-to-buffer remappings inside \p Invocation.
  144. static std::unique_ptr<llvm::MemoryBuffer>
  145. getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
  146. vfs::FileSystem *VFS,
  147. StringRef FilePath) {
  148. const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
  149. // Try to determine if the main file has been remapped, either from the
  150. // command line (to another file) or directly through the compiler
  151. // invocation (to a memory buffer).
  152. llvm::MemoryBuffer *Buffer = nullptr;
  153. std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
  154. auto FileStatus = VFS->status(FilePath);
  155. if (FileStatus) {
  156. llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
  157. // Check whether there is a file-file remapping of the main file
  158. for (const auto &RF : PreprocessorOpts.RemappedFiles) {
  159. std::string MPath(RF.first);
  160. auto MPathStatus = VFS->status(MPath);
  161. if (MPathStatus) {
  162. llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
  163. if (MainFileID == MID) {
  164. // We found a remapping. Try to load the resulting, remapped source.
  165. BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
  166. if (!BufferOwner)
  167. return nullptr;
  168. }
  169. }
  170. }
  171. // Check whether there is a file-buffer remapping. It supercedes the
  172. // file-file remapping.
  173. for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
  174. std::string MPath(RB.first);
  175. auto MPathStatus = VFS->status(MPath);
  176. if (MPathStatus) {
  177. llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
  178. if (MainFileID == MID) {
  179. // We found a remapping.
  180. BufferOwner.reset();
  181. Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
  182. }
  183. }
  184. }
  185. }
  186. // If the main source file was not remapped, load it now.
  187. if (!Buffer && !BufferOwner) {
  188. BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath));
  189. if (!BufferOwner)
  190. return nullptr;
  191. }
  192. if (BufferOwner)
  193. return BufferOwner;
  194. if (!Buffer)
  195. return nullptr;
  196. return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
  197. }
  198. struct ASTUnit::ASTWriterData {
  199. SmallString<128> Buffer;
  200. llvm::BitstreamWriter Stream;
  201. ASTWriter Writer;
  202. ASTWriterData(MemoryBufferCache &PCMCache)
  203. : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
  204. };
  205. void ASTUnit::clearFileLevelDecls() {
  206. llvm::DeleteContainerSeconds(FileDecls);
  207. }
  208. /// After failing to build a precompiled preamble (due to
  209. /// errors in the source that occurs in the preamble), the number of
  210. /// reparses during which we'll skip even trying to precompile the
  211. /// preamble.
  212. const unsigned DefaultPreambleRebuildInterval = 5;
  213. /// Tracks the number of ASTUnit objects that are currently active.
  214. ///
  215. /// Used for debugging purposes only.
  216. static std::atomic<unsigned> ActiveASTUnitObjects;
  217. ASTUnit::ASTUnit(bool _MainFileIsAST)
  218. : MainFileIsAST(_MainFileIsAST), WantTiming(getenv("LIBCLANG_TIMING")),
  219. ShouldCacheCodeCompletionResults(false),
  220. IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
  221. UnsafeToFree(false) {
  222. if (getenv("LIBCLANG_OBJTRACKING"))
  223. fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
  224. }
  225. ASTUnit::~ASTUnit() {
  226. // If we loaded from an AST file, balance out the BeginSourceFile call.
  227. if (MainFileIsAST && getDiagnostics().getClient()) {
  228. getDiagnostics().getClient()->EndSourceFile();
  229. }
  230. clearFileLevelDecls();
  231. // Free the buffers associated with remapped files. We are required to
  232. // perform this operation here because we explicitly request that the
  233. // compiler instance *not* free these buffers for each invocation of the
  234. // parser.
  235. if (Invocation && OwnsRemappedFileBuffers) {
  236. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  237. for (const auto &RB : PPOpts.RemappedFileBuffers)
  238. delete RB.second;
  239. }
  240. ClearCachedCompletionResults();
  241. if (getenv("LIBCLANG_OBJTRACKING"))
  242. fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
  243. }
  244. void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
  245. this->PP = std::move(PP);
  246. }
  247. /// Determine the set of code-completion contexts in which this
  248. /// declaration should be shown.
  249. static unsigned getDeclShowContexts(const NamedDecl *ND,
  250. const LangOptions &LangOpts,
  251. bool &IsNestedNameSpecifier) {
  252. IsNestedNameSpecifier = false;
  253. if (isa<UsingShadowDecl>(ND))
  254. ND = ND->getUnderlyingDecl();
  255. if (!ND)
  256. return 0;
  257. uint64_t Contexts = 0;
  258. if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
  259. isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
  260. isa<TypeAliasTemplateDecl>(ND)) {
  261. // Types can appear in these contexts.
  262. if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
  263. Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
  264. | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
  265. | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
  266. | (1LL << CodeCompletionContext::CCC_Statement)
  267. | (1LL << CodeCompletionContext::CCC_Type)
  268. | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
  269. // In C++, types can appear in expressions contexts (for functional casts).
  270. if (LangOpts.CPlusPlus)
  271. Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
  272. // In Objective-C, message sends can send interfaces. In Objective-C++,
  273. // all types are available due to functional casts.
  274. if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
  275. Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
  276. // In Objective-C, you can only be a subclass of another Objective-C class
  277. if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
  278. // Objective-C interfaces can be used in a class property expression.
  279. if (ID->getDefinition())
  280. Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
  281. Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
  282. }
  283. // Deal with tag names.
  284. if (isa<EnumDecl>(ND)) {
  285. Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
  286. // Part of the nested-name-specifier in C++0x.
  287. if (LangOpts.CPlusPlus11)
  288. IsNestedNameSpecifier = true;
  289. } else if (const auto *Record = dyn_cast<RecordDecl>(ND)) {
  290. if (Record->isUnion())
  291. Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
  292. else
  293. Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
  294. if (LangOpts.CPlusPlus)
  295. IsNestedNameSpecifier = true;
  296. } else if (isa<ClassTemplateDecl>(ND))
  297. IsNestedNameSpecifier = true;
  298. } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
  299. // Values can appear in these contexts.
  300. Contexts = (1LL << CodeCompletionContext::CCC_Statement)
  301. | (1LL << CodeCompletionContext::CCC_Expression)
  302. | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
  303. | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
  304. } else if (isa<ObjCProtocolDecl>(ND)) {
  305. Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
  306. } else if (isa<ObjCCategoryDecl>(ND)) {
  307. Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
  308. } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
  309. Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
  310. // Part of the nested-name-specifier.
  311. IsNestedNameSpecifier = true;
  312. }
  313. return Contexts;
  314. }
  315. void ASTUnit::CacheCodeCompletionResults() {
  316. if (!TheSema)
  317. return;
  318. SimpleTimer Timer(WantTiming);
  319. Timer.setOutput("Cache global code completions for " + getMainFileName());
  320. // Clear out the previous results.
  321. ClearCachedCompletionResults();
  322. // Gather the set of global code completions.
  323. using Result = CodeCompletionResult;
  324. SmallVector<Result, 8> Results;
  325. CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
  326. CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
  327. TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
  328. CCTUInfo, Results);
  329. // Translate global code completions into cached completions.
  330. llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
  331. CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
  332. for (auto &R : Results) {
  333. switch (R.Kind) {
  334. case Result::RK_Declaration: {
  335. bool IsNestedNameSpecifier = false;
  336. CachedCodeCompletionResult CachedResult;
  337. CachedResult.Completion = R.CreateCodeCompletionString(
  338. *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
  339. IncludeBriefCommentsInCodeCompletion);
  340. CachedResult.ShowInContexts = getDeclShowContexts(
  341. R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
  342. CachedResult.Priority = R.Priority;
  343. CachedResult.Kind = R.CursorKind;
  344. CachedResult.Availability = R.Availability;
  345. // Keep track of the type of this completion in an ASTContext-agnostic
  346. // way.
  347. QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
  348. if (UsageType.isNull()) {
  349. CachedResult.TypeClass = STC_Void;
  350. CachedResult.Type = 0;
  351. } else {
  352. CanQualType CanUsageType
  353. = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
  354. CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
  355. // Determine whether we have already seen this type. If so, we save
  356. // ourselves the work of formatting the type string by using the
  357. // temporary, CanQualType-based hash table to find the associated value.
  358. unsigned &TypeValue = CompletionTypes[CanUsageType];
  359. if (TypeValue == 0) {
  360. TypeValue = CompletionTypes.size();
  361. CachedCompletionTypes[QualType(CanUsageType).getAsString()]
  362. = TypeValue;
  363. }
  364. CachedResult.Type = TypeValue;
  365. }
  366. CachedCompletionResults.push_back(CachedResult);
  367. /// Handle nested-name-specifiers in C++.
  368. if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
  369. !R.StartsNestedNameSpecifier) {
  370. // The contexts in which a nested-name-specifier can appear in C++.
  371. uint64_t NNSContexts
  372. = (1LL << CodeCompletionContext::CCC_TopLevel)
  373. | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
  374. | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
  375. | (1LL << CodeCompletionContext::CCC_Statement)
  376. | (1LL << CodeCompletionContext::CCC_Expression)
  377. | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
  378. | (1LL << CodeCompletionContext::CCC_EnumTag)
  379. | (1LL << CodeCompletionContext::CCC_UnionTag)
  380. | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
  381. | (1LL << CodeCompletionContext::CCC_Type)
  382. | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
  383. | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
  384. if (isa<NamespaceDecl>(R.Declaration) ||
  385. isa<NamespaceAliasDecl>(R.Declaration))
  386. NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
  387. if (unsigned RemainingContexts
  388. = NNSContexts & ~CachedResult.ShowInContexts) {
  389. // If there any contexts where this completion can be a
  390. // nested-name-specifier but isn't already an option, create a
  391. // nested-name-specifier completion.
  392. R.StartsNestedNameSpecifier = true;
  393. CachedResult.Completion = R.CreateCodeCompletionString(
  394. *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
  395. IncludeBriefCommentsInCodeCompletion);
  396. CachedResult.ShowInContexts = RemainingContexts;
  397. CachedResult.Priority = CCP_NestedNameSpecifier;
  398. CachedResult.TypeClass = STC_Void;
  399. CachedResult.Type = 0;
  400. CachedCompletionResults.push_back(CachedResult);
  401. }
  402. }
  403. break;
  404. }
  405. case Result::RK_Keyword:
  406. case Result::RK_Pattern:
  407. // Ignore keywords and patterns; we don't care, since they are so
  408. // easily regenerated.
  409. break;
  410. case Result::RK_Macro: {
  411. CachedCodeCompletionResult CachedResult;
  412. CachedResult.Completion = R.CreateCodeCompletionString(
  413. *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
  414. IncludeBriefCommentsInCodeCompletion);
  415. CachedResult.ShowInContexts
  416. = (1LL << CodeCompletionContext::CCC_TopLevel)
  417. | (1LL << CodeCompletionContext::CCC_ObjCInterface)
  418. | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
  419. | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
  420. | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
  421. | (1LL << CodeCompletionContext::CCC_Statement)
  422. | (1LL << CodeCompletionContext::CCC_Expression)
  423. | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
  424. | (1LL << CodeCompletionContext::CCC_MacroNameUse)
  425. | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
  426. | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
  427. | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
  428. CachedResult.Priority = R.Priority;
  429. CachedResult.Kind = R.CursorKind;
  430. CachedResult.Availability = R.Availability;
  431. CachedResult.TypeClass = STC_Void;
  432. CachedResult.Type = 0;
  433. CachedCompletionResults.push_back(CachedResult);
  434. break;
  435. }
  436. }
  437. }
  438. // Save the current top-level hash value.
  439. CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
  440. }
  441. void ASTUnit::ClearCachedCompletionResults() {
  442. CachedCompletionResults.clear();
  443. CachedCompletionTypes.clear();
  444. CachedCompletionAllocator = nullptr;
  445. }
  446. namespace {
  447. /// Gathers information from ASTReader that will be used to initialize
  448. /// a Preprocessor.
  449. class ASTInfoCollector : public ASTReaderListener {
  450. Preprocessor &PP;
  451. ASTContext *Context;
  452. HeaderSearchOptions &HSOpts;
  453. PreprocessorOptions &PPOpts;
  454. LangOptions &LangOpt;
  455. std::shared_ptr<TargetOptions> &TargetOpts;
  456. IntrusiveRefCntPtr<TargetInfo> &Target;
  457. unsigned &Counter;
  458. bool InitializedLanguage = false;
  459. public:
  460. ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
  461. HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
  462. LangOptions &LangOpt,
  463. std::shared_ptr<TargetOptions> &TargetOpts,
  464. IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
  465. : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
  466. LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
  467. Counter(Counter) {}
  468. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  469. bool AllowCompatibleDifferences) override {
  470. if (InitializedLanguage)
  471. return false;
  472. LangOpt = LangOpts;
  473. InitializedLanguage = true;
  474. updated();
  475. return false;
  476. }
  477. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  478. StringRef SpecificModuleCachePath,
  479. bool Complain) override {
  480. this->HSOpts = HSOpts;
  481. return false;
  482. }
  483. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
  484. std::string &SuggestedPredefines) override {
  485. this->PPOpts = PPOpts;
  486. return false;
  487. }
  488. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  489. bool AllowCompatibleDifferences) override {
  490. // If we've already initialized the target, don't do it again.
  491. if (Target)
  492. return false;
  493. this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
  494. Target =
  495. TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
  496. updated();
  497. return false;
  498. }
  499. void ReadCounter(const serialization::ModuleFile &M,
  500. unsigned Value) override {
  501. Counter = Value;
  502. }
  503. private:
  504. void updated() {
  505. if (!Target || !InitializedLanguage)
  506. return;
  507. // Inform the target of the language options.
  508. //
  509. // FIXME: We shouldn't need to do this, the target should be immutable once
  510. // created. This complexity should be lifted elsewhere.
  511. Target->adjust(LangOpt);
  512. // Initialize the preprocessor.
  513. PP.Initialize(*Target);
  514. if (!Context)
  515. return;
  516. // Initialize the ASTContext
  517. Context->InitBuiltinTypes(*Target);
  518. // Adjust printing policy based on language options.
  519. Context->setPrintingPolicy(PrintingPolicy(LangOpt));
  520. // We didn't have access to the comment options when the ASTContext was
  521. // constructed, so register them now.
  522. Context->getCommentCommandTraits().registerCommentOptions(
  523. LangOpt.CommentOpts);
  524. }
  525. };
  526. /// Diagnostic consumer that saves each diagnostic it is given.
  527. class StoredDiagnosticConsumer : public DiagnosticConsumer {
  528. SmallVectorImpl<StoredDiagnostic> *StoredDiags;
  529. SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
  530. const LangOptions *LangOpts = nullptr;
  531. SourceManager *SourceMgr = nullptr;
  532. public:
  533. StoredDiagnosticConsumer(
  534. SmallVectorImpl<StoredDiagnostic> *StoredDiags,
  535. SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
  536. : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags) {
  537. assert((StoredDiags || StandaloneDiags) &&
  538. "No output collections were passed to StoredDiagnosticConsumer.");
  539. }
  540. void BeginSourceFile(const LangOptions &LangOpts,
  541. const Preprocessor *PP = nullptr) override {
  542. this->LangOpts = &LangOpts;
  543. if (PP)
  544. SourceMgr = &PP->getSourceManager();
  545. }
  546. void HandleDiagnostic(DiagnosticsEngine::Level Level,
  547. const Diagnostic &Info) override;
  548. };
  549. /// RAII object that optionally captures diagnostics, if
  550. /// there is no diagnostic client to capture them already.
  551. class CaptureDroppedDiagnostics {
  552. DiagnosticsEngine &Diags;
  553. StoredDiagnosticConsumer Client;
  554. DiagnosticConsumer *PreviousClient = nullptr;
  555. std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
  556. public:
  557. CaptureDroppedDiagnostics(
  558. bool RequestCapture, DiagnosticsEngine &Diags,
  559. SmallVectorImpl<StoredDiagnostic> *StoredDiags,
  560. SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
  561. : Diags(Diags), Client(StoredDiags, StandaloneDiags) {
  562. if (RequestCapture || Diags.getClient() == nullptr) {
  563. OwningPreviousClient = Diags.takeClient();
  564. PreviousClient = Diags.getClient();
  565. Diags.setClient(&Client, false);
  566. }
  567. }
  568. ~CaptureDroppedDiagnostics() {
  569. if (Diags.getClient() == &Client)
  570. Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
  571. }
  572. };
  573. } // namespace
  574. static ASTUnit::StandaloneDiagnostic
  575. makeStandaloneDiagnostic(const LangOptions &LangOpts,
  576. const StoredDiagnostic &InDiag);
  577. void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
  578. const Diagnostic &Info) {
  579. // Default implementation (Warnings/errors count).
  580. DiagnosticConsumer::HandleDiagnostic(Level, Info);
  581. // Only record the diagnostic if it's part of the source manager we know
  582. // about. This effectively drops diagnostics from modules we're building.
  583. // FIXME: In the long run, ee don't want to drop source managers from modules.
  584. if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
  585. StoredDiagnostic *ResultDiag = nullptr;
  586. if (StoredDiags) {
  587. StoredDiags->emplace_back(Level, Info);
  588. ResultDiag = &StoredDiags->back();
  589. }
  590. if (StandaloneDiags) {
  591. llvm::Optional<StoredDiagnostic> StoredDiag = None;
  592. if (!ResultDiag) {
  593. StoredDiag.emplace(Level, Info);
  594. ResultDiag = StoredDiag.getPointer();
  595. }
  596. StandaloneDiags->push_back(
  597. makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
  598. }
  599. }
  600. }
  601. IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
  602. return Reader;
  603. }
  604. ASTMutationListener *ASTUnit::getASTMutationListener() {
  605. if (WriterData)
  606. return &WriterData->Writer;
  607. return nullptr;
  608. }
  609. ASTDeserializationListener *ASTUnit::getDeserializationListener() {
  610. if (WriterData)
  611. return &WriterData->Writer;
  612. return nullptr;
  613. }
  614. std::unique_ptr<llvm::MemoryBuffer>
  615. ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
  616. assert(FileMgr);
  617. auto Buffer = FileMgr->getBufferForFile(Filename);
  618. if (Buffer)
  619. return std::move(*Buffer);
  620. if (ErrorStr)
  621. *ErrorStr = Buffer.getError().message();
  622. return nullptr;
  623. }
  624. /// Configure the diagnostics object for use with ASTUnit.
  625. void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
  626. ASTUnit &AST, bool CaptureDiagnostics) {
  627. assert(Diags.get() && "no DiagnosticsEngine was provided");
  628. if (CaptureDiagnostics)
  629. Diags->setClient(new StoredDiagnosticConsumer(&AST.StoredDiagnostics, nullptr));
  630. }
  631. std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
  632. const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
  633. WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
  634. const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
  635. bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
  636. bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
  637. bool UserFilesAreVolatile) {
  638. std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
  639. // Recover resources if we crash before exiting this method.
  640. llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
  641. ASTUnitCleanup(AST.get());
  642. llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
  643. llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
  644. DiagCleanup(Diags.get());
  645. ConfigureDiags(Diags, *AST, CaptureDiagnostics);
  646. AST->LangOpts = std::make_shared<LangOptions>();
  647. AST->OnlyLocalDecls = OnlyLocalDecls;
  648. AST->CaptureDiagnostics = CaptureDiagnostics;
  649. AST->Diagnostics = Diags;
  650. IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
  651. AST->FileMgr = new FileManager(FileSystemOpts, VFS);
  652. AST->UserFilesAreVolatile = UserFilesAreVolatile;
  653. AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
  654. AST->getFileManager(),
  655. UserFilesAreVolatile);
  656. AST->PCMCache = new MemoryBufferCache;
  657. AST->HSOpts = std::make_shared<HeaderSearchOptions>();
  658. AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
  659. AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
  660. AST->getSourceManager(),
  661. AST->getDiagnostics(),
  662. AST->getLangOpts(),
  663. /*Target=*/nullptr));
  664. AST->PPOpts = std::make_shared<PreprocessorOptions>();
  665. for (const auto &RemappedFile : RemappedFiles)
  666. AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
  667. // Gather Info for preprocessor construction later on.
  668. HeaderSearch &HeaderInfo = *AST->HeaderInfo;
  669. unsigned Counter;
  670. AST->PP = std::make_shared<Preprocessor>(
  671. AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
  672. AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
  673. /*IILookup=*/nullptr,
  674. /*OwnsHeaderSearch=*/false);
  675. Preprocessor &PP = *AST->PP;
  676. if (ToLoad >= LoadASTOnly)
  677. AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
  678. PP.getIdentifierTable(), PP.getSelectorTable(),
  679. PP.getBuiltinInfo());
  680. bool disableValid = false;
  681. if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
  682. disableValid = true;
  683. AST->Reader = new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, {},
  684. /*isysroot=*/"",
  685. /*DisableValidation=*/disableValid,
  686. AllowPCHWithCompilerErrors);
  687. AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
  688. *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
  689. AST->TargetOpts, AST->Target, Counter));
  690. // Attach the AST reader to the AST context as an external AST
  691. // source, so that declarations will be deserialized from the
  692. // AST file as needed.
  693. // We need the external source to be set up before we read the AST, because
  694. // eagerly-deserialized declarations may use it.
  695. if (AST->Ctx)
  696. AST->Ctx->setExternalSource(AST->Reader);
  697. switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
  698. SourceLocation(), ASTReader::ARR_None)) {
  699. case ASTReader::Success:
  700. break;
  701. case ASTReader::Failure:
  702. case ASTReader::Missing:
  703. case ASTReader::OutOfDate:
  704. case ASTReader::VersionMismatch:
  705. case ASTReader::ConfigurationMismatch:
  706. case ASTReader::HadErrors:
  707. AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
  708. return nullptr;
  709. }
  710. AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
  711. PP.setCounterValue(Counter);
  712. // Create an AST consumer, even though it isn't used.
  713. if (ToLoad >= LoadASTOnly)
  714. AST->Consumer.reset(new ASTConsumer);
  715. // Create a semantic analysis object and tell the AST reader about it.
  716. if (ToLoad >= LoadEverything) {
  717. AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
  718. AST->TheSema->Initialize();
  719. AST->Reader->InitializeSema(*AST->TheSema);
  720. }
  721. // Tell the diagnostic client that we have started a source file.
  722. AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
  723. return AST;
  724. }
  725. /// Add the given macro to the hash of all top-level entities.
  726. static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
  727. Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash);
  728. }
  729. namespace {
  730. /// Preprocessor callback class that updates a hash value with the names
  731. /// of all macros that have been defined by the translation unit.
  732. class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
  733. unsigned &Hash;
  734. public:
  735. explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {}
  736. void MacroDefined(const Token &MacroNameTok,
  737. const MacroDirective *MD) override {
  738. AddDefinedMacroToHash(MacroNameTok, Hash);
  739. }
  740. };
  741. } // namespace
  742. /// Add the given declaration to the hash of all top-level entities.
  743. static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
  744. if (!D)
  745. return;
  746. DeclContext *DC = D->getDeclContext();
  747. if (!DC)
  748. return;
  749. if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
  750. return;
  751. if (const auto *ND = dyn_cast<NamedDecl>(D)) {
  752. if (const auto *EnumD = dyn_cast<EnumDecl>(D)) {
  753. // For an unscoped enum include the enumerators in the hash since they
  754. // enter the top-level namespace.
  755. if (!EnumD->isScoped()) {
  756. for (const auto *EI : EnumD->enumerators()) {
  757. if (EI->getIdentifier())
  758. Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
  759. }
  760. }
  761. }
  762. if (ND->getIdentifier())
  763. Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
  764. else if (DeclarationName Name = ND->getDeclName()) {
  765. std::string NameStr = Name.getAsString();
  766. Hash = llvm::djbHash(NameStr, Hash);
  767. }
  768. return;
  769. }
  770. if (const auto *ImportD = dyn_cast<ImportDecl>(D)) {
  771. if (const Module *Mod = ImportD->getImportedModule()) {
  772. std::string ModName = Mod->getFullModuleName();
  773. Hash = llvm::djbHash(ModName, Hash);
  774. }
  775. return;
  776. }
  777. }
  778. namespace {
  779. class TopLevelDeclTrackerConsumer : public ASTConsumer {
  780. ASTUnit &Unit;
  781. unsigned &Hash;
  782. public:
  783. TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
  784. : Unit(_Unit), Hash(Hash) {
  785. Hash = 0;
  786. }
  787. void handleTopLevelDecl(Decl *D) {
  788. if (!D)
  789. return;
  790. // FIXME: Currently ObjC method declarations are incorrectly being
  791. // reported as top-level declarations, even though their DeclContext
  792. // is the containing ObjC @interface/@implementation. This is a
  793. // fundamental problem in the parser right now.
  794. if (isa<ObjCMethodDecl>(D))
  795. return;
  796. AddTopLevelDeclarationToHash(D, Hash);
  797. Unit.addTopLevelDecl(D);
  798. handleFileLevelDecl(D);
  799. }
  800. void handleFileLevelDecl(Decl *D) {
  801. Unit.addFileLevelDecl(D);
  802. if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
  803. for (auto *I : NSD->decls())
  804. handleFileLevelDecl(I);
  805. }
  806. }
  807. bool HandleTopLevelDecl(DeclGroupRef D) override {
  808. for (auto *TopLevelDecl : D)
  809. handleTopLevelDecl(TopLevelDecl);
  810. return true;
  811. }
  812. // We're not interested in "interesting" decls.
  813. void HandleInterestingDecl(DeclGroupRef) override {}
  814. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
  815. for (auto *TopLevelDecl : D)
  816. handleTopLevelDecl(TopLevelDecl);
  817. }
  818. ASTMutationListener *GetASTMutationListener() override {
  819. return Unit.getASTMutationListener();
  820. }
  821. ASTDeserializationListener *GetASTDeserializationListener() override {
  822. return Unit.getDeserializationListener();
  823. }
  824. };
  825. class TopLevelDeclTrackerAction : public ASTFrontendAction {
  826. public:
  827. ASTUnit &Unit;
  828. std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
  829. StringRef InFile) override {
  830. CI.getPreprocessor().addPPCallbacks(
  831. llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
  832. Unit.getCurrentTopLevelHashValue()));
  833. return llvm::make_unique<TopLevelDeclTrackerConsumer>(
  834. Unit, Unit.getCurrentTopLevelHashValue());
  835. }
  836. public:
  837. TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
  838. bool hasCodeCompletionSupport() const override { return false; }
  839. TranslationUnitKind getTranslationUnitKind() override {
  840. return Unit.getTranslationUnitKind();
  841. }
  842. };
  843. class ASTUnitPreambleCallbacks : public PreambleCallbacks {
  844. public:
  845. unsigned getHash() const { return Hash; }
  846. std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
  847. std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
  848. return std::move(TopLevelDeclIDs);
  849. }
  850. void AfterPCHEmitted(ASTWriter &Writer) override {
  851. TopLevelDeclIDs.reserve(TopLevelDecls.size());
  852. for (const auto *D : TopLevelDecls) {
  853. // Invalid top-level decls may not have been serialized.
  854. if (D->isInvalidDecl())
  855. continue;
  856. TopLevelDeclIDs.push_back(Writer.getDeclID(D));
  857. }
  858. }
  859. void HandleTopLevelDecl(DeclGroupRef DG) override {
  860. for (auto *D : DG) {
  861. // FIXME: Currently ObjC method declarations are incorrectly being
  862. // reported as top-level declarations, even though their DeclContext
  863. // is the containing ObjC @interface/@implementation. This is a
  864. // fundamental problem in the parser right now.
  865. if (isa<ObjCMethodDecl>(D))
  866. continue;
  867. AddTopLevelDeclarationToHash(D, Hash);
  868. TopLevelDecls.push_back(D);
  869. }
  870. }
  871. std::unique_ptr<PPCallbacks> createPPCallbacks() override {
  872. return llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
  873. }
  874. private:
  875. unsigned Hash = 0;
  876. std::vector<Decl *> TopLevelDecls;
  877. std::vector<serialization::DeclID> TopLevelDeclIDs;
  878. llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
  879. };
  880. } // namespace
  881. static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
  882. return StoredDiag.getLocation().isValid();
  883. }
  884. static void
  885. checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
  886. // Get rid of stored diagnostics except the ones from the driver which do not
  887. // have a source location.
  888. StoredDiags.erase(
  889. std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
  890. StoredDiags.end());
  891. }
  892. static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
  893. StoredDiagnostics,
  894. SourceManager &SM) {
  895. // The stored diagnostic has the old source manager in it; update
  896. // the locations to refer into the new source manager. Since we've
  897. // been careful to make sure that the source manager's state
  898. // before and after are identical, so that we can reuse the source
  899. // location itself.
  900. for (auto &SD : StoredDiagnostics) {
  901. if (SD.getLocation().isValid()) {
  902. FullSourceLoc Loc(SD.getLocation(), SM);
  903. SD.setLocation(Loc);
  904. }
  905. }
  906. }
  907. /// Parse the source file into a translation unit using the given compiler
  908. /// invocation, replacing the current translation unit.
  909. ///
  910. /// \returns True if a failure occurred that causes the ASTUnit not to
  911. /// contain any translation-unit information, false otherwise.
  912. bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  913. std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
  914. IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
  915. if (!Invocation)
  916. return true;
  917. auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
  918. if (OverrideMainBuffer) {
  919. assert(Preamble &&
  920. "No preamble was built, but OverrideMainBuffer is not null");
  921. IntrusiveRefCntPtr<vfs::FileSystem> OldVFS = VFS;
  922. Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
  923. if (OldVFS != VFS && FileMgr) {
  924. assert(OldVFS == FileMgr->getVirtualFileSystem() &&
  925. "VFS passed to Parse and VFS in FileMgr are different");
  926. FileMgr = new FileManager(FileMgr->getFileSystemOpts(), VFS);
  927. }
  928. }
  929. // Create the compiler instance to use for building the AST.
  930. std::unique_ptr<CompilerInstance> Clang(
  931. new CompilerInstance(std::move(PCHContainerOps)));
  932. if (FileMgr && VFS) {
  933. assert(VFS == FileMgr->getVirtualFileSystem() &&
  934. "VFS passed to Parse and VFS in FileMgr are different");
  935. } else if (VFS) {
  936. Clang->setVirtualFileSystem(VFS);
  937. }
  938. // Recover resources if we crash before exiting this method.
  939. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
  940. CICleanup(Clang.get());
  941. Clang->setInvocation(CCInvocation);
  942. OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
  943. // Set up diagnostics, capturing any diagnostics that would
  944. // otherwise be dropped.
  945. Clang->setDiagnostics(&getDiagnostics());
  946. // Create the target instance.
  947. Clang->setTarget(TargetInfo::CreateTargetInfo(
  948. Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
  949. if (!Clang->hasTarget())
  950. return true;
  951. // Inform the target of the language options.
  952. //
  953. // FIXME: We shouldn't need to do this, the target should be immutable once
  954. // created. This complexity should be lifted elsewhere.
  955. Clang->getTarget().adjust(Clang->getLangOpts());
  956. assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
  957. "Invocation must have exactly one source file!");
  958. assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
  959. InputKind::Source &&
  960. "FIXME: AST inputs not yet supported here!");
  961. assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
  962. InputKind::LLVM_IR &&
  963. "IR inputs not support here!");
  964. // Configure the various subsystems.
  965. LangOpts = Clang->getInvocation().LangOpts;
  966. FileSystemOpts = Clang->getFileSystemOpts();
  967. if (!FileMgr) {
  968. Clang->createFileManager();
  969. FileMgr = &Clang->getFileManager();
  970. }
  971. ResetForParse();
  972. SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
  973. UserFilesAreVolatile);
  974. if (!OverrideMainBuffer) {
  975. checkAndRemoveNonDriverDiags(StoredDiagnostics);
  976. TopLevelDeclsInPreamble.clear();
  977. }
  978. // Create a file manager object to provide access to and cache the filesystem.
  979. Clang->setFileManager(&getFileManager());
  980. // Create the source manager.
  981. Clang->setSourceManager(&getSourceManager());
  982. // If the main file has been overridden due to the use of a preamble,
  983. // make that override happen and introduce the preamble.
  984. if (OverrideMainBuffer) {
  985. // The stored diagnostic has the old source manager in it; update
  986. // the locations to refer into the new source manager. Since we've
  987. // been careful to make sure that the source manager's state
  988. // before and after are identical, so that we can reuse the source
  989. // location itself.
  990. checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
  991. // Keep track of the override buffer;
  992. SavedMainFileBuffer = std::move(OverrideMainBuffer);
  993. }
  994. std::unique_ptr<TopLevelDeclTrackerAction> Act(
  995. new TopLevelDeclTrackerAction(*this));
  996. // Recover resources if we crash before exiting this method.
  997. llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
  998. ActCleanup(Act.get());
  999. if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
  1000. goto error;
  1001. if (SavedMainFileBuffer)
  1002. TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
  1003. PreambleDiagnostics, StoredDiagnostics);
  1004. else
  1005. PreambleSrcLocCache.clear();
  1006. if (!Act->Execute())
  1007. goto error;
  1008. transferASTDataFromCompilerInstance(*Clang);
  1009. Act->EndSourceFile();
  1010. FailedParseDiagnostics.clear();
  1011. return false;
  1012. error:
  1013. // Remove the overridden buffer we used for the preamble.
  1014. SavedMainFileBuffer = nullptr;
  1015. // Keep the ownership of the data in the ASTUnit because the client may
  1016. // want to see the diagnostics.
  1017. transferASTDataFromCompilerInstance(*Clang);
  1018. FailedParseDiagnostics.swap(StoredDiagnostics);
  1019. StoredDiagnostics.clear();
  1020. NumStoredDiagnosticsFromDriver = 0;
  1021. return true;
  1022. }
  1023. static std::pair<unsigned, unsigned>
  1024. makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
  1025. const LangOptions &LangOpts) {
  1026. CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
  1027. unsigned Offset = SM.getFileOffset(FileRange.getBegin());
  1028. unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
  1029. return std::make_pair(Offset, EndOffset);
  1030. }
  1031. static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
  1032. const LangOptions &LangOpts,
  1033. const FixItHint &InFix) {
  1034. ASTUnit::StandaloneFixIt OutFix;
  1035. OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
  1036. OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
  1037. LangOpts);
  1038. OutFix.CodeToInsert = InFix.CodeToInsert;
  1039. OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
  1040. return OutFix;
  1041. }
  1042. static ASTUnit::StandaloneDiagnostic
  1043. makeStandaloneDiagnostic(const LangOptions &LangOpts,
  1044. const StoredDiagnostic &InDiag) {
  1045. ASTUnit::StandaloneDiagnostic OutDiag;
  1046. OutDiag.ID = InDiag.getID();
  1047. OutDiag.Level = InDiag.getLevel();
  1048. OutDiag.Message = InDiag.getMessage();
  1049. OutDiag.LocOffset = 0;
  1050. if (InDiag.getLocation().isInvalid())
  1051. return OutDiag;
  1052. const SourceManager &SM = InDiag.getLocation().getManager();
  1053. SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
  1054. OutDiag.Filename = SM.getFilename(FileLoc);
  1055. if (OutDiag.Filename.empty())
  1056. return OutDiag;
  1057. OutDiag.LocOffset = SM.getFileOffset(FileLoc);
  1058. for (const auto &Range : InDiag.getRanges())
  1059. OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
  1060. for (const auto &FixIt : InDiag.getFixIts())
  1061. OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
  1062. return OutDiag;
  1063. }
  1064. /// Attempt to build or re-use a precompiled preamble when (re-)parsing
  1065. /// the source file.
  1066. ///
  1067. /// This routine will compute the preamble of the main source file. If a
  1068. /// non-trivial preamble is found, it will precompile that preamble into a
  1069. /// precompiled header so that the precompiled preamble can be used to reduce
  1070. /// reparsing time. If a precompiled preamble has already been constructed,
  1071. /// this routine will determine if it is still valid and, if so, avoid
  1072. /// rebuilding the precompiled preamble.
  1073. ///
  1074. /// \param AllowRebuild When true (the default), this routine is
  1075. /// allowed to rebuild the precompiled preamble if it is found to be
  1076. /// out-of-date.
  1077. ///
  1078. /// \param MaxLines When non-zero, the maximum number of lines that
  1079. /// can occur within the preamble.
  1080. ///
  1081. /// \returns If the precompiled preamble can be used, returns a newly-allocated
  1082. /// buffer that should be used in place of the main file when doing so.
  1083. /// Otherwise, returns a NULL pointer.
  1084. std::unique_ptr<llvm::MemoryBuffer>
  1085. ASTUnit::getMainBufferWithPrecompiledPreamble(
  1086. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1087. CompilerInvocation &PreambleInvocationIn,
  1088. IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
  1089. unsigned MaxLines) {
  1090. auto MainFilePath =
  1091. PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
  1092. std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
  1093. getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
  1094. MainFilePath);
  1095. if (!MainFileBuffer)
  1096. return nullptr;
  1097. PreambleBounds Bounds =
  1098. ComputePreambleBounds(*PreambleInvocationIn.getLangOpts(),
  1099. MainFileBuffer.get(), MaxLines);
  1100. if (!Bounds.Size)
  1101. return nullptr;
  1102. if (Preamble) {
  1103. if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
  1104. VFS.get())) {
  1105. // Okay! We can re-use the precompiled preamble.
  1106. // Set the state of the diagnostic object to mimic its state
  1107. // after parsing the preamble.
  1108. getDiagnostics().Reset();
  1109. ProcessWarningOptions(getDiagnostics(),
  1110. PreambleInvocationIn.getDiagnosticOpts());
  1111. getDiagnostics().setNumWarnings(NumWarningsInPreamble);
  1112. PreambleRebuildCounter = 1;
  1113. return MainFileBuffer;
  1114. } else {
  1115. Preamble.reset();
  1116. PreambleDiagnostics.clear();
  1117. TopLevelDeclsInPreamble.clear();
  1118. PreambleSrcLocCache.clear();
  1119. PreambleRebuildCounter = 1;
  1120. }
  1121. }
  1122. // If the preamble rebuild counter > 1, it's because we previously
  1123. // failed to build a preamble and we're not yet ready to try
  1124. // again. Decrement the counter and return a failure.
  1125. if (PreambleRebuildCounter > 1) {
  1126. --PreambleRebuildCounter;
  1127. return nullptr;
  1128. }
  1129. assert(!Preamble && "No Preamble should be stored at that point");
  1130. // If we aren't allowed to rebuild the precompiled preamble, just
  1131. // return now.
  1132. if (!AllowRebuild)
  1133. return nullptr;
  1134. SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
  1135. SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
  1136. ASTUnitPreambleCallbacks Callbacks;
  1137. {
  1138. llvm::Optional<CaptureDroppedDiagnostics> Capture;
  1139. if (CaptureDiagnostics)
  1140. Capture.emplace(/*RequestCapture=*/true, *Diagnostics, &NewPreambleDiags,
  1141. &NewPreambleDiagsStandalone);
  1142. // We did not previously compute a preamble, or it can't be reused anyway.
  1143. SimpleTimer PreambleTimer(WantTiming);
  1144. PreambleTimer.setOutput("Precompiling preamble");
  1145. const bool PreviousSkipFunctionBodies =
  1146. PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies;
  1147. if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble)
  1148. PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true;
  1149. llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
  1150. PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
  1151. PCHContainerOps, /*StoreInMemory=*/false, Callbacks);
  1152. PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies =
  1153. PreviousSkipFunctionBodies;
  1154. if (NewPreamble) {
  1155. Preamble = std::move(*NewPreamble);
  1156. PreambleRebuildCounter = 1;
  1157. } else {
  1158. switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
  1159. case BuildPreambleError::CouldntCreateTempFile:
  1160. case BuildPreambleError::PreambleIsEmpty:
  1161. // Try again next time.
  1162. PreambleRebuildCounter = 1;
  1163. return nullptr;
  1164. case BuildPreambleError::CouldntCreateTargetInfo:
  1165. case BuildPreambleError::BeginSourceFileFailed:
  1166. case BuildPreambleError::CouldntEmitPCH:
  1167. // These erros are more likely to repeat, retry after some period.
  1168. PreambleRebuildCounter = DefaultPreambleRebuildInterval;
  1169. return nullptr;
  1170. }
  1171. llvm_unreachable("unexpected BuildPreambleError");
  1172. }
  1173. }
  1174. assert(Preamble && "Preamble wasn't built");
  1175. TopLevelDecls.clear();
  1176. TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
  1177. PreambleTopLevelHashValue = Callbacks.getHash();
  1178. NumWarningsInPreamble = getDiagnostics().getNumWarnings();
  1179. checkAndRemoveNonDriverDiags(NewPreambleDiags);
  1180. StoredDiagnostics = std::move(NewPreambleDiags);
  1181. PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
  1182. // If the hash of top-level entities differs from the hash of the top-level
  1183. // entities the last time we rebuilt the preamble, clear out the completion
  1184. // cache.
  1185. if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
  1186. CompletionCacheTopLevelHashValue = 0;
  1187. PreambleTopLevelHashValue = CurrentTopLevelHashValue;
  1188. }
  1189. return MainFileBuffer;
  1190. }
  1191. void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
  1192. assert(Preamble && "Should only be called when preamble was built");
  1193. std::vector<Decl *> Resolved;
  1194. Resolved.reserve(TopLevelDeclsInPreamble.size());
  1195. ExternalASTSource &Source = *getASTContext().getExternalSource();
  1196. for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
  1197. // Resolve the declaration ID to an actual declaration, possibly
  1198. // deserializing the declaration in the process.
  1199. if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
  1200. Resolved.push_back(D);
  1201. }
  1202. TopLevelDeclsInPreamble.clear();
  1203. TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
  1204. }
  1205. void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
  1206. // Steal the created target, context, and preprocessor if they have been
  1207. // created.
  1208. assert(CI.hasInvocation() && "missing invocation");
  1209. LangOpts = CI.getInvocation().LangOpts;
  1210. TheSema = CI.takeSema();
  1211. Consumer = CI.takeASTConsumer();
  1212. if (CI.hasASTContext())
  1213. Ctx = &CI.getASTContext();
  1214. if (CI.hasPreprocessor())
  1215. PP = CI.getPreprocessorPtr();
  1216. CI.setSourceManager(nullptr);
  1217. CI.setFileManager(nullptr);
  1218. if (CI.hasTarget())
  1219. Target = &CI.getTarget();
  1220. Reader = CI.getModuleManager();
  1221. HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
  1222. }
  1223. StringRef ASTUnit::getMainFileName() const {
  1224. if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
  1225. const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
  1226. if (Input.isFile())
  1227. return Input.getFile();
  1228. else
  1229. return Input.getBuffer()->getBufferIdentifier();
  1230. }
  1231. if (SourceMgr) {
  1232. if (const FileEntry *
  1233. FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
  1234. return FE->getName();
  1235. }
  1236. return {};
  1237. }
  1238. StringRef ASTUnit::getASTFileName() const {
  1239. if (!isMainFileAST())
  1240. return {};
  1241. serialization::ModuleFile &
  1242. Mod = Reader->getModuleManager().getPrimaryModule();
  1243. return Mod.FileName;
  1244. }
  1245. std::unique_ptr<ASTUnit>
  1246. ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
  1247. IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
  1248. bool CaptureDiagnostics, bool UserFilesAreVolatile) {
  1249. std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
  1250. ConfigureDiags(Diags, *AST, CaptureDiagnostics);
  1251. IntrusiveRefCntPtr<vfs::FileSystem> VFS =
  1252. createVFSFromCompilerInvocation(*CI, *Diags);
  1253. AST->Diagnostics = Diags;
  1254. AST->FileSystemOpts = CI->getFileSystemOpts();
  1255. AST->Invocation = std::move(CI);
  1256. AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
  1257. AST->UserFilesAreVolatile = UserFilesAreVolatile;
  1258. AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
  1259. UserFilesAreVolatile);
  1260. AST->PCMCache = new MemoryBufferCache;
  1261. return AST;
  1262. }
  1263. ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
  1264. std::shared_ptr<CompilerInvocation> CI,
  1265. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1266. IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
  1267. ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
  1268. bool OnlyLocalDecls, bool CaptureDiagnostics,
  1269. unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
  1270. bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
  1271. std::unique_ptr<ASTUnit> *ErrAST) {
  1272. assert(CI && "A CompilerInvocation is required");
  1273. std::unique_ptr<ASTUnit> OwnAST;
  1274. ASTUnit *AST = Unit;
  1275. if (!AST) {
  1276. // Create the AST unit.
  1277. OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
  1278. AST = OwnAST.get();
  1279. if (!AST)
  1280. return nullptr;
  1281. }
  1282. if (!ResourceFilesPath.empty()) {
  1283. // Override the resources path.
  1284. CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
  1285. }
  1286. AST->OnlyLocalDecls = OnlyLocalDecls;
  1287. AST->CaptureDiagnostics = CaptureDiagnostics;
  1288. if (PrecompilePreambleAfterNParses > 0)
  1289. AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
  1290. AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
  1291. AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
  1292. AST->IncludeBriefCommentsInCodeCompletion
  1293. = IncludeBriefCommentsInCodeCompletion;
  1294. // Recover resources if we crash before exiting this method.
  1295. llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
  1296. ASTUnitCleanup(OwnAST.get());
  1297. llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
  1298. llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
  1299. DiagCleanup(Diags.get());
  1300. // We'll manage file buffers ourselves.
  1301. CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
  1302. CI->getFrontendOpts().DisableFree = false;
  1303. ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
  1304. // Create the compiler instance to use for building the AST.
  1305. std::unique_ptr<CompilerInstance> Clang(
  1306. new CompilerInstance(std::move(PCHContainerOps)));
  1307. // Recover resources if we crash before exiting this method.
  1308. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
  1309. CICleanup(Clang.get());
  1310. Clang->setInvocation(std::move(CI));
  1311. AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
  1312. // Set up diagnostics, capturing any diagnostics that would
  1313. // otherwise be dropped.
  1314. Clang->setDiagnostics(&AST->getDiagnostics());
  1315. // Create the target instance.
  1316. Clang->setTarget(TargetInfo::CreateTargetInfo(
  1317. Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
  1318. if (!Clang->hasTarget())
  1319. return nullptr;
  1320. // Inform the target of the language options.
  1321. //
  1322. // FIXME: We shouldn't need to do this, the target should be immutable once
  1323. // created. This complexity should be lifted elsewhere.
  1324. Clang->getTarget().adjust(Clang->getLangOpts());
  1325. assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
  1326. "Invocation must have exactly one source file!");
  1327. assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
  1328. InputKind::Source &&
  1329. "FIXME: AST inputs not yet supported here!");
  1330. assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
  1331. InputKind::LLVM_IR &&
  1332. "IR inputs not support here!");
  1333. // Configure the various subsystems.
  1334. AST->TheSema.reset();
  1335. AST->Ctx = nullptr;
  1336. AST->PP = nullptr;
  1337. AST->Reader = nullptr;
  1338. // Create a file manager object to provide access to and cache the filesystem.
  1339. Clang->setFileManager(&AST->getFileManager());
  1340. // Create the source manager.
  1341. Clang->setSourceManager(&AST->getSourceManager());
  1342. FrontendAction *Act = Action;
  1343. std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
  1344. if (!Act) {
  1345. TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
  1346. Act = TrackerAct.get();
  1347. }
  1348. // Recover resources if we crash before exiting this method.
  1349. llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
  1350. ActCleanup(TrackerAct.get());
  1351. if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
  1352. AST->transferASTDataFromCompilerInstance(*Clang);
  1353. if (OwnAST && ErrAST)
  1354. ErrAST->swap(OwnAST);
  1355. return nullptr;
  1356. }
  1357. if (Persistent && !TrackerAct) {
  1358. Clang->getPreprocessor().addPPCallbacks(
  1359. llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
  1360. AST->getCurrentTopLevelHashValue()));
  1361. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  1362. if (Clang->hasASTConsumer())
  1363. Consumers.push_back(Clang->takeASTConsumer());
  1364. Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
  1365. *AST, AST->getCurrentTopLevelHashValue()));
  1366. Clang->setASTConsumer(
  1367. llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
  1368. }
  1369. if (!Act->Execute()) {
  1370. AST->transferASTDataFromCompilerInstance(*Clang);
  1371. if (OwnAST && ErrAST)
  1372. ErrAST->swap(OwnAST);
  1373. return nullptr;
  1374. }
  1375. // Steal the created target, context, and preprocessor.
  1376. AST->transferASTDataFromCompilerInstance(*Clang);
  1377. Act->EndSourceFile();
  1378. if (OwnAST)
  1379. return OwnAST.release();
  1380. else
  1381. return AST;
  1382. }
  1383. bool ASTUnit::LoadFromCompilerInvocation(
  1384. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1385. unsigned PrecompilePreambleAfterNParses,
  1386. IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
  1387. if (!Invocation)
  1388. return true;
  1389. assert(VFS && "VFS is null");
  1390. // We'll manage file buffers ourselves.
  1391. Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
  1392. Invocation->getFrontendOpts().DisableFree = false;
  1393. getDiagnostics().Reset();
  1394. ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
  1395. std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
  1396. if (PrecompilePreambleAfterNParses > 0) {
  1397. PreambleRebuildCounter = PrecompilePreambleAfterNParses;
  1398. OverrideMainBuffer =
  1399. getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
  1400. getDiagnostics().Reset();
  1401. ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
  1402. }
  1403. SimpleTimer ParsingTimer(WantTiming);
  1404. ParsingTimer.setOutput("Parsing " + getMainFileName());
  1405. // Recover resources if we crash before exiting this method.
  1406. llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
  1407. MemBufferCleanup(OverrideMainBuffer.get());
  1408. return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
  1409. }
  1410. std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
  1411. std::shared_ptr<CompilerInvocation> CI,
  1412. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1413. IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
  1414. bool OnlyLocalDecls, bool CaptureDiagnostics,
  1415. unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
  1416. bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
  1417. bool UserFilesAreVolatile) {
  1418. // Create the AST unit.
  1419. std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
  1420. ConfigureDiags(Diags, *AST, CaptureDiagnostics);
  1421. AST->Diagnostics = Diags;
  1422. AST->OnlyLocalDecls = OnlyLocalDecls;
  1423. AST->CaptureDiagnostics = CaptureDiagnostics;
  1424. AST->TUKind = TUKind;
  1425. AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
  1426. AST->IncludeBriefCommentsInCodeCompletion
  1427. = IncludeBriefCommentsInCodeCompletion;
  1428. AST->Invocation = std::move(CI);
  1429. AST->FileSystemOpts = FileMgr->getFileSystemOpts();
  1430. AST->FileMgr = FileMgr;
  1431. AST->UserFilesAreVolatile = UserFilesAreVolatile;
  1432. // Recover resources if we crash before exiting this method.
  1433. llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
  1434. ASTUnitCleanup(AST.get());
  1435. llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
  1436. llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
  1437. DiagCleanup(Diags.get());
  1438. if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
  1439. PrecompilePreambleAfterNParses,
  1440. AST->FileMgr->getVirtualFileSystem()))
  1441. return nullptr;
  1442. return AST;
  1443. }
  1444. ASTUnit *ASTUnit::LoadFromCommandLine(
  1445. const char **ArgBegin, const char **ArgEnd,
  1446. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1447. IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
  1448. bool OnlyLocalDecls, bool CaptureDiagnostics,
  1449. ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
  1450. unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
  1451. bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
  1452. bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
  1453. bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
  1454. llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
  1455. IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
  1456. assert(Diags.get() && "no DiagnosticsEngine was provided");
  1457. SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
  1458. std::shared_ptr<CompilerInvocation> CI;
  1459. {
  1460. CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
  1461. &StoredDiagnostics, nullptr);
  1462. CI = createInvocationFromCommandLine(
  1463. llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
  1464. if (!CI)
  1465. return nullptr;
  1466. }
  1467. // Override any files that need remapping
  1468. for (const auto &RemappedFile : RemappedFiles) {
  1469. CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
  1470. RemappedFile.second);
  1471. }
  1472. PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
  1473. PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
  1474. PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
  1475. PPOpts.SingleFileParseMode = SingleFileParse;
  1476. // Override the resources path.
  1477. CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
  1478. CI->getFrontendOpts().SkipFunctionBodies =
  1479. SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile;
  1480. if (ModuleFormat)
  1481. CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
  1482. // Create the AST unit.
  1483. std::unique_ptr<ASTUnit> AST;
  1484. AST.reset(new ASTUnit(false));
  1485. AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
  1486. AST->StoredDiagnostics.swap(StoredDiagnostics);
  1487. ConfigureDiags(Diags, *AST, CaptureDiagnostics);
  1488. AST->Diagnostics = Diags;
  1489. AST->FileSystemOpts = CI->getFileSystemOpts();
  1490. if (!VFS)
  1491. VFS = vfs::getRealFileSystem();
  1492. VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
  1493. AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
  1494. AST->PCMCache = new MemoryBufferCache;
  1495. AST->OnlyLocalDecls = OnlyLocalDecls;
  1496. AST->CaptureDiagnostics = CaptureDiagnostics;
  1497. AST->TUKind = TUKind;
  1498. AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
  1499. AST->IncludeBriefCommentsInCodeCompletion
  1500. = IncludeBriefCommentsInCodeCompletion;
  1501. AST->UserFilesAreVolatile = UserFilesAreVolatile;
  1502. AST->Invocation = CI;
  1503. AST->SkipFunctionBodies = SkipFunctionBodies;
  1504. if (ForSerialization)
  1505. AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
  1506. // Zero out now to ease cleanup during crash recovery.
  1507. CI = nullptr;
  1508. Diags = nullptr;
  1509. // Recover resources if we crash before exiting this method.
  1510. llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
  1511. ASTUnitCleanup(AST.get());
  1512. if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
  1513. PrecompilePreambleAfterNParses,
  1514. VFS)) {
  1515. // Some error occurred, if caller wants to examine diagnostics, pass it the
  1516. // ASTUnit.
  1517. if (ErrAST) {
  1518. AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
  1519. ErrAST->swap(AST);
  1520. }
  1521. return nullptr;
  1522. }
  1523. return AST.release();
  1524. }
  1525. bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1526. ArrayRef<RemappedFile> RemappedFiles,
  1527. IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
  1528. if (!Invocation)
  1529. return true;
  1530. if (!VFS) {
  1531. assert(FileMgr && "FileMgr is null on Reparse call");
  1532. VFS = FileMgr->getVirtualFileSystem();
  1533. }
  1534. clearFileLevelDecls();
  1535. SimpleTimer ParsingTimer(WantTiming);
  1536. ParsingTimer.setOutput("Reparsing " + getMainFileName());
  1537. // Remap files.
  1538. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  1539. for (const auto &RB : PPOpts.RemappedFileBuffers)
  1540. delete RB.second;
  1541. Invocation->getPreprocessorOpts().clearRemappedFiles();
  1542. for (const auto &RemappedFile : RemappedFiles) {
  1543. Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
  1544. RemappedFile.second);
  1545. }
  1546. // If we have a preamble file lying around, or if we might try to
  1547. // build a precompiled preamble, do so now.
  1548. std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
  1549. if (Preamble || PreambleRebuildCounter > 0)
  1550. OverrideMainBuffer =
  1551. getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
  1552. // Clear out the diagnostics state.
  1553. FileMgr.reset();
  1554. getDiagnostics().Reset();
  1555. ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
  1556. if (OverrideMainBuffer)
  1557. getDiagnostics().setNumWarnings(NumWarningsInPreamble);
  1558. // Parse the sources
  1559. bool Result =
  1560. Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
  1561. // If we're caching global code-completion results, and the top-level
  1562. // declarations have changed, clear out the code-completion cache.
  1563. if (!Result && ShouldCacheCodeCompletionResults &&
  1564. CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
  1565. CacheCodeCompletionResults();
  1566. // We now need to clear out the completion info related to this translation
  1567. // unit; it'll be recreated if necessary.
  1568. CCTUInfo.reset();
  1569. return Result;
  1570. }
  1571. void ASTUnit::ResetForParse() {
  1572. SavedMainFileBuffer.reset();
  1573. SourceMgr.reset();
  1574. TheSema.reset();
  1575. Ctx.reset();
  1576. PP.reset();
  1577. Reader.reset();
  1578. TopLevelDecls.clear();
  1579. clearFileLevelDecls();
  1580. }
  1581. //----------------------------------------------------------------------------//
  1582. // Code completion
  1583. //----------------------------------------------------------------------------//
  1584. namespace {
  1585. /// Code completion consumer that combines the cached code-completion
  1586. /// results from an ASTUnit with the code-completion results provided to it,
  1587. /// then passes the result on to
  1588. class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
  1589. uint64_t NormalContexts;
  1590. ASTUnit &AST;
  1591. CodeCompleteConsumer &Next;
  1592. public:
  1593. AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
  1594. const CodeCompleteOptions &CodeCompleteOpts)
  1595. : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
  1596. AST(AST), Next(Next) {
  1597. // Compute the set of contexts in which we will look when we don't have
  1598. // any information about the specific context.
  1599. NormalContexts
  1600. = (1LL << CodeCompletionContext::CCC_TopLevel)
  1601. | (1LL << CodeCompletionContext::CCC_ObjCInterface)
  1602. | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
  1603. | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
  1604. | (1LL << CodeCompletionContext::CCC_Statement)
  1605. | (1LL << CodeCompletionContext::CCC_Expression)
  1606. | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
  1607. | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
  1608. | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
  1609. | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
  1610. | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
  1611. | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
  1612. | (1LL << CodeCompletionContext::CCC_Recovery);
  1613. if (AST.getASTContext().getLangOpts().CPlusPlus)
  1614. NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
  1615. | (1LL << CodeCompletionContext::CCC_UnionTag)
  1616. | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
  1617. }
  1618. void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
  1619. CodeCompletionResult *Results,
  1620. unsigned NumResults) override;
  1621. void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
  1622. OverloadCandidate *Candidates,
  1623. unsigned NumCandidates) override {
  1624. Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
  1625. }
  1626. CodeCompletionAllocator &getAllocator() override {
  1627. return Next.getAllocator();
  1628. }
  1629. CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
  1630. return Next.getCodeCompletionTUInfo();
  1631. }
  1632. };
  1633. } // namespace
  1634. /// Helper function that computes which global names are hidden by the
  1635. /// local code-completion results.
  1636. static void CalculateHiddenNames(const CodeCompletionContext &Context,
  1637. CodeCompletionResult *Results,
  1638. unsigned NumResults,
  1639. ASTContext &Ctx,
  1640. llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
  1641. bool OnlyTagNames = false;
  1642. switch (Context.getKind()) {
  1643. case CodeCompletionContext::CCC_Recovery:
  1644. case CodeCompletionContext::CCC_TopLevel:
  1645. case CodeCompletionContext::CCC_ObjCInterface:
  1646. case CodeCompletionContext::CCC_ObjCImplementation:
  1647. case CodeCompletionContext::CCC_ObjCIvarList:
  1648. case CodeCompletionContext::CCC_ClassStructUnion:
  1649. case CodeCompletionContext::CCC_Statement:
  1650. case CodeCompletionContext::CCC_Expression:
  1651. case CodeCompletionContext::CCC_ObjCMessageReceiver:
  1652. case CodeCompletionContext::CCC_DotMemberAccess:
  1653. case CodeCompletionContext::CCC_ArrowMemberAccess:
  1654. case CodeCompletionContext::CCC_ObjCPropertyAccess:
  1655. case CodeCompletionContext::CCC_Namespace:
  1656. case CodeCompletionContext::CCC_Type:
  1657. case CodeCompletionContext::CCC_Name:
  1658. case CodeCompletionContext::CCC_PotentiallyQualifiedName:
  1659. case CodeCompletionContext::CCC_ParenthesizedExpression:
  1660. case CodeCompletionContext::CCC_ObjCInterfaceName:
  1661. break;
  1662. case CodeCompletionContext::CCC_EnumTag:
  1663. case CodeCompletionContext::CCC_UnionTag:
  1664. case CodeCompletionContext::CCC_ClassOrStructTag:
  1665. OnlyTagNames = true;
  1666. break;
  1667. case CodeCompletionContext::CCC_ObjCProtocolName:
  1668. case CodeCompletionContext::CCC_MacroName:
  1669. case CodeCompletionContext::CCC_MacroNameUse:
  1670. case CodeCompletionContext::CCC_PreprocessorExpression:
  1671. case CodeCompletionContext::CCC_PreprocessorDirective:
  1672. case CodeCompletionContext::CCC_NaturalLanguage:
  1673. case CodeCompletionContext::CCC_SelectorName:
  1674. case CodeCompletionContext::CCC_TypeQualifiers:
  1675. case CodeCompletionContext::CCC_Other:
  1676. case CodeCompletionContext::CCC_OtherWithMacros:
  1677. case CodeCompletionContext::CCC_ObjCInstanceMessage:
  1678. case CodeCompletionContext::CCC_ObjCClassMessage:
  1679. case CodeCompletionContext::CCC_ObjCCategoryName:
  1680. // We're looking for nothing, or we're looking for names that cannot
  1681. // be hidden.
  1682. return;
  1683. }
  1684. using Result = CodeCompletionResult;
  1685. for (unsigned I = 0; I != NumResults; ++I) {
  1686. if (Results[I].Kind != Result::RK_Declaration)
  1687. continue;
  1688. unsigned IDNS
  1689. = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
  1690. bool Hiding = false;
  1691. if (OnlyTagNames)
  1692. Hiding = (IDNS & Decl::IDNS_Tag);
  1693. else {
  1694. unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
  1695. Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
  1696. Decl::IDNS_NonMemberOperator);
  1697. if (Ctx.getLangOpts().CPlusPlus)
  1698. HiddenIDNS |= Decl::IDNS_Tag;
  1699. Hiding = (IDNS & HiddenIDNS);
  1700. }
  1701. if (!Hiding)
  1702. continue;
  1703. DeclarationName Name = Results[I].Declaration->getDeclName();
  1704. if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
  1705. HiddenNames.insert(Identifier->getName());
  1706. else
  1707. HiddenNames.insert(Name.getAsString());
  1708. }
  1709. }
  1710. void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
  1711. CodeCompletionContext Context,
  1712. CodeCompletionResult *Results,
  1713. unsigned NumResults) {
  1714. // Merge the results we were given with the results we cached.
  1715. bool AddedResult = false;
  1716. uint64_t InContexts =
  1717. Context.getKind() == CodeCompletionContext::CCC_Recovery
  1718. ? NormalContexts : (1LL << Context.getKind());
  1719. // Contains the set of names that are hidden by "local" completion results.
  1720. llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
  1721. using Result = CodeCompletionResult;
  1722. SmallVector<Result, 8> AllResults;
  1723. for (ASTUnit::cached_completion_iterator
  1724. C = AST.cached_completion_begin(),
  1725. CEnd = AST.cached_completion_end();
  1726. C != CEnd; ++C) {
  1727. // If the context we are in matches any of the contexts we are
  1728. // interested in, we'll add this result.
  1729. if ((C->ShowInContexts & InContexts) == 0)
  1730. continue;
  1731. // If we haven't added any results previously, do so now.
  1732. if (!AddedResult) {
  1733. CalculateHiddenNames(Context, Results, NumResults, S.Context,
  1734. HiddenNames);
  1735. AllResults.insert(AllResults.end(), Results, Results + NumResults);
  1736. AddedResult = true;
  1737. }
  1738. // Determine whether this global completion result is hidden by a local
  1739. // completion result. If so, skip it.
  1740. if (C->Kind != CXCursor_MacroDefinition &&
  1741. HiddenNames.count(C->Completion->getTypedText()))
  1742. continue;
  1743. // Adjust priority based on similar type classes.
  1744. unsigned Priority = C->Priority;
  1745. CodeCompletionString *Completion = C->Completion;
  1746. if (!Context.getPreferredType().isNull()) {
  1747. if (C->Kind == CXCursor_MacroDefinition) {
  1748. Priority = getMacroUsagePriority(C->Completion->getTypedText(),
  1749. S.getLangOpts(),
  1750. Context.getPreferredType()->isAnyPointerType());
  1751. } else if (C->Type) {
  1752. CanQualType Expected
  1753. = S.Context.getCanonicalType(
  1754. Context.getPreferredType().getUnqualifiedType());
  1755. SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
  1756. if (ExpectedSTC == C->TypeClass) {
  1757. // We know this type is similar; check for an exact match.
  1758. llvm::StringMap<unsigned> &CachedCompletionTypes
  1759. = AST.getCachedCompletionTypes();
  1760. llvm::StringMap<unsigned>::iterator Pos
  1761. = CachedCompletionTypes.find(QualType(Expected).getAsString());
  1762. if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
  1763. Priority /= CCF_ExactTypeMatch;
  1764. else
  1765. Priority /= CCF_SimilarTypeMatch;
  1766. }
  1767. }
  1768. }
  1769. // Adjust the completion string, if required.
  1770. if (C->Kind == CXCursor_MacroDefinition &&
  1771. Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
  1772. // Create a new code-completion string that just contains the
  1773. // macro name, without its arguments.
  1774. CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
  1775. CCP_CodePattern, C->Availability);
  1776. Builder.AddTypedTextChunk(C->Completion->getTypedText());
  1777. Priority = CCP_CodePattern;
  1778. Completion = Builder.TakeString();
  1779. }
  1780. AllResults.push_back(Result(Completion, Priority, C->Kind,
  1781. C->Availability));
  1782. }
  1783. // If we did not add any cached completion results, just forward the
  1784. // results we were given to the next consumer.
  1785. if (!AddedResult) {
  1786. Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
  1787. return;
  1788. }
  1789. Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
  1790. AllResults.size());
  1791. }
  1792. void ASTUnit::CodeComplete(
  1793. StringRef File, unsigned Line, unsigned Column,
  1794. ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
  1795. bool IncludeCodePatterns, bool IncludeBriefComments,
  1796. CodeCompleteConsumer &Consumer,
  1797. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  1798. DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
  1799. FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
  1800. SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
  1801. if (!Invocation)
  1802. return;
  1803. SimpleTimer CompletionTimer(WantTiming);
  1804. CompletionTimer.setOutput("Code completion @ " + File + ":" +
  1805. Twine(Line) + ":" + Twine(Column));
  1806. auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
  1807. FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
  1808. CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
  1809. PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
  1810. CodeCompleteOpts.IncludeMacros = IncludeMacros &&
  1811. CachedCompletionResults.empty();
  1812. CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
  1813. CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
  1814. CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
  1815. CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
  1816. assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
  1817. FrontendOpts.CodeCompletionAt.FileName = File;
  1818. FrontendOpts.CodeCompletionAt.Line = Line;
  1819. FrontendOpts.CodeCompletionAt.Column = Column;
  1820. // Set the language options appropriately.
  1821. LangOpts = *CCInvocation->getLangOpts();
  1822. // Spell-checking and warnings are wasteful during code-completion.
  1823. LangOpts.SpellChecking = false;
  1824. CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
  1825. std::unique_ptr<CompilerInstance> Clang(
  1826. new CompilerInstance(PCHContainerOps));
  1827. // Recover resources if we crash before exiting this method.
  1828. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
  1829. CICleanup(Clang.get());
  1830. auto &Inv = *CCInvocation;
  1831. Clang->setInvocation(std::move(CCInvocation));
  1832. OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
  1833. // Set up diagnostics, capturing any diagnostics produced.
  1834. Clang->setDiagnostics(&Diag);
  1835. CaptureDroppedDiagnostics Capture(true,
  1836. Clang->getDiagnostics(),
  1837. &StoredDiagnostics, nullptr);
  1838. ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
  1839. // Create the target instance.
  1840. Clang->setTarget(TargetInfo::CreateTargetInfo(
  1841. Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
  1842. if (!Clang->hasTarget()) {
  1843. Clang->setInvocation(nullptr);
  1844. return;
  1845. }
  1846. // Inform the target of the language options.
  1847. //
  1848. // FIXME: We shouldn't need to do this, the target should be immutable once
  1849. // created. This complexity should be lifted elsewhere.
  1850. Clang->getTarget().adjust(Clang->getLangOpts());
  1851. assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
  1852. "Invocation must have exactly one source file!");
  1853. assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
  1854. InputKind::Source &&
  1855. "FIXME: AST inputs not yet supported here!");
  1856. assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
  1857. InputKind::LLVM_IR &&
  1858. "IR inputs not support here!");
  1859. // Use the source and file managers that we were given.
  1860. Clang->setFileManager(&FileMgr);
  1861. Clang->setSourceManager(&SourceMgr);
  1862. // Remap files.
  1863. PreprocessorOpts.clearRemappedFiles();
  1864. PreprocessorOpts.RetainRemappedFileBuffers = true;
  1865. for (const auto &RemappedFile : RemappedFiles) {
  1866. PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
  1867. OwnedBuffers.push_back(RemappedFile.second);
  1868. }
  1869. // Use the code completion consumer we were given, but adding any cached
  1870. // code-completion results.
  1871. AugmentedCodeCompleteConsumer *AugmentedConsumer
  1872. = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
  1873. Clang->setCodeCompletionConsumer(AugmentedConsumer);
  1874. // If we have a precompiled preamble, try to use it. We only allow
  1875. // the use of the precompiled preamble if we're if the completion
  1876. // point is within the main file, after the end of the precompiled
  1877. // preamble.
  1878. std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
  1879. if (Preamble) {
  1880. std::string CompleteFilePath(File);
  1881. auto VFS = FileMgr.getVirtualFileSystem();
  1882. auto CompleteFileStatus = VFS->status(CompleteFilePath);
  1883. if (CompleteFileStatus) {
  1884. llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
  1885. std::string MainPath(OriginalSourceFile);
  1886. auto MainStatus = VFS->status(MainPath);
  1887. if (MainStatus) {
  1888. llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
  1889. if (CompleteFileID == MainID && Line > 1)
  1890. OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
  1891. PCHContainerOps, Inv, VFS, false, Line - 1);
  1892. }
  1893. }
  1894. }
  1895. // If the main file has been overridden due to the use of a preamble,
  1896. // make that override happen and introduce the preamble.
  1897. if (OverrideMainBuffer) {
  1898. assert(Preamble &&
  1899. "No preamble was built, but OverrideMainBuffer is not null");
  1900. auto VFS = FileMgr.getVirtualFileSystem();
  1901. Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
  1902. OverrideMainBuffer.get());
  1903. // FIXME: there is no way to update VFS if it was changed by
  1904. // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
  1905. // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
  1906. // PCH files are always readable.
  1907. OwnedBuffers.push_back(OverrideMainBuffer.release());
  1908. } else {
  1909. PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
  1910. PreprocessorOpts.PrecompiledPreambleBytes.second = false;
  1911. }
  1912. // Disable the preprocessing record if modules are not enabled.
  1913. if (!Clang->getLangOpts().Modules)
  1914. PreprocessorOpts.DetailedRecord = false;
  1915. std::unique_ptr<SyntaxOnlyAction> Act;
  1916. Act.reset(new SyntaxOnlyAction);
  1917. if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
  1918. Act->Execute();
  1919. Act->EndSourceFile();
  1920. }
  1921. }
  1922. bool ASTUnit::Save(StringRef File) {
  1923. if (HadModuleLoaderFatalFailure)
  1924. return true;
  1925. // Write to a temporary file and later rename it to the actual file, to avoid
  1926. // possible race conditions.
  1927. SmallString<128> TempPath;
  1928. TempPath = File;
  1929. TempPath += "-%%%%%%%%";
  1930. int fd;
  1931. if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
  1932. return true;
  1933. // FIXME: Can we somehow regenerate the stat cache here, or do we need to
  1934. // unconditionally create a stat cache when we parse the file?
  1935. llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
  1936. serialize(Out);
  1937. Out.close();
  1938. if (Out.has_error()) {
  1939. Out.clear_error();
  1940. return true;
  1941. }
  1942. if (llvm::sys::fs::rename(TempPath, File)) {
  1943. llvm::sys::fs::remove(TempPath);
  1944. return true;
  1945. }
  1946. return false;
  1947. }
  1948. static bool serializeUnit(ASTWriter &Writer,
  1949. SmallVectorImpl<char> &Buffer,
  1950. Sema &S,
  1951. bool hasErrors,
  1952. raw_ostream &OS) {
  1953. Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
  1954. // Write the generated bitstream to "Out".
  1955. if (!Buffer.empty())
  1956. OS.write(Buffer.data(), Buffer.size());
  1957. return false;
  1958. }
  1959. bool ASTUnit::serialize(raw_ostream &OS) {
  1960. // For serialization we are lenient if the errors were only warn-as-error kind.
  1961. bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
  1962. if (WriterData)
  1963. return serializeUnit(WriterData->Writer, WriterData->Buffer,
  1964. getSema(), hasErrors, OS);
  1965. SmallString<128> Buffer;
  1966. llvm::BitstreamWriter Stream(Buffer);
  1967. MemoryBufferCache PCMCache;
  1968. ASTWriter Writer(Stream, Buffer, PCMCache, {});
  1969. return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
  1970. }
  1971. using SLocRemap = ContinuousRangeMap<unsigned, int, 2>;
  1972. void ASTUnit::TranslateStoredDiagnostics(
  1973. FileManager &FileMgr,
  1974. SourceManager &SrcMgr,
  1975. const SmallVectorImpl<StandaloneDiagnostic> &Diags,
  1976. SmallVectorImpl<StoredDiagnostic> &Out) {
  1977. // Map the standalone diagnostic into the new source manager. We also need to
  1978. // remap all the locations to the new view. This includes the diag location,
  1979. // any associated source ranges, and the source ranges of associated fix-its.
  1980. // FIXME: There should be a cleaner way to do this.
  1981. SmallVector<StoredDiagnostic, 4> Result;
  1982. Result.reserve(Diags.size());
  1983. for (const auto &SD : Diags) {
  1984. // Rebuild the StoredDiagnostic.
  1985. if (SD.Filename.empty())
  1986. continue;
  1987. const FileEntry *FE = FileMgr.getFile(SD.Filename);
  1988. if (!FE)
  1989. continue;
  1990. SourceLocation FileLoc;
  1991. auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
  1992. if (ItFileID == PreambleSrcLocCache.end()) {
  1993. FileID FID = SrcMgr.translateFile(FE);
  1994. FileLoc = SrcMgr.getLocForStartOfFile(FID);
  1995. PreambleSrcLocCache[SD.Filename] = FileLoc;
  1996. } else {
  1997. FileLoc = ItFileID->getValue();
  1998. }
  1999. if (FileLoc.isInvalid())
  2000. continue;
  2001. SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
  2002. FullSourceLoc Loc(L, SrcMgr);
  2003. SmallVector<CharSourceRange, 4> Ranges;
  2004. Ranges.reserve(SD.Ranges.size());
  2005. for (const auto &Range : SD.Ranges) {
  2006. SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
  2007. SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
  2008. Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
  2009. }
  2010. SmallVector<FixItHint, 2> FixIts;
  2011. FixIts.reserve(SD.FixIts.size());
  2012. for (const auto &FixIt : SD.FixIts) {
  2013. FixIts.push_back(FixItHint());
  2014. FixItHint &FH = FixIts.back();
  2015. FH.CodeToInsert = FixIt.CodeToInsert;
  2016. SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
  2017. SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
  2018. FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
  2019. }
  2020. Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
  2021. SD.Message, Loc, Ranges, FixIts));
  2022. }
  2023. Result.swap(Out);
  2024. }
  2025. void ASTUnit::addFileLevelDecl(Decl *D) {
  2026. assert(D);
  2027. // We only care about local declarations.
  2028. if (D->isFromASTFile())
  2029. return;
  2030. SourceManager &SM = *SourceMgr;
  2031. SourceLocation Loc = D->getLocation();
  2032. if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
  2033. return;
  2034. // We only keep track of the file-level declarations of each file.
  2035. if (!D->getLexicalDeclContext()->isFileContext())
  2036. return;
  2037. SourceLocation FileLoc = SM.getFileLoc(Loc);
  2038. assert(SM.isLocalSourceLocation(FileLoc));
  2039. FileID FID;
  2040. unsigned Offset;
  2041. std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
  2042. if (FID.isInvalid())
  2043. return;
  2044. LocDeclsTy *&Decls = FileDecls[FID];
  2045. if (!Decls)
  2046. Decls = new LocDeclsTy();
  2047. std::pair<unsigned, Decl *> LocDecl(Offset, D);
  2048. if (Decls->empty() || Decls->back().first <= Offset) {
  2049. Decls->push_back(LocDecl);
  2050. return;
  2051. }
  2052. LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
  2053. LocDecl, llvm::less_first());
  2054. Decls->insert(I, LocDecl);
  2055. }
  2056. void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
  2057. SmallVectorImpl<Decl *> &Decls) {
  2058. if (File.isInvalid())
  2059. return;
  2060. if (SourceMgr->isLoadedFileID(File)) {
  2061. assert(Ctx->getExternalSource() && "No external source!");
  2062. return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
  2063. Decls);
  2064. }
  2065. FileDeclsTy::iterator I = FileDecls.find(File);
  2066. if (I == FileDecls.end())
  2067. return;
  2068. LocDeclsTy &LocDecls = *I->second;
  2069. if (LocDecls.empty())
  2070. return;
  2071. LocDeclsTy::iterator BeginIt =
  2072. std::lower_bound(LocDecls.begin(), LocDecls.end(),
  2073. std::make_pair(Offset, (Decl *)nullptr),
  2074. llvm::less_first());
  2075. if (BeginIt != LocDecls.begin())
  2076. --BeginIt;
  2077. // If we are pointing at a top-level decl inside an objc container, we need
  2078. // to backtrack until we find it otherwise we will fail to report that the
  2079. // region overlaps with an objc container.
  2080. while (BeginIt != LocDecls.begin() &&
  2081. BeginIt->second->isTopLevelDeclInObjCContainer())
  2082. --BeginIt;
  2083. LocDeclsTy::iterator EndIt = std::upper_bound(
  2084. LocDecls.begin(), LocDecls.end(),
  2085. std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
  2086. if (EndIt != LocDecls.end())
  2087. ++EndIt;
  2088. for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
  2089. Decls.push_back(DIt->second);
  2090. }
  2091. SourceLocation ASTUnit::getLocation(const FileEntry *File,
  2092. unsigned Line, unsigned Col) const {
  2093. const SourceManager &SM = getSourceManager();
  2094. SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
  2095. return SM.getMacroArgExpandedLocation(Loc);
  2096. }
  2097. SourceLocation ASTUnit::getLocation(const FileEntry *File,
  2098. unsigned Offset) const {
  2099. const SourceManager &SM = getSourceManager();
  2100. SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
  2101. return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
  2102. }
  2103. /// If \arg Loc is a loaded location from the preamble, returns
  2104. /// the corresponding local location of the main file, otherwise it returns
  2105. /// \arg Loc.
  2106. SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
  2107. FileID PreambleID;
  2108. if (SourceMgr)
  2109. PreambleID = SourceMgr->getPreambleFileID();
  2110. if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
  2111. return Loc;
  2112. unsigned Offs;
  2113. if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
  2114. SourceLocation FileLoc
  2115. = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
  2116. return FileLoc.getLocWithOffset(Offs);
  2117. }
  2118. return Loc;
  2119. }
  2120. /// If \arg Loc is a local location of the main file but inside the
  2121. /// preamble chunk, returns the corresponding loaded location from the
  2122. /// preamble, otherwise it returns \arg Loc.
  2123. SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
  2124. FileID PreambleID;
  2125. if (SourceMgr)
  2126. PreambleID = SourceMgr->getPreambleFileID();
  2127. if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
  2128. return Loc;
  2129. unsigned Offs;
  2130. if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
  2131. Offs < Preamble->getBounds().Size) {
  2132. SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
  2133. return FileLoc.getLocWithOffset(Offs);
  2134. }
  2135. return Loc;
  2136. }
  2137. bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
  2138. FileID FID;
  2139. if (SourceMgr)
  2140. FID = SourceMgr->getPreambleFileID();
  2141. if (Loc.isInvalid() || FID.isInvalid())
  2142. return false;
  2143. return SourceMgr->isInFileID(Loc, FID);
  2144. }
  2145. bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
  2146. FileID FID;
  2147. if (SourceMgr)
  2148. FID = SourceMgr->getMainFileID();
  2149. if (Loc.isInvalid() || FID.isInvalid())
  2150. return false;
  2151. return SourceMgr->isInFileID(Loc, FID);
  2152. }
  2153. SourceLocation ASTUnit::getEndOfPreambleFileID() const {
  2154. FileID FID;
  2155. if (SourceMgr)
  2156. FID = SourceMgr->getPreambleFileID();
  2157. if (FID.isInvalid())
  2158. return {};
  2159. return SourceMgr->getLocForEndOfFile(FID);
  2160. }
  2161. SourceLocation ASTUnit::getStartOfMainFileID() const {
  2162. FileID FID;
  2163. if (SourceMgr)
  2164. FID = SourceMgr->getMainFileID();
  2165. if (FID.isInvalid())
  2166. return {};
  2167. return SourceMgr->getLocForStartOfFile(FID);
  2168. }
  2169. llvm::iterator_range<PreprocessingRecord::iterator>
  2170. ASTUnit::getLocalPreprocessingEntities() const {
  2171. if (isMainFileAST()) {
  2172. serialization::ModuleFile &
  2173. Mod = Reader->getModuleManager().getPrimaryModule();
  2174. return Reader->getModulePreprocessedEntities(Mod);
  2175. }
  2176. if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
  2177. return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
  2178. return llvm::make_range(PreprocessingRecord::iterator(),
  2179. PreprocessingRecord::iterator());
  2180. }
  2181. bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
  2182. if (isMainFileAST()) {
  2183. serialization::ModuleFile &
  2184. Mod = Reader->getModuleManager().getPrimaryModule();
  2185. for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
  2186. if (!Fn(context, D))
  2187. return false;
  2188. }
  2189. return true;
  2190. }
  2191. for (ASTUnit::top_level_iterator TL = top_level_begin(),
  2192. TLEnd = top_level_end();
  2193. TL != TLEnd; ++TL) {
  2194. if (!Fn(context, *TL))
  2195. return false;
  2196. }
  2197. return true;
  2198. }
  2199. const FileEntry *ASTUnit::getPCHFile() {
  2200. if (!Reader)
  2201. return nullptr;
  2202. serialization::ModuleFile *Mod = nullptr;
  2203. Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
  2204. switch (M.Kind) {
  2205. case serialization::MK_ImplicitModule:
  2206. case serialization::MK_ExplicitModule:
  2207. case serialization::MK_PrebuiltModule:
  2208. return true; // skip dependencies.
  2209. case serialization::MK_PCH:
  2210. Mod = &M;
  2211. return true; // found it.
  2212. case serialization::MK_Preamble:
  2213. return false; // look in dependencies.
  2214. case serialization::MK_MainFile:
  2215. return false; // look in dependencies.
  2216. }
  2217. return true;
  2218. });
  2219. if (Mod)
  2220. return Mod->File;
  2221. return nullptr;
  2222. }
  2223. bool ASTUnit::isModuleFile() const {
  2224. return isMainFileAST() && getLangOpts().isCompilingModule();
  2225. }
  2226. InputKind ASTUnit::getInputKind() const {
  2227. auto &LangOpts = getLangOpts();
  2228. InputKind::Language Lang;
  2229. if (LangOpts.OpenCL)
  2230. Lang = InputKind::OpenCL;
  2231. else if (LangOpts.CUDA)
  2232. Lang = InputKind::CUDA;
  2233. else if (LangOpts.RenderScript)
  2234. Lang = InputKind::RenderScript;
  2235. else if (LangOpts.CPlusPlus)
  2236. Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX;
  2237. else
  2238. Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C;
  2239. InputKind::Format Fmt = InputKind::Source;
  2240. if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
  2241. Fmt = InputKind::ModuleMap;
  2242. // We don't know if input was preprocessed. Assume not.
  2243. bool PP = false;
  2244. return InputKind(Lang, Fmt, PP);
  2245. }
  2246. #ifndef NDEBUG
  2247. ASTUnit::ConcurrencyState::ConcurrencyState() {
  2248. Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
  2249. }
  2250. ASTUnit::ConcurrencyState::~ConcurrencyState() {
  2251. delete static_cast<llvm::sys::MutexImpl *>(Mutex);
  2252. }
  2253. void ASTUnit::ConcurrencyState::start() {
  2254. bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
  2255. assert(acquired && "Concurrent access to ASTUnit!");
  2256. }
  2257. void ASTUnit::ConcurrencyState::finish() {
  2258. static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
  2259. }
  2260. #else // NDEBUG
  2261. ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
  2262. ASTUnit::ConcurrencyState::~ConcurrencyState() {}
  2263. void ASTUnit::ConcurrencyState::start() {}
  2264. void ASTUnit::ConcurrencyState::finish() {}
  2265. #endif // NDEBUG