ASTUnit.cpp 101 KB

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