ASTUnit.cpp 95 KB

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