ASTUnit.cpp 104 KB

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