ASTUnit.cpp 74 KB

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