ASTUnit.cpp 103 KB

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