ASTUnit.cpp 103 KB

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