ASTUnit.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935
  1. //===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // ASTUnit Implementation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Frontend/ASTUnit.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTConsumer.h"
  16. #include "clang/AST/DeclVisitor.h"
  17. #include "clang/AST/TypeOrdering.h"
  18. #include "clang/AST/StmtVisitor.h"
  19. #include "clang/Driver/Compilation.h"
  20. #include "clang/Driver/Driver.h"
  21. #include "clang/Driver/Job.h"
  22. #include "clang/Driver/Tool.h"
  23. #include "clang/Frontend/CompilerInstance.h"
  24. #include "clang/Frontend/FrontendActions.h"
  25. #include "clang/Frontend/FrontendDiagnostic.h"
  26. #include "clang/Frontend/FrontendOptions.h"
  27. #include "clang/Frontend/Utils.h"
  28. #include "clang/Serialization/ASTReader.h"
  29. #include "clang/Serialization/ASTWriter.h"
  30. #include "clang/Lex/HeaderSearch.h"
  31. #include "clang/Lex/Preprocessor.h"
  32. #include "clang/Basic/TargetOptions.h"
  33. #include "clang/Basic/TargetInfo.h"
  34. #include "clang/Basic/Diagnostic.h"
  35. #include "llvm/ADT/StringSet.h"
  36. #include "llvm/Support/MemoryBuffer.h"
  37. #include "llvm/System/Host.h"
  38. #include "llvm/System/Path.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include "llvm/Support/Timer.h"
  41. #include <cstdlib>
  42. #include <cstdio>
  43. #include <sys/stat.h>
  44. using namespace clang;
  45. using llvm::TimeRecord;
  46. namespace {
  47. class SimpleTimer {
  48. bool WantTiming;
  49. TimeRecord Start;
  50. std::string Output;
  51. public:
  52. explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
  53. if (WantTiming)
  54. Start = TimeRecord::getCurrentTime();
  55. }
  56. void setOutput(const llvm::Twine &Output) {
  57. if (WantTiming)
  58. this->Output = Output.str();
  59. }
  60. ~SimpleTimer() {
  61. if (WantTiming) {
  62. TimeRecord Elapsed = TimeRecord::getCurrentTime();
  63. Elapsed -= Start;
  64. llvm::errs() << Output << ':';
  65. Elapsed.print(Elapsed, llvm::errs());
  66. llvm::errs() << '\n';
  67. }
  68. }
  69. };
  70. }
  71. /// \brief After failing to build a precompiled preamble (due to
  72. /// errors in the source that occurs in the preamble), the number of
  73. /// reparses during which we'll skip even trying to precompile the
  74. /// preamble.
  75. const unsigned DefaultPreambleRebuildInterval = 5;
  76. /// \brief Tracks the number of ASTUnit objects that are currently active.
  77. ///
  78. /// Used for debugging purposes only.
  79. static unsigned ActiveASTUnitObjects;
  80. ASTUnit::ASTUnit(bool _MainFileIsAST)
  81. : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
  82. CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
  83. NumStoredDiagnosticsFromDriver(0),
  84. ConcurrencyCheckValue(CheckUnlocked),
  85. PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
  86. ShouldCacheCodeCompletionResults(false),
  87. NumTopLevelDeclsAtLastCompletionCache(0),
  88. CacheCodeCompletionCoolDown(0),
  89. UnsafeToFree(false) {
  90. if (getenv("LIBCLANG_OBJTRACKING")) {
  91. ++ActiveASTUnitObjects;
  92. fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
  93. }
  94. }
  95. ASTUnit::~ASTUnit() {
  96. ConcurrencyCheckValue = CheckLocked;
  97. CleanTemporaryFiles();
  98. if (!PreambleFile.empty())
  99. llvm::sys::Path(PreambleFile).eraseFromDisk();
  100. // Free the buffers associated with remapped files. We are required to
  101. // perform this operation here because we explicitly request that the
  102. // compiler instance *not* free these buffers for each invocation of the
  103. // parser.
  104. if (Invocation.get()) {
  105. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  106. for (PreprocessorOptions::remapped_file_buffer_iterator
  107. FB = PPOpts.remapped_file_buffer_begin(),
  108. FBEnd = PPOpts.remapped_file_buffer_end();
  109. FB != FBEnd;
  110. ++FB)
  111. delete FB->second;
  112. }
  113. delete SavedMainFileBuffer;
  114. delete PreambleBuffer;
  115. ClearCachedCompletionResults();
  116. if (getenv("LIBCLANG_OBJTRACKING")) {
  117. --ActiveASTUnitObjects;
  118. fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
  119. }
  120. }
  121. void ASTUnit::CleanTemporaryFiles() {
  122. for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
  123. TemporaryFiles[I].eraseFromDisk();
  124. TemporaryFiles.clear();
  125. }
  126. /// \brief Determine the set of code-completion contexts in which this
  127. /// declaration should be shown.
  128. static unsigned getDeclShowContexts(NamedDecl *ND,
  129. const LangOptions &LangOpts,
  130. bool &IsNestedNameSpecifier) {
  131. IsNestedNameSpecifier = false;
  132. if (isa<UsingShadowDecl>(ND))
  133. ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
  134. if (!ND)
  135. return 0;
  136. unsigned Contexts = 0;
  137. if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
  138. isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
  139. // Types can appear in these contexts.
  140. if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
  141. Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
  142. | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
  143. | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
  144. | (1 << (CodeCompletionContext::CCC_Statement - 1))
  145. | (1 << (CodeCompletionContext::CCC_Type - 1))
  146. | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
  147. // In C++, types can appear in expressions contexts (for functional casts).
  148. if (LangOpts.CPlusPlus)
  149. Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
  150. // In Objective-C, message sends can send interfaces. In Objective-C++,
  151. // all types are available due to functional casts.
  152. if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
  153. Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
  154. // Deal with tag names.
  155. if (isa<EnumDecl>(ND)) {
  156. Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
  157. // Part of the nested-name-specifier in C++0x.
  158. if (LangOpts.CPlusPlus0x)
  159. IsNestedNameSpecifier = true;
  160. } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
  161. if (Record->isUnion())
  162. Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
  163. else
  164. Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
  165. if (LangOpts.CPlusPlus)
  166. IsNestedNameSpecifier = true;
  167. } else if (isa<ClassTemplateDecl>(ND))
  168. IsNestedNameSpecifier = true;
  169. } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
  170. // Values can appear in these contexts.
  171. Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
  172. | (1 << (CodeCompletionContext::CCC_Expression - 1))
  173. | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
  174. | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
  175. } else if (isa<ObjCProtocolDecl>(ND)) {
  176. Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
  177. } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
  178. Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
  179. // Part of the nested-name-specifier.
  180. IsNestedNameSpecifier = true;
  181. }
  182. return Contexts;
  183. }
  184. void ASTUnit::CacheCodeCompletionResults() {
  185. if (!TheSema)
  186. return;
  187. SimpleTimer Timer(WantTiming);
  188. Timer.setOutput("Cache global code completions for " + getMainFileName());
  189. // Clear out the previous results.
  190. ClearCachedCompletionResults();
  191. // Gather the set of global code completions.
  192. typedef CodeCompletionResult Result;
  193. llvm::SmallVector<Result, 8> Results;
  194. TheSema->GatherGlobalCodeCompletions(Results);
  195. // Translate global code completions into cached completions.
  196. llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
  197. for (unsigned I = 0, N = Results.size(); I != N; ++I) {
  198. switch (Results[I].Kind) {
  199. case Result::RK_Declaration: {
  200. bool IsNestedNameSpecifier = false;
  201. CachedCodeCompletionResult CachedResult;
  202. CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
  203. CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
  204. Ctx->getLangOptions(),
  205. IsNestedNameSpecifier);
  206. CachedResult.Priority = Results[I].Priority;
  207. CachedResult.Kind = Results[I].CursorKind;
  208. CachedResult.Availability = Results[I].Availability;
  209. // Keep track of the type of this completion in an ASTContext-agnostic
  210. // way.
  211. QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
  212. if (UsageType.isNull()) {
  213. CachedResult.TypeClass = STC_Void;
  214. CachedResult.Type = 0;
  215. } else {
  216. CanQualType CanUsageType
  217. = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
  218. CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
  219. // Determine whether we have already seen this type. If so, we save
  220. // ourselves the work of formatting the type string by using the
  221. // temporary, CanQualType-based hash table to find the associated value.
  222. unsigned &TypeValue = CompletionTypes[CanUsageType];
  223. if (TypeValue == 0) {
  224. TypeValue = CompletionTypes.size();
  225. CachedCompletionTypes[QualType(CanUsageType).getAsString()]
  226. = TypeValue;
  227. }
  228. CachedResult.Type = TypeValue;
  229. }
  230. CachedCompletionResults.push_back(CachedResult);
  231. /// Handle nested-name-specifiers in C++.
  232. if (TheSema->Context.getLangOptions().CPlusPlus &&
  233. IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
  234. // The contexts in which a nested-name-specifier can appear in C++.
  235. unsigned NNSContexts
  236. = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
  237. | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
  238. | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
  239. | (1 << (CodeCompletionContext::CCC_Statement - 1))
  240. | (1 << (CodeCompletionContext::CCC_Expression - 1))
  241. | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
  242. | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
  243. | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
  244. | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
  245. | (1 << (CodeCompletionContext::CCC_Type - 1))
  246. | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
  247. | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
  248. if (isa<NamespaceDecl>(Results[I].Declaration) ||
  249. isa<NamespaceAliasDecl>(Results[I].Declaration))
  250. NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
  251. if (unsigned RemainingContexts
  252. = NNSContexts & ~CachedResult.ShowInContexts) {
  253. // If there any contexts where this completion can be a
  254. // nested-name-specifier but isn't already an option, create a
  255. // nested-name-specifier completion.
  256. Results[I].StartsNestedNameSpecifier = true;
  257. CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
  258. CachedResult.ShowInContexts = RemainingContexts;
  259. CachedResult.Priority = CCP_NestedNameSpecifier;
  260. CachedResult.TypeClass = STC_Void;
  261. CachedResult.Type = 0;
  262. CachedCompletionResults.push_back(CachedResult);
  263. }
  264. }
  265. break;
  266. }
  267. case Result::RK_Keyword:
  268. case Result::RK_Pattern:
  269. // Ignore keywords and patterns; we don't care, since they are so
  270. // easily regenerated.
  271. break;
  272. case Result::RK_Macro: {
  273. CachedCodeCompletionResult CachedResult;
  274. CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
  275. CachedResult.ShowInContexts
  276. = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
  277. | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
  278. | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
  279. | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
  280. | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
  281. | (1 << (CodeCompletionContext::CCC_Statement - 1))
  282. | (1 << (CodeCompletionContext::CCC_Expression - 1))
  283. | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
  284. | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
  285. | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
  286. | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
  287. CachedResult.Priority = Results[I].Priority;
  288. CachedResult.Kind = Results[I].CursorKind;
  289. CachedResult.Availability = Results[I].Availability;
  290. CachedResult.TypeClass = STC_Void;
  291. CachedResult.Type = 0;
  292. CachedCompletionResults.push_back(CachedResult);
  293. break;
  294. }
  295. }
  296. Results[I].Destroy();
  297. }
  298. // Make a note of the state when we performed this caching.
  299. NumTopLevelDeclsAtLastCompletionCache = top_level_size();
  300. }
  301. void ASTUnit::ClearCachedCompletionResults() {
  302. for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
  303. delete CachedCompletionResults[I].Completion;
  304. CachedCompletionResults.clear();
  305. CachedCompletionTypes.clear();
  306. }
  307. namespace {
  308. /// \brief Gathers information from ASTReader that will be used to initialize
  309. /// a Preprocessor.
  310. class ASTInfoCollector : public ASTReaderListener {
  311. LangOptions &LangOpt;
  312. HeaderSearch &HSI;
  313. std::string &TargetTriple;
  314. std::string &Predefines;
  315. unsigned &Counter;
  316. unsigned NumHeaderInfos;
  317. public:
  318. ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
  319. std::string &TargetTriple, std::string &Predefines,
  320. unsigned &Counter)
  321. : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
  322. Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
  323. virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
  324. LangOpt = LangOpts;
  325. return false;
  326. }
  327. virtual bool ReadTargetTriple(llvm::StringRef Triple) {
  328. TargetTriple = Triple;
  329. return false;
  330. }
  331. virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
  332. llvm::StringRef OriginalFileName,
  333. std::string &SuggestedPredefines) {
  334. Predefines = Buffers[0].Data;
  335. for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
  336. Predefines += Buffers[I].Data;
  337. }
  338. return false;
  339. }
  340. virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
  341. HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
  342. }
  343. virtual void ReadCounter(unsigned Value) {
  344. Counter = Value;
  345. }
  346. };
  347. class StoredDiagnosticClient : public DiagnosticClient {
  348. llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
  349. public:
  350. explicit StoredDiagnosticClient(
  351. llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
  352. : StoredDiags(StoredDiags) { }
  353. virtual void HandleDiagnostic(Diagnostic::Level Level,
  354. const DiagnosticInfo &Info);
  355. };
  356. /// \brief RAII object that optionally captures diagnostics, if
  357. /// there is no diagnostic client to capture them already.
  358. class CaptureDroppedDiagnostics {
  359. Diagnostic &Diags;
  360. StoredDiagnosticClient Client;
  361. DiagnosticClient *PreviousClient;
  362. public:
  363. CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
  364. llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
  365. : Diags(Diags), Client(StoredDiags), PreviousClient(0)
  366. {
  367. if (RequestCapture || Diags.getClient() == 0) {
  368. PreviousClient = Diags.takeClient();
  369. Diags.setClient(&Client);
  370. }
  371. }
  372. ~CaptureDroppedDiagnostics() {
  373. if (Diags.getClient() == &Client) {
  374. Diags.takeClient();
  375. Diags.setClient(PreviousClient);
  376. }
  377. }
  378. };
  379. } // anonymous namespace
  380. void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
  381. const DiagnosticInfo &Info) {
  382. // Default implementation (Warnings/errors count).
  383. DiagnosticClient::HandleDiagnostic(Level, Info);
  384. StoredDiags.push_back(StoredDiagnostic(Level, Info));
  385. }
  386. const std::string &ASTUnit::getOriginalSourceFileName() {
  387. return OriginalSourceFile;
  388. }
  389. const std::string &ASTUnit::getASTFileName() {
  390. assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
  391. return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
  392. }
  393. llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
  394. std::string *ErrorStr,
  395. int64_t FileSize) {
  396. assert(FileMgr);
  397. return FileMgr->getBufferForFile(Filename, ErrorStr, FileSize);
  398. }
  399. /// \brief Configure the diagnostics object for use with ASTUnit.
  400. void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
  401. ASTUnit &AST, bool CaptureDiagnostics) {
  402. if (!Diags.getPtr()) {
  403. // No diagnostics engine was provided, so create our own diagnostics object
  404. // with the default options.
  405. DiagnosticOptions DiagOpts;
  406. DiagnosticClient *Client = 0;
  407. if (CaptureDiagnostics)
  408. Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
  409. Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0, Client);
  410. } else if (CaptureDiagnostics) {
  411. Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
  412. }
  413. }
  414. ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
  415. llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
  416. const FileSystemOptions &FileSystemOpts,
  417. bool OnlyLocalDecls,
  418. RemappedFile *RemappedFiles,
  419. unsigned NumRemappedFiles,
  420. bool CaptureDiagnostics) {
  421. llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
  422. ConfigureDiags(Diags, *AST, CaptureDiagnostics);
  423. AST->OnlyLocalDecls = OnlyLocalDecls;
  424. AST->CaptureDiagnostics = CaptureDiagnostics;
  425. AST->Diagnostics = Diags;
  426. AST->FileMgr.reset(new FileManager(FileSystemOpts));
  427. AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics(),
  428. AST->getFileManager()));
  429. AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
  430. for (unsigned I = 0; I != NumRemappedFiles; ++I) {
  431. // Create the file entry for the file that we're mapping from.
  432. const FileEntry *FromFile
  433. = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
  434. RemappedFiles[I].second->getBufferSize(),
  435. 0);
  436. if (!FromFile) {
  437. AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
  438. << RemappedFiles[I].first;
  439. delete RemappedFiles[I].second;
  440. continue;
  441. }
  442. // Override the contents of the "from" file with the contents of
  443. // the "to" file.
  444. AST->getSourceManager().overrideFileContents(FromFile,
  445. RemappedFiles[I].second);
  446. }
  447. // Gather Info for preprocessor construction later on.
  448. LangOptions LangInfo;
  449. HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
  450. std::string TargetTriple;
  451. std::string Predefines;
  452. unsigned Counter;
  453. llvm::OwningPtr<ASTReader> Reader;
  454. Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
  455. AST->getDiagnostics()));
  456. Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
  457. Predefines, Counter));
  458. switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
  459. case ASTReader::Success:
  460. break;
  461. case ASTReader::Failure:
  462. case ASTReader::IgnorePCH:
  463. AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
  464. return NULL;
  465. }
  466. AST->OriginalSourceFile = Reader->getOriginalSourceFile();
  467. // AST file loaded successfully. Now create the preprocessor.
  468. // Get information about the target being compiled for.
  469. //
  470. // FIXME: This is broken, we should store the TargetOptions in the AST file.
  471. TargetOptions TargetOpts;
  472. TargetOpts.ABI = "";
  473. TargetOpts.CXXABI = "";
  474. TargetOpts.CPU = "";
  475. TargetOpts.Features.clear();
  476. TargetOpts.Triple = TargetTriple;
  477. AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
  478. TargetOpts));
  479. AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
  480. *AST->Target.get(),
  481. AST->getSourceManager(), HeaderInfo));
  482. Preprocessor &PP = *AST->PP.get();
  483. PP.setPredefines(Reader->getSuggestedPredefines());
  484. PP.setCounterValue(Counter);
  485. Reader->setPreprocessor(PP);
  486. // Create and initialize the ASTContext.
  487. AST->Ctx.reset(new ASTContext(LangInfo,
  488. AST->getSourceManager(),
  489. *AST->Target.get(),
  490. PP.getIdentifierTable(),
  491. PP.getSelectorTable(),
  492. PP.getBuiltinInfo(),
  493. /* size_reserve = */0));
  494. ASTContext &Context = *AST->Ctx.get();
  495. Reader->InitializeContext(Context);
  496. // Attach the AST reader to the AST context as an external AST
  497. // source, so that declarations will be deserialized from the
  498. // AST file as needed.
  499. ASTReader *ReaderPtr = Reader.get();
  500. llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
  501. Context.setExternalSource(Source);
  502. // Create an AST consumer, even though it isn't used.
  503. AST->Consumer.reset(new ASTConsumer);
  504. // Create a semantic analysis object and tell the AST reader about it.
  505. AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
  506. AST->TheSema->Initialize();
  507. ReaderPtr->InitializeSema(*AST->TheSema);
  508. return AST.take();
  509. }
  510. namespace {
  511. class TopLevelDeclTrackerConsumer : public ASTConsumer {
  512. ASTUnit &Unit;
  513. public:
  514. TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
  515. void HandleTopLevelDecl(DeclGroupRef D) {
  516. for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
  517. Decl *D = *it;
  518. // FIXME: Currently ObjC method declarations are incorrectly being
  519. // reported as top-level declarations, even though their DeclContext
  520. // is the containing ObjC @interface/@implementation. This is a
  521. // fundamental problem in the parser right now.
  522. if (isa<ObjCMethodDecl>(D))
  523. continue;
  524. Unit.addTopLevelDecl(D);
  525. }
  526. }
  527. // We're not interested in "interesting" decls.
  528. void HandleInterestingDecl(DeclGroupRef) {}
  529. };
  530. class TopLevelDeclTrackerAction : public ASTFrontendAction {
  531. public:
  532. ASTUnit &Unit;
  533. virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
  534. llvm::StringRef InFile) {
  535. return new TopLevelDeclTrackerConsumer(Unit);
  536. }
  537. public:
  538. TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
  539. virtual bool hasCodeCompletionSupport() const { return false; }
  540. virtual bool usesCompleteTranslationUnit() {
  541. return Unit.isCompleteTranslationUnit();
  542. }
  543. };
  544. class PrecompilePreambleConsumer : public PCHGenerator {
  545. ASTUnit &Unit;
  546. std::vector<Decl *> TopLevelDecls;
  547. public:
  548. PrecompilePreambleConsumer(ASTUnit &Unit,
  549. const Preprocessor &PP, bool Chaining,
  550. const char *isysroot, llvm::raw_ostream *Out)
  551. : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
  552. virtual void HandleTopLevelDecl(DeclGroupRef D) {
  553. for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
  554. Decl *D = *it;
  555. // FIXME: Currently ObjC method declarations are incorrectly being
  556. // reported as top-level declarations, even though their DeclContext
  557. // is the containing ObjC @interface/@implementation. This is a
  558. // fundamental problem in the parser right now.
  559. if (isa<ObjCMethodDecl>(D))
  560. continue;
  561. TopLevelDecls.push_back(D);
  562. }
  563. }
  564. virtual void HandleTranslationUnit(ASTContext &Ctx) {
  565. PCHGenerator::HandleTranslationUnit(Ctx);
  566. if (!Unit.getDiagnostics().hasErrorOccurred()) {
  567. // Translate the top-level declarations we captured during
  568. // parsing into declaration IDs in the precompiled
  569. // preamble. This will allow us to deserialize those top-level
  570. // declarations when requested.
  571. for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
  572. Unit.addTopLevelDeclFromPreamble(
  573. getWriter().getDeclID(TopLevelDecls[I]));
  574. }
  575. }
  576. };
  577. class PrecompilePreambleAction : public ASTFrontendAction {
  578. ASTUnit &Unit;
  579. public:
  580. explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
  581. virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
  582. llvm::StringRef InFile) {
  583. std::string Sysroot;
  584. llvm::raw_ostream *OS = 0;
  585. bool Chaining;
  586. if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
  587. OS, Chaining))
  588. return 0;
  589. const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
  590. Sysroot.c_str() : 0;
  591. return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
  592. isysroot, OS);
  593. }
  594. virtual bool hasCodeCompletionSupport() const { return false; }
  595. virtual bool hasASTFileSupport() const { return false; }
  596. virtual bool usesCompleteTranslationUnit() { return false; }
  597. };
  598. }
  599. /// Parse the source file into a translation unit using the given compiler
  600. /// invocation, replacing the current translation unit.
  601. ///
  602. /// \returns True if a failure occurred that causes the ASTUnit not to
  603. /// contain any translation-unit information, false otherwise.
  604. bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
  605. delete SavedMainFileBuffer;
  606. SavedMainFileBuffer = 0;
  607. if (!Invocation.get()) {
  608. delete OverrideMainBuffer;
  609. return true;
  610. }
  611. // Create the compiler instance to use for building the AST.
  612. CompilerInstance Clang;
  613. Clang.setInvocation(Invocation.take());
  614. OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
  615. // Set up diagnostics, capturing any diagnostics that would
  616. // otherwise be dropped.
  617. Clang.setDiagnostics(&getDiagnostics());
  618. // Create the target instance.
  619. Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
  620. Clang.getTargetOpts()));
  621. if (!Clang.hasTarget()) {
  622. delete OverrideMainBuffer;
  623. return true;
  624. }
  625. // Inform the target of the language options.
  626. //
  627. // FIXME: We shouldn't need to do this, the target should be immutable once
  628. // created. This complexity should be lifted elsewhere.
  629. Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
  630. assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
  631. "Invocation must have exactly one source file!");
  632. assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
  633. "FIXME: AST inputs not yet supported here!");
  634. assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
  635. "IR inputs not support here!");
  636. // Configure the various subsystems.
  637. // FIXME: Should we retain the previous file manager?
  638. FileSystemOpts = Clang.getFileSystemOpts();
  639. FileMgr.reset(new FileManager(Clang.getFileSystemOpts()));
  640. SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr));
  641. TheSema.reset();
  642. Ctx.reset();
  643. PP.reset();
  644. // Clear out old caches and data.
  645. TopLevelDecls.clear();
  646. CleanTemporaryFiles();
  647. PreprocessedEntitiesByFile.clear();
  648. if (!OverrideMainBuffer) {
  649. StoredDiagnostics.erase(
  650. StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
  651. StoredDiagnostics.end());
  652. TopLevelDeclsInPreamble.clear();
  653. }
  654. // Create a file manager object to provide access to and cache the filesystem.
  655. Clang.setFileManager(&getFileManager());
  656. // Create the source manager.
  657. Clang.setSourceManager(&getSourceManager());
  658. // If the main file has been overridden due to the use of a preamble,
  659. // make that override happen and introduce the preamble.
  660. PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
  661. std::string PriorImplicitPCHInclude;
  662. if (OverrideMainBuffer) {
  663. PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
  664. PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
  665. PreprocessorOpts.PrecompiledPreambleBytes.second
  666. = PreambleEndsAtStartOfLine;
  667. PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
  668. PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
  669. PreprocessorOpts.DisablePCHValidation = true;
  670. // The stored diagnostic has the old source manager in it; update
  671. // the locations to refer into the new source manager. Since we've
  672. // been careful to make sure that the source manager's state
  673. // before and after are identical, so that we can reuse the source
  674. // location itself.
  675. for (unsigned I = NumStoredDiagnosticsFromDriver,
  676. N = StoredDiagnostics.size();
  677. I < N; ++I) {
  678. FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
  679. getSourceManager());
  680. StoredDiagnostics[I].setLocation(Loc);
  681. }
  682. // Keep track of the override buffer;
  683. SavedMainFileBuffer = OverrideMainBuffer;
  684. } else {
  685. PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
  686. PreprocessorOpts.PrecompiledPreambleBytes.second = false;
  687. }
  688. llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
  689. Act.reset(new TopLevelDeclTrackerAction(*this));
  690. if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
  691. Clang.getFrontendOpts().Inputs[0].first))
  692. goto error;
  693. Act->Execute();
  694. // Steal the created target, context, and preprocessor, and take back the
  695. // source and file managers.
  696. TheSema.reset(Clang.takeSema());
  697. Consumer.reset(Clang.takeASTConsumer());
  698. Ctx.reset(Clang.takeASTContext());
  699. PP.reset(Clang.takePreprocessor());
  700. Clang.takeSourceManager();
  701. Clang.takeFileManager();
  702. Target.reset(Clang.takeTarget());
  703. Act->EndSourceFile();
  704. // Remove the overridden buffer we used for the preamble.
  705. if (OverrideMainBuffer) {
  706. PreprocessorOpts.eraseRemappedFile(
  707. PreprocessorOpts.remapped_file_buffer_end() - 1);
  708. PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
  709. }
  710. Invocation.reset(Clang.takeInvocation());
  711. return false;
  712. error:
  713. // Remove the overridden buffer we used for the preamble.
  714. if (OverrideMainBuffer) {
  715. PreprocessorOpts.eraseRemappedFile(
  716. PreprocessorOpts.remapped_file_buffer_end() - 1);
  717. PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
  718. delete OverrideMainBuffer;
  719. SavedMainFileBuffer = 0;
  720. }
  721. StoredDiagnostics.clear();
  722. Clang.takeSourceManager();
  723. Clang.takeFileManager();
  724. Invocation.reset(Clang.takeInvocation());
  725. return true;
  726. }
  727. /// \brief Simple function to retrieve a path for a preamble precompiled header.
  728. static std::string GetPreamblePCHPath() {
  729. // FIXME: This is lame; sys::Path should provide this function (in particular,
  730. // it should know how to find the temporary files dir).
  731. // FIXME: This is really lame. I copied this code from the Driver!
  732. // FIXME: This is a hack so that we can override the preamble file during
  733. // crash-recovery testing, which is the only case where the preamble files
  734. // are not necessarily cleaned up.
  735. const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
  736. if (TmpFile)
  737. return TmpFile;
  738. std::string Error;
  739. const char *TmpDir = ::getenv("TMPDIR");
  740. if (!TmpDir)
  741. TmpDir = ::getenv("TEMP");
  742. if (!TmpDir)
  743. TmpDir = ::getenv("TMP");
  744. #ifdef LLVM_ON_WIN32
  745. if (!TmpDir)
  746. TmpDir = ::getenv("USERPROFILE");
  747. #endif
  748. if (!TmpDir)
  749. TmpDir = "/tmp";
  750. llvm::sys::Path P(TmpDir);
  751. P.createDirectoryOnDisk(true);
  752. P.appendComponent("preamble");
  753. P.appendSuffix("pch");
  754. if (P.createTemporaryFileOnDisk())
  755. return std::string();
  756. return P.str();
  757. }
  758. /// \brief Compute the preamble for the main file, providing the source buffer
  759. /// that corresponds to the main file along with a pair (bytes, start-of-line)
  760. /// that describes the preamble.
  761. std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
  762. ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
  763. unsigned MaxLines, bool &CreatedBuffer) {
  764. FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
  765. PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
  766. CreatedBuffer = false;
  767. // Try to determine if the main file has been remapped, either from the
  768. // command line (to another file) or directly through the compiler invocation
  769. // (to a memory buffer).
  770. llvm::MemoryBuffer *Buffer = 0;
  771. llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
  772. if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
  773. // Check whether there is a file-file remapping of the main file
  774. for (PreprocessorOptions::remapped_file_iterator
  775. M = PreprocessorOpts.remapped_file_begin(),
  776. E = PreprocessorOpts.remapped_file_end();
  777. M != E;
  778. ++M) {
  779. llvm::sys::PathWithStatus MPath(M->first);
  780. if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
  781. if (MainFileStatus->uniqueID == MStatus->uniqueID) {
  782. // We found a remapping. Try to load the resulting, remapped source.
  783. if (CreatedBuffer) {
  784. delete Buffer;
  785. CreatedBuffer = false;
  786. }
  787. Buffer = getBufferForFile(M->second);
  788. if (!Buffer)
  789. return std::make_pair((llvm::MemoryBuffer*)0,
  790. std::make_pair(0, true));
  791. CreatedBuffer = true;
  792. }
  793. }
  794. }
  795. // Check whether there is a file-buffer remapping. It supercedes the
  796. // file-file remapping.
  797. for (PreprocessorOptions::remapped_file_buffer_iterator
  798. M = PreprocessorOpts.remapped_file_buffer_begin(),
  799. E = PreprocessorOpts.remapped_file_buffer_end();
  800. M != E;
  801. ++M) {
  802. llvm::sys::PathWithStatus MPath(M->first);
  803. if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
  804. if (MainFileStatus->uniqueID == MStatus->uniqueID) {
  805. // We found a remapping.
  806. if (CreatedBuffer) {
  807. delete Buffer;
  808. CreatedBuffer = false;
  809. }
  810. Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
  811. }
  812. }
  813. }
  814. }
  815. // If the main source file was not remapped, load it now.
  816. if (!Buffer) {
  817. Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
  818. if (!Buffer)
  819. return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
  820. CreatedBuffer = true;
  821. }
  822. return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
  823. }
  824. static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
  825. unsigned NewSize,
  826. llvm::StringRef NewName) {
  827. llvm::MemoryBuffer *Result
  828. = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
  829. memcpy(const_cast<char*>(Result->getBufferStart()),
  830. Old->getBufferStart(), Old->getBufferSize());
  831. memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
  832. ' ', NewSize - Old->getBufferSize() - 1);
  833. const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
  834. return Result;
  835. }
  836. /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
  837. /// the source file.
  838. ///
  839. /// This routine will compute the preamble of the main source file. If a
  840. /// non-trivial preamble is found, it will precompile that preamble into a
  841. /// precompiled header so that the precompiled preamble can be used to reduce
  842. /// reparsing time. If a precompiled preamble has already been constructed,
  843. /// this routine will determine if it is still valid and, if so, avoid
  844. /// rebuilding the precompiled preamble.
  845. ///
  846. /// \param AllowRebuild When true (the default), this routine is
  847. /// allowed to rebuild the precompiled preamble if it is found to be
  848. /// out-of-date.
  849. ///
  850. /// \param MaxLines When non-zero, the maximum number of lines that
  851. /// can occur within the preamble.
  852. ///
  853. /// \returns If the precompiled preamble can be used, returns a newly-allocated
  854. /// buffer that should be used in place of the main file when doing so.
  855. /// Otherwise, returns a NULL pointer.
  856. llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
  857. CompilerInvocation PreambleInvocation,
  858. bool AllowRebuild,
  859. unsigned MaxLines) {
  860. FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
  861. PreprocessorOptions &PreprocessorOpts
  862. = PreambleInvocation.getPreprocessorOpts();
  863. bool CreatedPreambleBuffer = false;
  864. std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
  865. = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
  866. // If ComputePreamble() Take ownership of the
  867. llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
  868. if (CreatedPreambleBuffer)
  869. OwnedPreambleBuffer.reset(NewPreamble.first);
  870. if (!NewPreamble.second.first) {
  871. // We couldn't find a preamble in the main source. Clear out the current
  872. // preamble, if we have one. It's obviously no good any more.
  873. Preamble.clear();
  874. if (!PreambleFile.empty()) {
  875. llvm::sys::Path(PreambleFile).eraseFromDisk();
  876. PreambleFile.clear();
  877. }
  878. // The next time we actually see a preamble, precompile it.
  879. PreambleRebuildCounter = 1;
  880. return 0;
  881. }
  882. if (!Preamble.empty()) {
  883. // We've previously computed a preamble. Check whether we have the same
  884. // preamble now that we did before, and that there's enough space in
  885. // the main-file buffer within the precompiled preamble to fit the
  886. // new main file.
  887. if (Preamble.size() == NewPreamble.second.first &&
  888. PreambleEndsAtStartOfLine == NewPreamble.second.second &&
  889. NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
  890. memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
  891. NewPreamble.second.first) == 0) {
  892. // The preamble has not changed. We may be able to re-use the precompiled
  893. // preamble.
  894. // Check that none of the files used by the preamble have changed.
  895. bool AnyFileChanged = false;
  896. // First, make a record of those files that have been overridden via
  897. // remapping or unsaved_files.
  898. llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
  899. for (PreprocessorOptions::remapped_file_iterator
  900. R = PreprocessorOpts.remapped_file_begin(),
  901. REnd = PreprocessorOpts.remapped_file_end();
  902. !AnyFileChanged && R != REnd;
  903. ++R) {
  904. struct stat StatBuf;
  905. if (stat(R->second.c_str(), &StatBuf)) {
  906. // If we can't stat the file we're remapping to, assume that something
  907. // horrible happened.
  908. AnyFileChanged = true;
  909. break;
  910. }
  911. OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
  912. StatBuf.st_mtime);
  913. }
  914. for (PreprocessorOptions::remapped_file_buffer_iterator
  915. R = PreprocessorOpts.remapped_file_buffer_begin(),
  916. REnd = PreprocessorOpts.remapped_file_buffer_end();
  917. !AnyFileChanged && R != REnd;
  918. ++R) {
  919. // FIXME: Should we actually compare the contents of file->buffer
  920. // remappings?
  921. OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
  922. 0);
  923. }
  924. // Check whether anything has changed.
  925. for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
  926. F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
  927. !AnyFileChanged && F != FEnd;
  928. ++F) {
  929. llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
  930. = OverriddenFiles.find(F->first());
  931. if (Overridden != OverriddenFiles.end()) {
  932. // This file was remapped; check whether the newly-mapped file
  933. // matches up with the previous mapping.
  934. if (Overridden->second != F->second)
  935. AnyFileChanged = true;
  936. continue;
  937. }
  938. // The file was not remapped; check whether it has changed on disk.
  939. struct stat StatBuf;
  940. if (stat(F->first(), &StatBuf)) {
  941. // If we can't stat the file, assume that something horrible happened.
  942. AnyFileChanged = true;
  943. } else if (StatBuf.st_size != F->second.first ||
  944. StatBuf.st_mtime != F->second.second)
  945. AnyFileChanged = true;
  946. }
  947. if (!AnyFileChanged) {
  948. // Okay! We can re-use the precompiled preamble.
  949. // Set the state of the diagnostic object to mimic its state
  950. // after parsing the preamble.
  951. // FIXME: This won't catch any #pragma push warning changes that
  952. // have occurred in the preamble.
  953. getDiagnostics().Reset();
  954. ProcessWarningOptions(getDiagnostics(),
  955. PreambleInvocation.getDiagnosticOpts());
  956. getDiagnostics().setNumWarnings(NumWarningsInPreamble);
  957. if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
  958. StoredDiagnostics.erase(
  959. StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
  960. StoredDiagnostics.end());
  961. // Create a version of the main file buffer that is padded to
  962. // buffer size we reserved when creating the preamble.
  963. return CreatePaddedMainFileBuffer(NewPreamble.first,
  964. PreambleReservedSize,
  965. FrontendOpts.Inputs[0].second);
  966. }
  967. }
  968. // If we aren't allowed to rebuild the precompiled preamble, just
  969. // return now.
  970. if (!AllowRebuild)
  971. return 0;
  972. // We can't reuse the previously-computed preamble. Build a new one.
  973. Preamble.clear();
  974. llvm::sys::Path(PreambleFile).eraseFromDisk();
  975. PreambleRebuildCounter = 1;
  976. } else if (!AllowRebuild) {
  977. // We aren't allowed to rebuild the precompiled preamble; just
  978. // return now.
  979. return 0;
  980. }
  981. // If the preamble rebuild counter > 1, it's because we previously
  982. // failed to build a preamble and we're not yet ready to try
  983. // again. Decrement the counter and return a failure.
  984. if (PreambleRebuildCounter > 1) {
  985. --PreambleRebuildCounter;
  986. return 0;
  987. }
  988. // Create a temporary file for the precompiled preamble. In rare
  989. // circumstances, this can fail.
  990. std::string PreamblePCHPath = GetPreamblePCHPath();
  991. if (PreamblePCHPath.empty()) {
  992. // Try again next time.
  993. PreambleRebuildCounter = 1;
  994. return 0;
  995. }
  996. // We did not previously compute a preamble, or it can't be reused anyway.
  997. SimpleTimer PreambleTimer(WantTiming);
  998. PreambleTimer.setOutput("Precompiling preamble");
  999. // Create a new buffer that stores the preamble. The buffer also contains
  1000. // extra space for the original contents of the file (which will be present
  1001. // when we actually parse the file) along with more room in case the file
  1002. // grows.
  1003. PreambleReservedSize = NewPreamble.first->getBufferSize();
  1004. if (PreambleReservedSize < 4096)
  1005. PreambleReservedSize = 8191;
  1006. else
  1007. PreambleReservedSize *= 2;
  1008. // Save the preamble text for later; we'll need to compare against it for
  1009. // subsequent reparses.
  1010. Preamble.assign(NewPreamble.first->getBufferStart(),
  1011. NewPreamble.first->getBufferStart()
  1012. + NewPreamble.second.first);
  1013. PreambleEndsAtStartOfLine = NewPreamble.second.second;
  1014. delete PreambleBuffer;
  1015. PreambleBuffer
  1016. = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
  1017. FrontendOpts.Inputs[0].second);
  1018. memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
  1019. NewPreamble.first->getBufferStart(), Preamble.size());
  1020. memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
  1021. ' ', PreambleReservedSize - Preamble.size() - 1);
  1022. const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
  1023. // Remap the main source file to the preamble buffer.
  1024. llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
  1025. PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
  1026. // Tell the compiler invocation to generate a temporary precompiled header.
  1027. FrontendOpts.ProgramAction = frontend::GeneratePCH;
  1028. FrontendOpts.ChainedPCH = true;
  1029. // FIXME: Generate the precompiled header into memory?
  1030. FrontendOpts.OutputFile = PreamblePCHPath;
  1031. PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
  1032. PreprocessorOpts.PrecompiledPreambleBytes.second = false;
  1033. // Create the compiler instance to use for building the precompiled preamble.
  1034. CompilerInstance Clang;
  1035. Clang.setInvocation(&PreambleInvocation);
  1036. OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
  1037. // Set up diagnostics, capturing all of the diagnostics produced.
  1038. Clang.setDiagnostics(&getDiagnostics());
  1039. // Create the target instance.
  1040. Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
  1041. Clang.getTargetOpts()));
  1042. if (!Clang.hasTarget()) {
  1043. llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
  1044. Preamble.clear();
  1045. PreambleRebuildCounter = DefaultPreambleRebuildInterval;
  1046. PreprocessorOpts.eraseRemappedFile(
  1047. PreprocessorOpts.remapped_file_buffer_end() - 1);
  1048. return 0;
  1049. }
  1050. // Inform the target of the language options.
  1051. //
  1052. // FIXME: We shouldn't need to do this, the target should be immutable once
  1053. // created. This complexity should be lifted elsewhere.
  1054. Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
  1055. assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
  1056. "Invocation must have exactly one source file!");
  1057. assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
  1058. "FIXME: AST inputs not yet supported here!");
  1059. assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
  1060. "IR inputs not support here!");
  1061. // Clear out old caches and data.
  1062. getDiagnostics().Reset();
  1063. ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
  1064. StoredDiagnostics.erase(
  1065. StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
  1066. StoredDiagnostics.end());
  1067. TopLevelDecls.clear();
  1068. TopLevelDeclsInPreamble.clear();
  1069. // Create a file manager object to provide access to and cache the filesystem.
  1070. Clang.setFileManager(new FileManager(Clang.getFileSystemOpts()));
  1071. // Create the source manager.
  1072. Clang.setSourceManager(new SourceManager(getDiagnostics(),
  1073. Clang.getFileManager()));
  1074. llvm::OwningPtr<PrecompilePreambleAction> Act;
  1075. Act.reset(new PrecompilePreambleAction(*this));
  1076. if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
  1077. Clang.getFrontendOpts().Inputs[0].first)) {
  1078. Clang.takeInvocation();
  1079. llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
  1080. Preamble.clear();
  1081. PreambleRebuildCounter = DefaultPreambleRebuildInterval;
  1082. PreprocessorOpts.eraseRemappedFile(
  1083. PreprocessorOpts.remapped_file_buffer_end() - 1);
  1084. return 0;
  1085. }
  1086. Act->Execute();
  1087. Act->EndSourceFile();
  1088. Clang.takeInvocation();
  1089. if (Diagnostics->hasErrorOccurred()) {
  1090. // There were errors parsing the preamble, so no precompiled header was
  1091. // generated. Forget that we even tried.
  1092. // FIXME: Should we leave a note for ourselves to try again?
  1093. llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
  1094. Preamble.clear();
  1095. TopLevelDeclsInPreamble.clear();
  1096. PreambleRebuildCounter = DefaultPreambleRebuildInterval;
  1097. PreprocessorOpts.eraseRemappedFile(
  1098. PreprocessorOpts.remapped_file_buffer_end() - 1);
  1099. return 0;
  1100. }
  1101. // Keep track of the preamble we precompiled.
  1102. PreambleFile = FrontendOpts.OutputFile;
  1103. NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
  1104. NumWarningsInPreamble = getDiagnostics().getNumWarnings();
  1105. // Keep track of all of the files that the source manager knows about,
  1106. // so we can verify whether they have changed or not.
  1107. FilesInPreamble.clear();
  1108. SourceManager &SourceMgr = Clang.getSourceManager();
  1109. const llvm::MemoryBuffer *MainFileBuffer
  1110. = SourceMgr.getBuffer(SourceMgr.getMainFileID());
  1111. for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
  1112. FEnd = SourceMgr.fileinfo_end();
  1113. F != FEnd;
  1114. ++F) {
  1115. const FileEntry *File = F->second->Entry;
  1116. if (!File || F->second->getRawBuffer() == MainFileBuffer)
  1117. continue;
  1118. FilesInPreamble[File->getName()]
  1119. = std::make_pair(F->second->getSize(), File->getModificationTime());
  1120. }
  1121. PreambleRebuildCounter = 1;
  1122. PreprocessorOpts.eraseRemappedFile(
  1123. PreprocessorOpts.remapped_file_buffer_end() - 1);
  1124. return CreatePaddedMainFileBuffer(NewPreamble.first,
  1125. PreambleReservedSize,
  1126. FrontendOpts.Inputs[0].second);
  1127. }
  1128. void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
  1129. std::vector<Decl *> Resolved;
  1130. Resolved.reserve(TopLevelDeclsInPreamble.size());
  1131. ExternalASTSource &Source = *getASTContext().getExternalSource();
  1132. for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
  1133. // Resolve the declaration ID to an actual declaration, possibly
  1134. // deserializing the declaration in the process.
  1135. Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
  1136. if (D)
  1137. Resolved.push_back(D);
  1138. }
  1139. TopLevelDeclsInPreamble.clear();
  1140. TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
  1141. }
  1142. unsigned ASTUnit::getMaxPCHLevel() const {
  1143. if (!getOnlyLocalDecls())
  1144. return Decl::MaxPCHLevel;
  1145. return 0;
  1146. }
  1147. llvm::StringRef ASTUnit::getMainFileName() const {
  1148. return Invocation->getFrontendOpts().Inputs[0].second;
  1149. }
  1150. bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
  1151. if (!Invocation)
  1152. return true;
  1153. // We'll manage file buffers ourselves.
  1154. Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
  1155. Invocation->getFrontendOpts().DisableFree = false;
  1156. llvm::MemoryBuffer *OverrideMainBuffer = 0;
  1157. if (PrecompilePreamble) {
  1158. PreambleRebuildCounter = 2;
  1159. OverrideMainBuffer
  1160. = getMainBufferWithPrecompiledPreamble(*Invocation);
  1161. }
  1162. SimpleTimer ParsingTimer(WantTiming);
  1163. ParsingTimer.setOutput("Parsing " + getMainFileName());
  1164. return Parse(OverrideMainBuffer);
  1165. }
  1166. ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
  1167. llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
  1168. bool OnlyLocalDecls,
  1169. bool CaptureDiagnostics,
  1170. bool PrecompilePreamble,
  1171. bool CompleteTranslationUnit,
  1172. bool CacheCodeCompletionResults) {
  1173. // Create the AST unit.
  1174. llvm::OwningPtr<ASTUnit> AST;
  1175. AST.reset(new ASTUnit(false));
  1176. ConfigureDiags(Diags, *AST, CaptureDiagnostics);
  1177. AST->Diagnostics = Diags;
  1178. AST->OnlyLocalDecls = OnlyLocalDecls;
  1179. AST->CaptureDiagnostics = CaptureDiagnostics;
  1180. AST->CompleteTranslationUnit = CompleteTranslationUnit;
  1181. AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
  1182. AST->CacheCodeCompletionCoolDown = 1;
  1183. AST->Invocation.reset(CI);
  1184. return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
  1185. }
  1186. ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
  1187. const char **ArgEnd,
  1188. llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
  1189. llvm::StringRef ResourceFilesPath,
  1190. bool OnlyLocalDecls,
  1191. bool CaptureDiagnostics,
  1192. RemappedFile *RemappedFiles,
  1193. unsigned NumRemappedFiles,
  1194. bool PrecompilePreamble,
  1195. bool CompleteTranslationUnit,
  1196. bool CacheCodeCompletionResults,
  1197. bool CXXPrecompilePreamble,
  1198. bool CXXChainedPCH) {
  1199. if (!Diags.getPtr()) {
  1200. // No diagnostics engine was provided, so create our own diagnostics object
  1201. // with the default options.
  1202. DiagnosticOptions DiagOpts;
  1203. Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
  1204. }
  1205. llvm::SmallVector<const char *, 16> Args;
  1206. Args.push_back("<clang>"); // FIXME: Remove dummy argument.
  1207. Args.insert(Args.end(), ArgBegin, ArgEnd);
  1208. // FIXME: Find a cleaner way to force the driver into restricted modes. We
  1209. // also want to force it to use clang.
  1210. Args.push_back("-fsyntax-only");
  1211. llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
  1212. llvm::OwningPtr<CompilerInvocation> CI;
  1213. {
  1214. CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
  1215. StoredDiagnostics);
  1216. // FIXME: We shouldn't have to pass in the path info.
  1217. driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
  1218. "a.out", false, false, *Diags);
  1219. // Don't check that inputs exist, they have been remapped.
  1220. TheDriver.setCheckInputsExist(false);
  1221. llvm::OwningPtr<driver::Compilation> C(
  1222. TheDriver.BuildCompilation(Args.size(), Args.data()));
  1223. // We expect to get back exactly one command job, if we didn't something
  1224. // failed.
  1225. const driver::JobList &Jobs = C->getJobs();
  1226. if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
  1227. llvm::SmallString<256> Msg;
  1228. llvm::raw_svector_ostream OS(Msg);
  1229. C->PrintJob(OS, C->getJobs(), "; ", true);
  1230. Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
  1231. return 0;
  1232. }
  1233. const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
  1234. if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
  1235. Diags->Report(diag::err_fe_expected_clang_command);
  1236. return 0;
  1237. }
  1238. const driver::ArgStringList &CCArgs = Cmd->getArguments();
  1239. CI.reset(new CompilerInvocation);
  1240. CompilerInvocation::CreateFromArgs(*CI,
  1241. const_cast<const char **>(CCArgs.data()),
  1242. const_cast<const char **>(CCArgs.data()) +
  1243. CCArgs.size(),
  1244. *Diags);
  1245. }
  1246. // Override any files that need remapping
  1247. for (unsigned I = 0; I != NumRemappedFiles; ++I)
  1248. CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
  1249. RemappedFiles[I].second);
  1250. // Override the resources path.
  1251. CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
  1252. // Check whether we should precompile the preamble and/or use chained PCH.
  1253. // FIXME: This is a temporary hack while we debug C++ chained PCH.
  1254. if (CI->getLangOpts().CPlusPlus) {
  1255. PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
  1256. if (PrecompilePreamble && !CXXChainedPCH &&
  1257. !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
  1258. PrecompilePreamble = false;
  1259. }
  1260. // Create the AST unit.
  1261. llvm::OwningPtr<ASTUnit> AST;
  1262. AST.reset(new ASTUnit(false));
  1263. ConfigureDiags(Diags, *AST, CaptureDiagnostics);
  1264. AST->Diagnostics = Diags;
  1265. AST->FileMgr.reset(new FileManager(FileSystemOptions()));
  1266. AST->OnlyLocalDecls = OnlyLocalDecls;
  1267. AST->CaptureDiagnostics = CaptureDiagnostics;
  1268. AST->CompleteTranslationUnit = CompleteTranslationUnit;
  1269. AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
  1270. AST->CacheCodeCompletionCoolDown = 1;
  1271. AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
  1272. AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
  1273. AST->StoredDiagnostics.swap(StoredDiagnostics);
  1274. AST->Invocation.reset(CI.take());
  1275. return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
  1276. }
  1277. bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
  1278. if (!Invocation.get())
  1279. return true;
  1280. SimpleTimer ParsingTimer(WantTiming);
  1281. ParsingTimer.setOutput("Reparsing " + getMainFileName());
  1282. // Remap files.
  1283. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  1284. for (PreprocessorOptions::remapped_file_buffer_iterator
  1285. R = PPOpts.remapped_file_buffer_begin(),
  1286. REnd = PPOpts.remapped_file_buffer_end();
  1287. R != REnd;
  1288. ++R) {
  1289. delete R->second;
  1290. }
  1291. Invocation->getPreprocessorOpts().clearRemappedFiles();
  1292. for (unsigned I = 0; I != NumRemappedFiles; ++I)
  1293. Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
  1294. RemappedFiles[I].second);
  1295. // If we have a preamble file lying around, or if we might try to
  1296. // build a precompiled preamble, do so now.
  1297. llvm::MemoryBuffer *OverrideMainBuffer = 0;
  1298. if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
  1299. OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
  1300. // Clear out the diagnostics state.
  1301. if (!OverrideMainBuffer) {
  1302. getDiagnostics().Reset();
  1303. ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
  1304. }
  1305. // Parse the sources
  1306. bool Result = Parse(OverrideMainBuffer);
  1307. if (ShouldCacheCodeCompletionResults) {
  1308. if (CacheCodeCompletionCoolDown > 0)
  1309. --CacheCodeCompletionCoolDown;
  1310. else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
  1311. CacheCodeCompletionResults();
  1312. }
  1313. return Result;
  1314. }
  1315. //----------------------------------------------------------------------------//
  1316. // Code completion
  1317. //----------------------------------------------------------------------------//
  1318. namespace {
  1319. /// \brief Code completion consumer that combines the cached code-completion
  1320. /// results from an ASTUnit with the code-completion results provided to it,
  1321. /// then passes the result on to
  1322. class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
  1323. unsigned NormalContexts;
  1324. ASTUnit &AST;
  1325. CodeCompleteConsumer &Next;
  1326. public:
  1327. AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
  1328. bool IncludeMacros, bool IncludeCodePatterns,
  1329. bool IncludeGlobals)
  1330. : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
  1331. Next.isOutputBinary()), AST(AST), Next(Next)
  1332. {
  1333. // Compute the set of contexts in which we will look when we don't have
  1334. // any information about the specific context.
  1335. NormalContexts
  1336. = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
  1337. | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
  1338. | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
  1339. | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
  1340. | (1 << (CodeCompletionContext::CCC_Statement - 1))
  1341. | (1 << (CodeCompletionContext::CCC_Expression - 1))
  1342. | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
  1343. | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
  1344. | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
  1345. | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
  1346. | (1 << (CodeCompletionContext::CCC_Recovery - 1));
  1347. if (AST.getASTContext().getLangOptions().CPlusPlus)
  1348. NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
  1349. | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
  1350. | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
  1351. }
  1352. virtual void ProcessCodeCompleteResults(Sema &S,
  1353. CodeCompletionContext Context,
  1354. CodeCompletionResult *Results,
  1355. unsigned NumResults);
  1356. virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
  1357. OverloadCandidate *Candidates,
  1358. unsigned NumCandidates) {
  1359. Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
  1360. }
  1361. };
  1362. }
  1363. /// \brief Helper function that computes which global names are hidden by the
  1364. /// local code-completion results.
  1365. static void CalculateHiddenNames(const CodeCompletionContext &Context,
  1366. CodeCompletionResult *Results,
  1367. unsigned NumResults,
  1368. ASTContext &Ctx,
  1369. llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
  1370. bool OnlyTagNames = false;
  1371. switch (Context.getKind()) {
  1372. case CodeCompletionContext::CCC_Recovery:
  1373. case CodeCompletionContext::CCC_TopLevel:
  1374. case CodeCompletionContext::CCC_ObjCInterface:
  1375. case CodeCompletionContext::CCC_ObjCImplementation:
  1376. case CodeCompletionContext::CCC_ObjCIvarList:
  1377. case CodeCompletionContext::CCC_ClassStructUnion:
  1378. case CodeCompletionContext::CCC_Statement:
  1379. case CodeCompletionContext::CCC_Expression:
  1380. case CodeCompletionContext::CCC_ObjCMessageReceiver:
  1381. case CodeCompletionContext::CCC_MemberAccess:
  1382. case CodeCompletionContext::CCC_Namespace:
  1383. case CodeCompletionContext::CCC_Type:
  1384. case CodeCompletionContext::CCC_Name:
  1385. case CodeCompletionContext::CCC_PotentiallyQualifiedName:
  1386. case CodeCompletionContext::CCC_ParenthesizedExpression:
  1387. break;
  1388. case CodeCompletionContext::CCC_EnumTag:
  1389. case CodeCompletionContext::CCC_UnionTag:
  1390. case CodeCompletionContext::CCC_ClassOrStructTag:
  1391. OnlyTagNames = true;
  1392. break;
  1393. case CodeCompletionContext::CCC_ObjCProtocolName:
  1394. case CodeCompletionContext::CCC_MacroName:
  1395. case CodeCompletionContext::CCC_MacroNameUse:
  1396. case CodeCompletionContext::CCC_PreprocessorExpression:
  1397. case CodeCompletionContext::CCC_PreprocessorDirective:
  1398. case CodeCompletionContext::CCC_NaturalLanguage:
  1399. case CodeCompletionContext::CCC_SelectorName:
  1400. case CodeCompletionContext::CCC_TypeQualifiers:
  1401. case CodeCompletionContext::CCC_Other:
  1402. // We're looking for nothing, or we're looking for names that cannot
  1403. // be hidden.
  1404. return;
  1405. }
  1406. typedef CodeCompletionResult Result;
  1407. for (unsigned I = 0; I != NumResults; ++I) {
  1408. if (Results[I].Kind != Result::RK_Declaration)
  1409. continue;
  1410. unsigned IDNS
  1411. = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
  1412. bool Hiding = false;
  1413. if (OnlyTagNames)
  1414. Hiding = (IDNS & Decl::IDNS_Tag);
  1415. else {
  1416. unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
  1417. Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
  1418. Decl::IDNS_NonMemberOperator);
  1419. if (Ctx.getLangOptions().CPlusPlus)
  1420. HiddenIDNS |= Decl::IDNS_Tag;
  1421. Hiding = (IDNS & HiddenIDNS);
  1422. }
  1423. if (!Hiding)
  1424. continue;
  1425. DeclarationName Name = Results[I].Declaration->getDeclName();
  1426. if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
  1427. HiddenNames.insert(Identifier->getName());
  1428. else
  1429. HiddenNames.insert(Name.getAsString());
  1430. }
  1431. }
  1432. void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
  1433. CodeCompletionContext Context,
  1434. CodeCompletionResult *Results,
  1435. unsigned NumResults) {
  1436. // Merge the results we were given with the results we cached.
  1437. bool AddedResult = false;
  1438. unsigned InContexts
  1439. = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
  1440. : (1 << (Context.getKind() - 1)));
  1441. // Contains the set of names that are hidden by "local" completion results.
  1442. llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
  1443. llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
  1444. typedef CodeCompletionResult Result;
  1445. llvm::SmallVector<Result, 8> AllResults;
  1446. for (ASTUnit::cached_completion_iterator
  1447. C = AST.cached_completion_begin(),
  1448. CEnd = AST.cached_completion_end();
  1449. C != CEnd; ++C) {
  1450. // If the context we are in matches any of the contexts we are
  1451. // interested in, we'll add this result.
  1452. if ((C->ShowInContexts & InContexts) == 0)
  1453. continue;
  1454. // If we haven't added any results previously, do so now.
  1455. if (!AddedResult) {
  1456. CalculateHiddenNames(Context, Results, NumResults, S.Context,
  1457. HiddenNames);
  1458. AllResults.insert(AllResults.end(), Results, Results + NumResults);
  1459. AddedResult = true;
  1460. }
  1461. // Determine whether this global completion result is hidden by a local
  1462. // completion result. If so, skip it.
  1463. if (C->Kind != CXCursor_MacroDefinition &&
  1464. HiddenNames.count(C->Completion->getTypedText()))
  1465. continue;
  1466. // Adjust priority based on similar type classes.
  1467. unsigned Priority = C->Priority;
  1468. CXCursorKind CursorKind = C->Kind;
  1469. CodeCompletionString *Completion = C->Completion;
  1470. if (!Context.getPreferredType().isNull()) {
  1471. if (C->Kind == CXCursor_MacroDefinition) {
  1472. Priority = getMacroUsagePriority(C->Completion->getTypedText(),
  1473. S.getLangOptions(),
  1474. Context.getPreferredType()->isAnyPointerType());
  1475. } else if (C->Type) {
  1476. CanQualType Expected
  1477. = S.Context.getCanonicalType(
  1478. Context.getPreferredType().getUnqualifiedType());
  1479. SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
  1480. if (ExpectedSTC == C->TypeClass) {
  1481. // We know this type is similar; check for an exact match.
  1482. llvm::StringMap<unsigned> &CachedCompletionTypes
  1483. = AST.getCachedCompletionTypes();
  1484. llvm::StringMap<unsigned>::iterator Pos
  1485. = CachedCompletionTypes.find(QualType(Expected).getAsString());
  1486. if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
  1487. Priority /= CCF_ExactTypeMatch;
  1488. else
  1489. Priority /= CCF_SimilarTypeMatch;
  1490. }
  1491. }
  1492. }
  1493. // Adjust the completion string, if required.
  1494. if (C->Kind == CXCursor_MacroDefinition &&
  1495. Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
  1496. // Create a new code-completion string that just contains the
  1497. // macro name, without its arguments.
  1498. Completion = new CodeCompletionString;
  1499. Completion->AddTypedTextChunk(C->Completion->getTypedText());
  1500. StringsToDestroy.push_back(Completion);
  1501. CursorKind = CXCursor_NotImplemented;
  1502. Priority = CCP_CodePattern;
  1503. }
  1504. AllResults.push_back(Result(Completion, Priority, CursorKind,
  1505. C->Availability));
  1506. }
  1507. // If we did not add any cached completion results, just forward the
  1508. // results we were given to the next consumer.
  1509. if (!AddedResult) {
  1510. Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
  1511. return;
  1512. }
  1513. Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
  1514. AllResults.size());
  1515. for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
  1516. delete StringsToDestroy[I];
  1517. }
  1518. void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
  1519. RemappedFile *RemappedFiles,
  1520. unsigned NumRemappedFiles,
  1521. bool IncludeMacros,
  1522. bool IncludeCodePatterns,
  1523. CodeCompleteConsumer &Consumer,
  1524. Diagnostic &Diag, LangOptions &LangOpts,
  1525. SourceManager &SourceMgr, FileManager &FileMgr,
  1526. llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
  1527. llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
  1528. if (!Invocation.get())
  1529. return;
  1530. SimpleTimer CompletionTimer(WantTiming);
  1531. CompletionTimer.setOutput("Code completion @ " + File + ":" +
  1532. llvm::Twine(Line) + ":" + llvm::Twine(Column));
  1533. CompilerInvocation CCInvocation(*Invocation);
  1534. FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
  1535. PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
  1536. FrontendOpts.ShowMacrosInCodeCompletion
  1537. = IncludeMacros && CachedCompletionResults.empty();
  1538. FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
  1539. FrontendOpts.ShowGlobalSymbolsInCodeCompletion
  1540. = CachedCompletionResults.empty();
  1541. FrontendOpts.CodeCompletionAt.FileName = File;
  1542. FrontendOpts.CodeCompletionAt.Line = Line;
  1543. FrontendOpts.CodeCompletionAt.Column = Column;
  1544. // Set the language options appropriately.
  1545. LangOpts = CCInvocation.getLangOpts();
  1546. CompilerInstance Clang;
  1547. Clang.setInvocation(&CCInvocation);
  1548. OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
  1549. // Set up diagnostics, capturing any diagnostics produced.
  1550. Clang.setDiagnostics(&Diag);
  1551. ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
  1552. CaptureDroppedDiagnostics Capture(true,
  1553. Clang.getDiagnostics(),
  1554. StoredDiagnostics);
  1555. // Create the target instance.
  1556. Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
  1557. Clang.getTargetOpts()));
  1558. if (!Clang.hasTarget()) {
  1559. Clang.takeInvocation();
  1560. return;
  1561. }
  1562. // Inform the target of the language options.
  1563. //
  1564. // FIXME: We shouldn't need to do this, the target should be immutable once
  1565. // created. This complexity should be lifted elsewhere.
  1566. Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
  1567. assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
  1568. "Invocation must have exactly one source file!");
  1569. assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
  1570. "FIXME: AST inputs not yet supported here!");
  1571. assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
  1572. "IR inputs not support here!");
  1573. // Use the source and file managers that we were given.
  1574. Clang.setFileManager(&FileMgr);
  1575. Clang.setSourceManager(&SourceMgr);
  1576. // Remap files.
  1577. PreprocessorOpts.clearRemappedFiles();
  1578. PreprocessorOpts.RetainRemappedFileBuffers = true;
  1579. for (unsigned I = 0; I != NumRemappedFiles; ++I) {
  1580. PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
  1581. RemappedFiles[I].second);
  1582. OwnedBuffers.push_back(RemappedFiles[I].second);
  1583. }
  1584. // Use the code completion consumer we were given, but adding any cached
  1585. // code-completion results.
  1586. AugmentedCodeCompleteConsumer
  1587. AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
  1588. FrontendOpts.ShowCodePatternsInCodeCompletion,
  1589. FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
  1590. Clang.setCodeCompletionConsumer(&AugmentedConsumer);
  1591. // If we have a precompiled preamble, try to use it. We only allow
  1592. // the use of the precompiled preamble if we're if the completion
  1593. // point is within the main file, after the end of the precompiled
  1594. // preamble.
  1595. llvm::MemoryBuffer *OverrideMainBuffer = 0;
  1596. if (!PreambleFile.empty()) {
  1597. using llvm::sys::FileStatus;
  1598. llvm::sys::PathWithStatus CompleteFilePath(File);
  1599. llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
  1600. if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
  1601. if (const FileStatus *MainStatus = MainPath.getFileStatus())
  1602. if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
  1603. OverrideMainBuffer
  1604. = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
  1605. Line - 1);
  1606. }
  1607. // If the main file has been overridden due to the use of a preamble,
  1608. // make that override happen and introduce the preamble.
  1609. StoredDiagnostics.insert(StoredDiagnostics.end(),
  1610. this->StoredDiagnostics.begin(),
  1611. this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
  1612. if (OverrideMainBuffer) {
  1613. PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
  1614. PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
  1615. PreprocessorOpts.PrecompiledPreambleBytes.second
  1616. = PreambleEndsAtStartOfLine;
  1617. PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
  1618. PreprocessorOpts.DisablePCHValidation = true;
  1619. // The stored diagnostics have the old source manager. Copy them
  1620. // to our output set of stored diagnostics, updating the source
  1621. // manager to the one we were given.
  1622. for (unsigned I = NumStoredDiagnosticsFromDriver,
  1623. N = this->StoredDiagnostics.size();
  1624. I < N; ++I) {
  1625. StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
  1626. FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
  1627. StoredDiagnostics[I].setLocation(Loc);
  1628. }
  1629. OwnedBuffers.push_back(OverrideMainBuffer);
  1630. } else {
  1631. PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
  1632. PreprocessorOpts.PrecompiledPreambleBytes.second = false;
  1633. }
  1634. llvm::OwningPtr<SyntaxOnlyAction> Act;
  1635. Act.reset(new SyntaxOnlyAction);
  1636. if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
  1637. Clang.getFrontendOpts().Inputs[0].first)) {
  1638. Act->Execute();
  1639. Act->EndSourceFile();
  1640. }
  1641. // Steal back our resources.
  1642. Clang.takeFileManager();
  1643. Clang.takeSourceManager();
  1644. Clang.takeInvocation();
  1645. Clang.takeCodeCompletionConsumer();
  1646. }
  1647. bool ASTUnit::Save(llvm::StringRef File) {
  1648. if (getDiagnostics().hasErrorOccurred())
  1649. return true;
  1650. // FIXME: Can we somehow regenerate the stat cache here, or do we need to
  1651. // unconditionally create a stat cache when we parse the file?
  1652. std::string ErrorInfo;
  1653. llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
  1654. llvm::raw_fd_ostream::F_Binary);
  1655. if (!ErrorInfo.empty() || Out.has_error())
  1656. return true;
  1657. std::vector<unsigned char> Buffer;
  1658. llvm::BitstreamWriter Stream(Buffer);
  1659. ASTWriter Writer(Stream);
  1660. Writer.WriteAST(getSema(), 0, 0);
  1661. // Write the generated bitstream to "Out".
  1662. if (!Buffer.empty())
  1663. Out.write((char *)&Buffer.front(), Buffer.size());
  1664. Out.close();
  1665. return Out.has_error();
  1666. }