ASTUnit.cpp 102 KB

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