ASTUnit.cpp 93 KB

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