ASTUnit.cpp 102 KB

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