PrecompiledPreamble.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. //===--- PrecompiledPreamble.cpp - Build precompiled preambles --*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Helper class to build precompiled preamble.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Frontend/PrecompiledPreamble.h"
  13. #include "clang/Basic/FileManager.h"
  14. #include "clang/Basic/LangStandard.h"
  15. #include "clang/Frontend/CompilerInstance.h"
  16. #include "clang/Frontend/CompilerInvocation.h"
  17. #include "clang/Frontend/FrontendActions.h"
  18. #include "clang/Frontend/FrontendOptions.h"
  19. #include "clang/Lex/HeaderSearch.h"
  20. #include "clang/Lex/Lexer.h"
  21. #include "clang/Lex/Preprocessor.h"
  22. #include "clang/Lex/PreprocessorOptions.h"
  23. #include "clang/Serialization/ASTWriter.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/ADT/StringSet.h"
  26. #include "llvm/ADT/iterator_range.h"
  27. #include "llvm/Config/llvm-config.h"
  28. #include "llvm/Support/CrashRecoveryContext.h"
  29. #include "llvm/Support/FileSystem.h"
  30. #include "llvm/Support/Path.h"
  31. #include "llvm/Support/Process.h"
  32. #include "llvm/Support/VirtualFileSystem.h"
  33. #include <limits>
  34. #include <mutex>
  35. #include <utility>
  36. using namespace clang;
  37. namespace {
  38. StringRef getInMemoryPreamblePath() {
  39. #if defined(LLVM_ON_UNIX)
  40. return "/__clang_tmp/___clang_inmemory_preamble___";
  41. #elif defined(_WIN32)
  42. return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
  43. #else
  44. #warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
  45. return "/__clang_tmp/___clang_inmemory_preamble___";
  46. #endif
  47. }
  48. IntrusiveRefCntPtr<llvm::vfs::FileSystem>
  49. createVFSOverlayForPreamblePCH(StringRef PCHFilename,
  50. std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
  51. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
  52. // We want only the PCH file from the real filesystem to be available,
  53. // so we create an in-memory VFS with just that and overlay it on top.
  54. IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> PCHFS(
  55. new llvm::vfs::InMemoryFileSystem());
  56. PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
  57. IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> Overlay(
  58. new llvm::vfs::OverlayFileSystem(VFS));
  59. Overlay->pushOverlay(PCHFS);
  60. return Overlay;
  61. }
  62. class PreambleDependencyCollector : public DependencyCollector {
  63. public:
  64. // We want to collect all dependencies for correctness. Avoiding the real
  65. // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
  66. // but there is no way to distinguish between those and the ones that can be
  67. // spuriously added by '-isystem' (e.g. to suppress warnings from those
  68. // headers).
  69. bool needSystemDependencies() override { return true; }
  70. };
  71. // Collects files whose existence would invalidate the preamble.
  72. // Collecting *all* of these would make validating it too slow though, so we
  73. // just find all the candidates for 'file not found' diagnostics.
  74. //
  75. // A caveat that may be significant for generated files: we'll omit files under
  76. // search path entries whose roots don't exist when the preamble is built.
  77. // These are pruned by InitHeaderSearch and so we don't see the search path.
  78. // It would be nice to include them but we don't want to duplicate all the rest
  79. // of the InitHeaderSearch logic to reconstruct them.
  80. class MissingFileCollector : public PPCallbacks {
  81. llvm::StringSet<> &Out;
  82. const HeaderSearch &Search;
  83. const SourceManager &SM;
  84. public:
  85. MissingFileCollector(llvm::StringSet<> &Out, const HeaderSearch &Search,
  86. const SourceManager &SM)
  87. : Out(Out), Search(Search), SM(SM) {}
  88. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  89. StringRef FileName, bool IsAngled,
  90. CharSourceRange FilenameRange,
  91. OptionalFileEntryRef File, StringRef SearchPath,
  92. StringRef RelativePath, const Module *Imported,
  93. SrcMgr::CharacteristicKind FileType) override {
  94. // File is std::nullopt if it wasn't found.
  95. // (We have some false negatives if PP recovered e.g. <foo> -> "foo")
  96. if (File)
  97. return;
  98. // If it's a rare absolute include, we know the full path already.
  99. if (llvm::sys::path::is_absolute(FileName)) {
  100. Out.insert(FileName);
  101. return;
  102. }
  103. // Reconstruct the filenames that would satisfy this directive...
  104. llvm::SmallString<256> Buf;
  105. auto NotFoundRelativeTo = [&](const DirectoryEntry *DE) {
  106. Buf = DE->getName();
  107. llvm::sys::path::append(Buf, FileName);
  108. llvm::sys::path::remove_dots(Buf, /*remove_dot_dot=*/true);
  109. Out.insert(Buf);
  110. };
  111. // ...relative to the including file.
  112. if (!IsAngled) {
  113. if (const FileEntry *IncludingFile =
  114. SM.getFileEntryForID(SM.getFileID(IncludeTok.getLocation())))
  115. if (IncludingFile->getDir())
  116. NotFoundRelativeTo(IncludingFile->getDir());
  117. }
  118. // ...relative to the search paths.
  119. for (const auto &Dir : llvm::make_range(
  120. IsAngled ? Search.angled_dir_begin() : Search.search_dir_begin(),
  121. Search.search_dir_end())) {
  122. // No support for frameworks or header maps yet.
  123. if (Dir.isNormalDir())
  124. NotFoundRelativeTo(Dir.getDir());
  125. }
  126. }
  127. };
  128. /// Keeps a track of files to be deleted in destructor.
  129. class TemporaryFiles {
  130. public:
  131. // A static instance to be used by all clients.
  132. static TemporaryFiles &getInstance();
  133. private:
  134. // Disallow constructing the class directly.
  135. TemporaryFiles() = default;
  136. // Disallow copy.
  137. TemporaryFiles(const TemporaryFiles &) = delete;
  138. public:
  139. ~TemporaryFiles();
  140. /// Adds \p File to a set of tracked files.
  141. void addFile(StringRef File);
  142. /// Remove \p File from disk and from the set of tracked files.
  143. void removeFile(StringRef File);
  144. private:
  145. std::mutex Mutex;
  146. llvm::StringSet<> Files;
  147. };
  148. TemporaryFiles &TemporaryFiles::getInstance() {
  149. static TemporaryFiles Instance;
  150. return Instance;
  151. }
  152. TemporaryFiles::~TemporaryFiles() {
  153. std::lock_guard<std::mutex> Guard(Mutex);
  154. for (const auto &File : Files)
  155. llvm::sys::fs::remove(File.getKey());
  156. }
  157. void TemporaryFiles::addFile(StringRef File) {
  158. std::lock_guard<std::mutex> Guard(Mutex);
  159. auto IsInserted = Files.insert(File).second;
  160. (void)IsInserted;
  161. assert(IsInserted && "File has already been added");
  162. }
  163. void TemporaryFiles::removeFile(StringRef File) {
  164. std::lock_guard<std::mutex> Guard(Mutex);
  165. auto WasPresent = Files.erase(File);
  166. (void)WasPresent;
  167. assert(WasPresent && "File was not tracked");
  168. llvm::sys::fs::remove(File);
  169. }
  170. // A temp file that would be deleted on destructor call. If destructor is not
  171. // called for any reason, the file will be deleted at static objects'
  172. // destruction.
  173. // An assertion will fire if two TempPCHFiles are created with the same name,
  174. // so it's not intended to be used outside preamble-handling.
  175. class TempPCHFile {
  176. public:
  177. // A main method used to construct TempPCHFile.
  178. static std::unique_ptr<TempPCHFile> create() {
  179. // FIXME: This is a hack so that we can override the preamble file during
  180. // crash-recovery testing, which is the only case where the preamble files
  181. // are not necessarily cleaned up.
  182. if (const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"))
  183. return std::unique_ptr<TempPCHFile>(new TempPCHFile(TmpFile));
  184. llvm::SmallString<64> File;
  185. // Using a version of createTemporaryFile with a file descriptor guarantees
  186. // that we would never get a race condition in a multi-threaded setting
  187. // (i.e., multiple threads getting the same temporary path).
  188. int FD;
  189. if (auto EC =
  190. llvm::sys::fs::createTemporaryFile("preamble", "pch", FD, File))
  191. return nullptr;
  192. // We only needed to make sure the file exists, close the file right away.
  193. llvm::sys::Process::SafelyCloseFileDescriptor(FD);
  194. return std::unique_ptr<TempPCHFile>(new TempPCHFile(File.str().str()));
  195. }
  196. TempPCHFile &operator=(const TempPCHFile &) = delete;
  197. TempPCHFile(const TempPCHFile &) = delete;
  198. ~TempPCHFile() { TemporaryFiles::getInstance().removeFile(FilePath); };
  199. /// A path where temporary file is stored.
  200. llvm::StringRef getFilePath() const { return FilePath; };
  201. private:
  202. TempPCHFile(std::string FilePath) : FilePath(std::move(FilePath)) {
  203. TemporaryFiles::getInstance().addFile(this->FilePath);
  204. }
  205. std::string FilePath;
  206. };
  207. class PrecompilePreambleAction : public ASTFrontendAction {
  208. public:
  209. PrecompilePreambleAction(std::shared_ptr<PCHBuffer> Buffer, bool WritePCHFile,
  210. PreambleCallbacks &Callbacks)
  211. : Buffer(std::move(Buffer)), WritePCHFile(WritePCHFile),
  212. Callbacks(Callbacks) {}
  213. std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
  214. StringRef InFile) override;
  215. bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
  216. void setEmittedPreamblePCH(ASTWriter &Writer) {
  217. if (FileOS) {
  218. *FileOS << Buffer->Data;
  219. // Make sure it hits disk now.
  220. FileOS.reset();
  221. }
  222. this->HasEmittedPreamblePCH = true;
  223. Callbacks.AfterPCHEmitted(Writer);
  224. }
  225. bool BeginSourceFileAction(CompilerInstance &CI) override {
  226. assert(CI.getLangOpts().CompilingPCH);
  227. return ASTFrontendAction::BeginSourceFileAction(CI);
  228. }
  229. bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
  230. bool hasCodeCompletionSupport() const override { return false; }
  231. bool hasASTFileSupport() const override { return false; }
  232. TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
  233. private:
  234. friend class PrecompilePreambleConsumer;
  235. bool HasEmittedPreamblePCH = false;
  236. std::shared_ptr<PCHBuffer> Buffer;
  237. bool WritePCHFile; // otherwise the PCH is written into the PCHBuffer only.
  238. std::unique_ptr<llvm::raw_pwrite_stream> FileOS; // null if in-memory
  239. PreambleCallbacks &Callbacks;
  240. };
  241. class PrecompilePreambleConsumer : public PCHGenerator {
  242. public:
  243. PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
  244. const Preprocessor &PP,
  245. InMemoryModuleCache &ModuleCache,
  246. StringRef isysroot,
  247. std::shared_ptr<PCHBuffer> Buffer)
  248. : PCHGenerator(PP, ModuleCache, "", isysroot, std::move(Buffer),
  249. ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
  250. /*AllowASTWithErrors=*/true),
  251. Action(Action) {}
  252. bool HandleTopLevelDecl(DeclGroupRef DG) override {
  253. Action.Callbacks.HandleTopLevelDecl(DG);
  254. return true;
  255. }
  256. void HandleTranslationUnit(ASTContext &Ctx) override {
  257. PCHGenerator::HandleTranslationUnit(Ctx);
  258. if (!hasEmittedPCH())
  259. return;
  260. Action.setEmittedPreamblePCH(getWriter());
  261. }
  262. bool shouldSkipFunctionBody(Decl *D) override {
  263. return Action.Callbacks.shouldSkipFunctionBody(D);
  264. }
  265. private:
  266. PrecompilePreambleAction &Action;
  267. };
  268. std::unique_ptr<ASTConsumer>
  269. PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
  270. StringRef InFile) {
  271. std::string Sysroot;
  272. if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
  273. return nullptr;
  274. if (WritePCHFile) {
  275. std::string OutputFile; // unused
  276. FileOS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
  277. if (!FileOS)
  278. return nullptr;
  279. }
  280. if (!CI.getFrontendOpts().RelocatablePCH)
  281. Sysroot.clear();
  282. return std::make_unique<PrecompilePreambleConsumer>(
  283. *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, Buffer);
  284. }
  285. template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
  286. if (!Val)
  287. return false;
  288. Output = std::move(*Val);
  289. return true;
  290. }
  291. } // namespace
  292. PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
  293. const llvm::MemoryBufferRef &Buffer,
  294. unsigned MaxLines) {
  295. return Lexer::ComputePreamble(Buffer.getBuffer(), LangOpts, MaxLines);
  296. }
  297. class PrecompiledPreamble::PCHStorage {
  298. public:
  299. static std::unique_ptr<PCHStorage> file(std::unique_ptr<TempPCHFile> File) {
  300. assert(File);
  301. std::unique_ptr<PCHStorage> S(new PCHStorage());
  302. S->File = std::move(File);
  303. return S;
  304. }
  305. static std::unique_ptr<PCHStorage> inMemory(std::shared_ptr<PCHBuffer> Buf) {
  306. std::unique_ptr<PCHStorage> S(new PCHStorage());
  307. S->Memory = std::move(Buf);
  308. return S;
  309. }
  310. enum class Kind { InMemory, TempFile };
  311. Kind getKind() const {
  312. if (Memory)
  313. return Kind::InMemory;
  314. if (File)
  315. return Kind::TempFile;
  316. llvm_unreachable("Neither Memory nor File?");
  317. }
  318. llvm::StringRef filePath() const {
  319. assert(getKind() == Kind::TempFile);
  320. return File->getFilePath();
  321. }
  322. llvm::StringRef memoryContents() const {
  323. assert(getKind() == Kind::InMemory);
  324. return StringRef(Memory->Data.data(), Memory->Data.size());
  325. }
  326. // Shrink in-memory buffers to fit.
  327. // This incurs a copy, but preambles tend to be long-lived.
  328. // Only safe to call once nothing can alias the buffer.
  329. void shrink() {
  330. if (!Memory)
  331. return;
  332. Memory->Data = decltype(Memory->Data)(Memory->Data);
  333. }
  334. private:
  335. PCHStorage() = default;
  336. PCHStorage(const PCHStorage &) = delete;
  337. PCHStorage &operator=(const PCHStorage &) = delete;
  338. std::shared_ptr<PCHBuffer> Memory;
  339. std::unique_ptr<TempPCHFile> File;
  340. };
  341. PrecompiledPreamble::~PrecompiledPreamble() = default;
  342. PrecompiledPreamble::PrecompiledPreamble(PrecompiledPreamble &&) = default;
  343. PrecompiledPreamble &
  344. PrecompiledPreamble::operator=(PrecompiledPreamble &&) = default;
  345. llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
  346. const CompilerInvocation &Invocation,
  347. const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
  348. DiagnosticsEngine &Diagnostics,
  349. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
  350. std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
  351. PreambleCallbacks &Callbacks) {
  352. assert(VFS && "VFS is null");
  353. auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
  354. FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
  355. PreprocessorOptions &PreprocessorOpts =
  356. PreambleInvocation->getPreprocessorOpts();
  357. std::shared_ptr<PCHBuffer> Buffer = std::make_shared<PCHBuffer>();
  358. std::unique_ptr<PCHStorage> Storage;
  359. if (StoreInMemory) {
  360. Storage = PCHStorage::inMemory(Buffer);
  361. } else {
  362. // Create a temporary file for the precompiled preamble. In rare
  363. // circumstances, this can fail.
  364. std::unique_ptr<TempPCHFile> PreamblePCHFile = TempPCHFile::create();
  365. if (!PreamblePCHFile)
  366. return BuildPreambleError::CouldntCreateTempFile;
  367. Storage = PCHStorage::file(std::move(PreamblePCHFile));
  368. }
  369. // Save the preamble text for later; we'll need to compare against it for
  370. // subsequent reparses.
  371. std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
  372. MainFileBuffer->getBufferStart() +
  373. Bounds.Size);
  374. bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
  375. // Tell the compiler invocation to generate a temporary precompiled header.
  376. FrontendOpts.ProgramAction = frontend::GeneratePCH;
  377. FrontendOpts.OutputFile = std::string(
  378. StoreInMemory ? getInMemoryPreamblePath() : Storage->filePath());
  379. PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
  380. PreprocessorOpts.PrecompiledPreambleBytes.second = false;
  381. // Inform preprocessor to record conditional stack when building the preamble.
  382. PreprocessorOpts.GeneratePreamble = true;
  383. // Create the compiler instance to use for building the precompiled preamble.
  384. std::unique_ptr<CompilerInstance> Clang(
  385. new CompilerInstance(std::move(PCHContainerOps)));
  386. // Recover resources if we crash before exiting this method.
  387. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
  388. Clang.get());
  389. Clang->setInvocation(std::move(PreambleInvocation));
  390. Clang->setDiagnostics(&Diagnostics);
  391. // Create the target instance.
  392. if (!Clang->createTarget())
  393. return BuildPreambleError::CouldntCreateTargetInfo;
  394. if (Clang->getFrontendOpts().Inputs.size() != 1 ||
  395. Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
  396. InputKind::Source ||
  397. Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() ==
  398. Language::LLVM_IR) {
  399. return BuildPreambleError::BadInputs;
  400. }
  401. // Clear out old caches and data.
  402. Diagnostics.Reset();
  403. ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
  404. VFS =
  405. createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
  406. // Create a file manager object to provide access to and cache the filesystem.
  407. Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
  408. // Create the source manager.
  409. Clang->setSourceManager(
  410. new SourceManager(Diagnostics, Clang->getFileManager()));
  411. auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
  412. Clang->addDependencyCollector(PreambleDepCollector);
  413. Clang->getLangOpts().CompilingPCH = true;
  414. // Remap the main source file to the preamble buffer.
  415. StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
  416. auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
  417. MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
  418. if (PreprocessorOpts.RetainRemappedFileBuffers) {
  419. // MainFileBuffer will be deleted by unique_ptr after leaving the method.
  420. PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
  421. } else {
  422. // In that case, remapped buffer will be deleted by CompilerInstance on
  423. // BeginSourceFile, so we call release() to avoid double deletion.
  424. PreprocessorOpts.addRemappedFile(MainFilePath,
  425. PreambleInputBuffer.release());
  426. }
  427. auto Act = std::make_unique<PrecompilePreambleAction>(
  428. std::move(Buffer),
  429. /*WritePCHFile=*/Storage->getKind() == PCHStorage::Kind::TempFile,
  430. Callbacks);
  431. if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
  432. return BuildPreambleError::BeginSourceFileFailed;
  433. // Performed after BeginSourceFile to ensure Clang->Preprocessor can be
  434. // referenced in the callback.
  435. Callbacks.BeforeExecute(*Clang);
  436. std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
  437. Callbacks.createPPCallbacks();
  438. if (DelegatedPPCallbacks)
  439. Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
  440. if (auto CommentHandler = Callbacks.getCommentHandler())
  441. Clang->getPreprocessor().addCommentHandler(CommentHandler);
  442. llvm::StringSet<> MissingFiles;
  443. Clang->getPreprocessor().addPPCallbacks(
  444. std::make_unique<MissingFileCollector>(
  445. MissingFiles, Clang->getPreprocessor().getHeaderSearchInfo(),
  446. Clang->getSourceManager()));
  447. if (llvm::Error Err = Act->Execute())
  448. return errorToErrorCode(std::move(Err));
  449. // Run the callbacks.
  450. Callbacks.AfterExecute(*Clang);
  451. Act->EndSourceFile();
  452. if (!Act->hasEmittedPreamblePCH())
  453. return BuildPreambleError::CouldntEmitPCH;
  454. Act.reset(); // Frees the PCH buffer, unless Storage keeps it in memory.
  455. // Keep track of all of the files that the source manager knows about,
  456. // so we can verify whether they have changed or not.
  457. llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
  458. SourceManager &SourceMgr = Clang->getSourceManager();
  459. for (auto &Filename : PreambleDepCollector->getDependencies()) {
  460. auto FileOrErr = Clang->getFileManager().getFile(Filename);
  461. if (!FileOrErr ||
  462. *FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
  463. continue;
  464. auto File = *FileOrErr;
  465. if (time_t ModTime = File->getModificationTime()) {
  466. FilesInPreamble[File->getName()] =
  467. PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
  468. ModTime);
  469. } else {
  470. llvm::MemoryBufferRef Buffer =
  471. SourceMgr.getMemoryBufferForFileOrFake(File);
  472. FilesInPreamble[File->getName()] =
  473. PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
  474. }
  475. }
  476. // Shrinking the storage requires extra temporary memory.
  477. // Destroying clang first reduces peak memory usage.
  478. CICleanup.unregister();
  479. Clang.reset();
  480. Storage->shrink();
  481. return PrecompiledPreamble(
  482. std::move(Storage), std::move(PreambleBytes), PreambleEndsAtStartOfLine,
  483. std::move(FilesInPreamble), std::move(MissingFiles));
  484. }
  485. PreambleBounds PrecompiledPreamble::getBounds() const {
  486. return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
  487. }
  488. std::size_t PrecompiledPreamble::getSize() const {
  489. switch (Storage->getKind()) {
  490. case PCHStorage::Kind::InMemory:
  491. return Storage->memoryContents().size();
  492. case PCHStorage::Kind::TempFile: {
  493. uint64_t Result;
  494. if (llvm::sys::fs::file_size(Storage->filePath(), Result))
  495. return 0;
  496. assert(Result <= std::numeric_limits<std::size_t>::max() &&
  497. "file size did not fit into size_t");
  498. return Result;
  499. }
  500. }
  501. llvm_unreachable("Unhandled storage kind");
  502. }
  503. bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
  504. const llvm::MemoryBufferRef &MainFileBuffer,
  505. PreambleBounds Bounds,
  506. llvm::vfs::FileSystem &VFS) const {
  507. assert(
  508. Bounds.Size <= MainFileBuffer.getBufferSize() &&
  509. "Buffer is too large. Bounds were calculated from a different buffer?");
  510. auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
  511. PreprocessorOptions &PreprocessorOpts =
  512. PreambleInvocation->getPreprocessorOpts();
  513. // We've previously computed a preamble. Check whether we have the same
  514. // preamble now that we did before, and that there's enough space in
  515. // the main-file buffer within the precompiled preamble to fit the
  516. // new main file.
  517. if (PreambleBytes.size() != Bounds.Size ||
  518. PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
  519. !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
  520. MainFileBuffer.getBuffer().begin()))
  521. return false;
  522. // The preamble has not changed. We may be able to re-use the precompiled
  523. // preamble.
  524. // Check that none of the files used by the preamble have changed.
  525. // First, make a record of those files that have been overridden via
  526. // remapping or unsaved_files.
  527. std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
  528. llvm::StringSet<> OverriddenAbsPaths; // Either by buffers or files.
  529. for (const auto &R : PreprocessorOpts.RemappedFiles) {
  530. llvm::vfs::Status Status;
  531. if (!moveOnNoError(VFS.status(R.second), Status)) {
  532. // If we can't stat the file we're remapping to, assume that something
  533. // horrible happened.
  534. return false;
  535. }
  536. // If a mapped file was previously missing, then it has changed.
  537. llvm::SmallString<128> MappedPath(R.first);
  538. if (!VFS.makeAbsolute(MappedPath))
  539. OverriddenAbsPaths.insert(MappedPath);
  540. OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
  541. Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
  542. }
  543. // OverridenFileBuffers tracks only the files not found in VFS.
  544. llvm::StringMap<PreambleFileHash> OverridenFileBuffers;
  545. for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
  546. const PrecompiledPreamble::PreambleFileHash PreambleHash =
  547. PreambleFileHash::createForMemoryBuffer(RB.second->getMemBufferRef());
  548. llvm::vfs::Status Status;
  549. if (moveOnNoError(VFS.status(RB.first), Status))
  550. OverriddenFiles[Status.getUniqueID()] = PreambleHash;
  551. else
  552. OverridenFileBuffers[RB.first] = PreambleHash;
  553. llvm::SmallString<128> MappedPath(RB.first);
  554. if (!VFS.makeAbsolute(MappedPath))
  555. OverriddenAbsPaths.insert(MappedPath);
  556. }
  557. // Check whether anything has changed.
  558. for (const auto &F : FilesInPreamble) {
  559. auto OverridenFileBuffer = OverridenFileBuffers.find(F.first());
  560. if (OverridenFileBuffer != OverridenFileBuffers.end()) {
  561. // The file's buffer was remapped and the file was not found in VFS.
  562. // Check whether it matches up with the previous mapping.
  563. if (OverridenFileBuffer->second != F.second)
  564. return false;
  565. continue;
  566. }
  567. llvm::vfs::Status Status;
  568. if (!moveOnNoError(VFS.status(F.first()), Status)) {
  569. // If the file's buffer is not remapped and we can't stat it,
  570. // assume that something horrible happened.
  571. return false;
  572. }
  573. std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
  574. OverriddenFiles.find(Status.getUniqueID());
  575. if (Overridden != OverriddenFiles.end()) {
  576. // This file was remapped; check whether the newly-mapped file
  577. // matches up with the previous mapping.
  578. if (Overridden->second != F.second)
  579. return false;
  580. continue;
  581. }
  582. // Neither the file's buffer nor the file itself was remapped;
  583. // check whether it has changed on disk.
  584. if (Status.getSize() != uint64_t(F.second.Size) ||
  585. llvm::sys::toTimeT(Status.getLastModificationTime()) !=
  586. F.second.ModTime)
  587. return false;
  588. }
  589. for (const auto &F : MissingFiles) {
  590. // A missing file may be "provided" by an override buffer or file.
  591. if (OverriddenAbsPaths.count(F.getKey()))
  592. return false;
  593. // If a file previously recorded as missing exists as a regular file, then
  594. // consider the preamble out-of-date.
  595. if (auto Status = VFS.status(F.getKey())) {
  596. if (Status->isRegularFile())
  597. return false;
  598. }
  599. }
  600. return true;
  601. }
  602. void PrecompiledPreamble::AddImplicitPreamble(
  603. CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
  604. llvm::MemoryBuffer *MainFileBuffer) const {
  605. PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
  606. configurePreamble(Bounds, CI, VFS, MainFileBuffer);
  607. }
  608. void PrecompiledPreamble::OverridePreamble(
  609. CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
  610. llvm::MemoryBuffer *MainFileBuffer) const {
  611. auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), *MainFileBuffer, 0);
  612. configurePreamble(Bounds, CI, VFS, MainFileBuffer);
  613. }
  614. PrecompiledPreamble::PrecompiledPreamble(
  615. std::unique_ptr<PCHStorage> Storage, std::vector<char> PreambleBytes,
  616. bool PreambleEndsAtStartOfLine,
  617. llvm::StringMap<PreambleFileHash> FilesInPreamble,
  618. llvm::StringSet<> MissingFiles)
  619. : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
  620. MissingFiles(std::move(MissingFiles)),
  621. PreambleBytes(std::move(PreambleBytes)),
  622. PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
  623. assert(this->Storage != nullptr);
  624. }
  625. PrecompiledPreamble::PreambleFileHash
  626. PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
  627. time_t ModTime) {
  628. PreambleFileHash Result;
  629. Result.Size = Size;
  630. Result.ModTime = ModTime;
  631. Result.MD5 = {};
  632. return Result;
  633. }
  634. PrecompiledPreamble::PreambleFileHash
  635. PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
  636. const llvm::MemoryBufferRef &Buffer) {
  637. PreambleFileHash Result;
  638. Result.Size = Buffer.getBufferSize();
  639. Result.ModTime = 0;
  640. llvm::MD5 MD5Ctx;
  641. MD5Ctx.update(Buffer.getBuffer().data());
  642. MD5Ctx.final(Result.MD5);
  643. return Result;
  644. }
  645. void PrecompiledPreamble::configurePreamble(
  646. PreambleBounds Bounds, CompilerInvocation &CI,
  647. IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
  648. llvm::MemoryBuffer *MainFileBuffer) const {
  649. assert(VFS);
  650. auto &PreprocessorOpts = CI.getPreprocessorOpts();
  651. // Remap main file to point to MainFileBuffer.
  652. auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
  653. PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
  654. // Configure ImpicitPCHInclude.
  655. PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
  656. PreprocessorOpts.PrecompiledPreambleBytes.second =
  657. Bounds.PreambleEndsAtStartOfLine;
  658. PreprocessorOpts.DisablePCHOrModuleValidation =
  659. DisableValidationForModuleKind::PCH;
  660. // Don't bother generating the long version of the predefines buffer.
  661. // The preamble is going to overwrite it anyway.
  662. PreprocessorOpts.UsePredefines = false;
  663. setupPreambleStorage(*Storage, PreprocessorOpts, VFS);
  664. }
  665. void PrecompiledPreamble::setupPreambleStorage(
  666. const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
  667. IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) {
  668. if (Storage.getKind() == PCHStorage::Kind::TempFile) {
  669. llvm::StringRef PCHPath = Storage.filePath();
  670. PreprocessorOpts.ImplicitPCHInclude = PCHPath.str();
  671. // Make sure we can access the PCH file even if we're using a VFS
  672. IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS =
  673. llvm::vfs::getRealFileSystem();
  674. if (VFS == RealFS || VFS->exists(PCHPath))
  675. return;
  676. auto Buf = RealFS->getBufferForFile(PCHPath);
  677. if (!Buf) {
  678. // We can't read the file even from RealFS, this is clearly an error,
  679. // but we'll just leave the current VFS as is and let clang's code
  680. // figure out what to do with missing PCH.
  681. return;
  682. }
  683. // We have a slight inconsistency here -- we're using the VFS to
  684. // read files, but the PCH was generated in the real file system.
  685. VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
  686. } else {
  687. assert(Storage.getKind() == PCHStorage::Kind::InMemory);
  688. // For in-memory preamble, we have to provide a VFS overlay that makes it
  689. // accessible.
  690. StringRef PCHPath = getInMemoryPreamblePath();
  691. PreprocessorOpts.ImplicitPCHInclude = std::string(PCHPath);
  692. auto Buf = llvm::MemoryBuffer::getMemBuffer(
  693. Storage.memoryContents(), PCHPath, /*RequiresNullTerminator=*/false);
  694. VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
  695. }
  696. }
  697. void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
  698. void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
  699. void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
  700. void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
  701. std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
  702. return nullptr;
  703. }
  704. CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
  705. static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
  706. std::error_code clang::make_error_code(BuildPreambleError Error) {
  707. return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
  708. }
  709. const char *BuildPreambleErrorCategory::name() const noexcept {
  710. return "build-preamble.error";
  711. }
  712. std::string BuildPreambleErrorCategory::message(int condition) const {
  713. switch (static_cast<BuildPreambleError>(condition)) {
  714. case BuildPreambleError::CouldntCreateTempFile:
  715. return "Could not create temporary file for PCH";
  716. case BuildPreambleError::CouldntCreateTargetInfo:
  717. return "CreateTargetInfo() return null";
  718. case BuildPreambleError::BeginSourceFileFailed:
  719. return "BeginSourceFile() return an error";
  720. case BuildPreambleError::CouldntEmitPCH:
  721. return "Could not emit PCH";
  722. case BuildPreambleError::BadInputs:
  723. return "Command line arguments must contain exactly one source file";
  724. }
  725. llvm_unreachable("unexpected BuildPreambleError");
  726. }