ASTUnit.cpp 96 KB

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