PrecompiledPreamble.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  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/AST/DeclObjC.h"
  14. #include "clang/Basic/LangStandard.h"
  15. #include "clang/Basic/TargetInfo.h"
  16. #include "clang/Frontend/CompilerInstance.h"
  17. #include "clang/Frontend/CompilerInvocation.h"
  18. #include "clang/Frontend/FrontendActions.h"
  19. #include "clang/Frontend/FrontendOptions.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/StringExtras.h"
  25. #include "llvm/ADT/StringSet.h"
  26. #include "llvm/Config/llvm-config.h"
  27. #include "llvm/Support/CrashRecoveryContext.h"
  28. #include "llvm/Support/FileSystem.h"
  29. #include "llvm/Support/Process.h"
  30. #include "llvm/Support/VirtualFileSystem.h"
  31. #include <limits>
  32. #include <mutex>
  33. #include <utility>
  34. using namespace clang;
  35. namespace {
  36. StringRef getInMemoryPreamblePath() {
  37. #if defined(LLVM_ON_UNIX)
  38. return "/__clang_tmp/___clang_inmemory_preamble___";
  39. #elif defined(_WIN32)
  40. return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
  41. #else
  42. #warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
  43. return "/__clang_tmp/___clang_inmemory_preamble___";
  44. #endif
  45. }
  46. IntrusiveRefCntPtr<llvm::vfs::FileSystem>
  47. createVFSOverlayForPreamblePCH(StringRef PCHFilename,
  48. std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
  49. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
  50. // We want only the PCH file from the real filesystem to be available,
  51. // so we create an in-memory VFS with just that and overlay it on top.
  52. IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> PCHFS(
  53. new llvm::vfs::InMemoryFileSystem());
  54. PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
  55. IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> Overlay(
  56. new llvm::vfs::OverlayFileSystem(VFS));
  57. Overlay->pushOverlay(PCHFS);
  58. return Overlay;
  59. }
  60. class PreambleDependencyCollector : public DependencyCollector {
  61. public:
  62. // We want to collect all dependencies for correctness. Avoiding the real
  63. // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
  64. // but there is no way to distinguish between those and the ones that can be
  65. // spuriously added by '-isystem' (e.g. to suppress warnings from those
  66. // headers).
  67. bool needSystemDependencies() override { return true; }
  68. };
  69. /// Keeps a track of files to be deleted in destructor.
  70. class TemporaryFiles {
  71. public:
  72. // A static instance to be used by all clients.
  73. static TemporaryFiles &getInstance();
  74. private:
  75. // Disallow constructing the class directly.
  76. TemporaryFiles() = default;
  77. // Disallow copy.
  78. TemporaryFiles(const TemporaryFiles &) = delete;
  79. public:
  80. ~TemporaryFiles();
  81. /// Adds \p File to a set of tracked files.
  82. void addFile(StringRef File);
  83. /// Remove \p File from disk and from the set of tracked files.
  84. void removeFile(StringRef File);
  85. private:
  86. std::mutex Mutex;
  87. llvm::StringSet<> Files;
  88. };
  89. TemporaryFiles &TemporaryFiles::getInstance() {
  90. static TemporaryFiles Instance;
  91. return Instance;
  92. }
  93. TemporaryFiles::~TemporaryFiles() {
  94. std::lock_guard<std::mutex> Guard(Mutex);
  95. for (const auto &File : Files)
  96. llvm::sys::fs::remove(File.getKey());
  97. }
  98. void TemporaryFiles::addFile(StringRef File) {
  99. std::lock_guard<std::mutex> Guard(Mutex);
  100. auto IsInserted = Files.insert(File).second;
  101. (void)IsInserted;
  102. assert(IsInserted && "File has already been added");
  103. }
  104. void TemporaryFiles::removeFile(StringRef File) {
  105. std::lock_guard<std::mutex> Guard(Mutex);
  106. auto WasPresent = Files.erase(File);
  107. (void)WasPresent;
  108. assert(WasPresent && "File was not tracked");
  109. llvm::sys::fs::remove(File);
  110. }
  111. class PrecompilePreambleAction : public ASTFrontendAction {
  112. public:
  113. PrecompilePreambleAction(std::string *InMemStorage,
  114. PreambleCallbacks &Callbacks)
  115. : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
  116. std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
  117. StringRef InFile) override;
  118. bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
  119. void setEmittedPreamblePCH(ASTWriter &Writer) {
  120. this->HasEmittedPreamblePCH = true;
  121. Callbacks.AfterPCHEmitted(Writer);
  122. }
  123. bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
  124. bool hasCodeCompletionSupport() const override { return false; }
  125. bool hasASTFileSupport() const override { return false; }
  126. TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
  127. private:
  128. friend class PrecompilePreambleConsumer;
  129. bool HasEmittedPreamblePCH = false;
  130. std::string *InMemStorage;
  131. PreambleCallbacks &Callbacks;
  132. };
  133. class PrecompilePreambleConsumer : public PCHGenerator {
  134. public:
  135. PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
  136. const Preprocessor &PP,
  137. InMemoryModuleCache &ModuleCache,
  138. StringRef isysroot,
  139. std::unique_ptr<raw_ostream> Out)
  140. : PCHGenerator(PP, ModuleCache, "", isysroot,
  141. std::make_shared<PCHBuffer>(),
  142. ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
  143. /*AllowASTWithErrors=*/true),
  144. Action(Action), Out(std::move(Out)) {}
  145. bool HandleTopLevelDecl(DeclGroupRef DG) override {
  146. Action.Callbacks.HandleTopLevelDecl(DG);
  147. return true;
  148. }
  149. void HandleTranslationUnit(ASTContext &Ctx) override {
  150. PCHGenerator::HandleTranslationUnit(Ctx);
  151. if (!hasEmittedPCH())
  152. return;
  153. // Write the generated bitstream to "Out".
  154. *Out << getPCH();
  155. // Make sure it hits disk now.
  156. Out->flush();
  157. // Free the buffer.
  158. llvm::SmallVector<char, 0> Empty;
  159. getPCH() = std::move(Empty);
  160. Action.setEmittedPreamblePCH(getWriter());
  161. }
  162. private:
  163. PrecompilePreambleAction &Action;
  164. std::unique_ptr<raw_ostream> Out;
  165. };
  166. std::unique_ptr<ASTConsumer>
  167. PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
  168. StringRef InFile) {
  169. std::string Sysroot;
  170. if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
  171. return nullptr;
  172. std::unique_ptr<llvm::raw_ostream> OS;
  173. if (InMemStorage) {
  174. OS = std::make_unique<llvm::raw_string_ostream>(*InMemStorage);
  175. } else {
  176. std::string OutputFile;
  177. OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
  178. }
  179. if (!OS)
  180. return nullptr;
  181. if (!CI.getFrontendOpts().RelocatablePCH)
  182. Sysroot.clear();
  183. return std::make_unique<PrecompilePreambleConsumer>(
  184. *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, std::move(OS));
  185. }
  186. template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
  187. if (!Val)
  188. return false;
  189. Output = std::move(*Val);
  190. return true;
  191. }
  192. } // namespace
  193. PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
  194. llvm::MemoryBuffer *Buffer,
  195. unsigned MaxLines) {
  196. return Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines);
  197. }
  198. llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
  199. const CompilerInvocation &Invocation,
  200. const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
  201. DiagnosticsEngine &Diagnostics,
  202. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
  203. std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
  204. PreambleCallbacks &Callbacks) {
  205. assert(VFS && "VFS is null");
  206. auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
  207. FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
  208. PreprocessorOptions &PreprocessorOpts =
  209. PreambleInvocation->getPreprocessorOpts();
  210. llvm::Optional<TempPCHFile> TempFile;
  211. if (!StoreInMemory) {
  212. // Create a temporary file for the precompiled preamble. In rare
  213. // circumstances, this can fail.
  214. llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
  215. PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
  216. if (!PreamblePCHFile)
  217. return BuildPreambleError::CouldntCreateTempFile;
  218. TempFile = std::move(*PreamblePCHFile);
  219. }
  220. PCHStorage Storage = StoreInMemory ? PCHStorage(InMemoryPreamble())
  221. : PCHStorage(std::move(*TempFile));
  222. // Save the preamble text for later; we'll need to compare against it for
  223. // subsequent reparses.
  224. std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
  225. MainFileBuffer->getBufferStart() +
  226. Bounds.Size);
  227. bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
  228. // Tell the compiler invocation to generate a temporary precompiled header.
  229. FrontendOpts.ProgramAction = frontend::GeneratePCH;
  230. FrontendOpts.OutputFile = StoreInMemory ? getInMemoryPreamblePath()
  231. : Storage.asFile().getFilePath();
  232. PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
  233. PreprocessorOpts.PrecompiledPreambleBytes.second = false;
  234. // Inform preprocessor to record conditional stack when building the preamble.
  235. PreprocessorOpts.GeneratePreamble = true;
  236. // Create the compiler instance to use for building the precompiled preamble.
  237. std::unique_ptr<CompilerInstance> Clang(
  238. new CompilerInstance(std::move(PCHContainerOps)));
  239. // Recover resources if we crash before exiting this method.
  240. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
  241. Clang.get());
  242. Clang->setInvocation(std::move(PreambleInvocation));
  243. Clang->setDiagnostics(&Diagnostics);
  244. // Create the target instance.
  245. Clang->setTarget(TargetInfo::CreateTargetInfo(
  246. Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
  247. if (!Clang->hasTarget())
  248. return BuildPreambleError::CouldntCreateTargetInfo;
  249. // Inform the target of the language options.
  250. //
  251. // FIXME: We shouldn't need to do this, the target should be immutable once
  252. // created. This complexity should be lifted elsewhere.
  253. Clang->getTarget().adjust(Clang->getLangOpts());
  254. if (Clang->getFrontendOpts().Inputs.size() != 1 ||
  255. Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
  256. InputKind::Source ||
  257. Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() ==
  258. Language::LLVM_IR) {
  259. return BuildPreambleError::BadInputs;
  260. }
  261. // Clear out old caches and data.
  262. Diagnostics.Reset();
  263. ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
  264. VFS =
  265. createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
  266. // Create a file manager object to provide access to and cache the filesystem.
  267. Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
  268. // Create the source manager.
  269. Clang->setSourceManager(
  270. new SourceManager(Diagnostics, Clang->getFileManager()));
  271. auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
  272. Clang->addDependencyCollector(PreambleDepCollector);
  273. // Remap the main source file to the preamble buffer.
  274. StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
  275. auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
  276. MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
  277. if (PreprocessorOpts.RetainRemappedFileBuffers) {
  278. // MainFileBuffer will be deleted by unique_ptr after leaving the method.
  279. PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
  280. } else {
  281. // In that case, remapped buffer will be deleted by CompilerInstance on
  282. // BeginSourceFile, so we call release() to avoid double deletion.
  283. PreprocessorOpts.addRemappedFile(MainFilePath,
  284. PreambleInputBuffer.release());
  285. }
  286. std::unique_ptr<PrecompilePreambleAction> Act;
  287. Act.reset(new PrecompilePreambleAction(
  288. StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
  289. Callbacks.BeforeExecute(*Clang);
  290. if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
  291. return BuildPreambleError::BeginSourceFileFailed;
  292. std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
  293. Callbacks.createPPCallbacks();
  294. if (DelegatedPPCallbacks)
  295. Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
  296. if (auto CommentHandler = Callbacks.getCommentHandler())
  297. Clang->getPreprocessor().addCommentHandler(CommentHandler);
  298. if (llvm::Error Err = Act->Execute())
  299. return errorToErrorCode(std::move(Err));
  300. // Run the callbacks.
  301. Callbacks.AfterExecute(*Clang);
  302. Act->EndSourceFile();
  303. if (!Act->hasEmittedPreamblePCH())
  304. return BuildPreambleError::CouldntEmitPCH;
  305. // Keep track of all of the files that the source manager knows about,
  306. // so we can verify whether they have changed or not.
  307. llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
  308. SourceManager &SourceMgr = Clang->getSourceManager();
  309. for (auto &Filename : PreambleDepCollector->getDependencies()) {
  310. auto FileOrErr = Clang->getFileManager().getFile(Filename);
  311. if (!FileOrErr ||
  312. *FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
  313. continue;
  314. auto File = *FileOrErr;
  315. if (time_t ModTime = File->getModificationTime()) {
  316. FilesInPreamble[File->getName()] =
  317. PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
  318. ModTime);
  319. } else {
  320. const llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
  321. FilesInPreamble[File->getName()] =
  322. PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
  323. }
  324. }
  325. return PrecompiledPreamble(std::move(Storage), std::move(PreambleBytes),
  326. PreambleEndsAtStartOfLine,
  327. std::move(FilesInPreamble));
  328. }
  329. PreambleBounds PrecompiledPreamble::getBounds() const {
  330. return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
  331. }
  332. std::size_t PrecompiledPreamble::getSize() const {
  333. switch (Storage.getKind()) {
  334. case PCHStorage::Kind::Empty:
  335. assert(false && "Calling getSize() on invalid PrecompiledPreamble. "
  336. "Was it std::moved?");
  337. return 0;
  338. case PCHStorage::Kind::InMemory:
  339. return Storage.asMemory().Data.size();
  340. case PCHStorage::Kind::TempFile: {
  341. uint64_t Result;
  342. if (llvm::sys::fs::file_size(Storage.asFile().getFilePath(), Result))
  343. return 0;
  344. assert(Result <= std::numeric_limits<std::size_t>::max() &&
  345. "file size did not fit into size_t");
  346. return Result;
  347. }
  348. }
  349. llvm_unreachable("Unhandled storage kind");
  350. }
  351. bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
  352. const llvm::MemoryBuffer *MainFileBuffer,
  353. PreambleBounds Bounds,
  354. llvm::vfs::FileSystem *VFS) const {
  355. assert(
  356. Bounds.Size <= MainFileBuffer->getBufferSize() &&
  357. "Buffer is too large. Bounds were calculated from a different buffer?");
  358. auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
  359. PreprocessorOptions &PreprocessorOpts =
  360. PreambleInvocation->getPreprocessorOpts();
  361. // We've previously computed a preamble. Check whether we have the same
  362. // preamble now that we did before, and that there's enough space in
  363. // the main-file buffer within the precompiled preamble to fit the
  364. // new main file.
  365. if (PreambleBytes.size() != Bounds.Size ||
  366. PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
  367. !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
  368. MainFileBuffer->getBuffer().begin()))
  369. return false;
  370. // The preamble has not changed. We may be able to re-use the precompiled
  371. // preamble.
  372. // Check that none of the files used by the preamble have changed.
  373. // First, make a record of those files that have been overridden via
  374. // remapping or unsaved_files.
  375. std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
  376. for (const auto &R : PreprocessorOpts.RemappedFiles) {
  377. llvm::vfs::Status Status;
  378. if (!moveOnNoError(VFS->status(R.second), Status)) {
  379. // If we can't stat the file we're remapping to, assume that something
  380. // horrible happened.
  381. return false;
  382. }
  383. OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
  384. Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
  385. }
  386. // OverridenFileBuffers tracks only the files not found in VFS.
  387. llvm::StringMap<PreambleFileHash> OverridenFileBuffers;
  388. for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
  389. const PrecompiledPreamble::PreambleFileHash PreambleHash =
  390. PreambleFileHash::createForMemoryBuffer(RB.second);
  391. llvm::vfs::Status Status;
  392. if (moveOnNoError(VFS->status(RB.first), Status))
  393. OverriddenFiles[Status.getUniqueID()] = PreambleHash;
  394. else
  395. OverridenFileBuffers[RB.first] = PreambleHash;
  396. }
  397. // Check whether anything has changed.
  398. for (const auto &F : FilesInPreamble) {
  399. auto OverridenFileBuffer = OverridenFileBuffers.find(F.first());
  400. if (OverridenFileBuffer != OverridenFileBuffers.end()) {
  401. // The file's buffer was remapped and the file was not found in VFS.
  402. // Check whether it matches up with the previous mapping.
  403. if (OverridenFileBuffer->second != F.second)
  404. return false;
  405. continue;
  406. }
  407. llvm::vfs::Status Status;
  408. if (!moveOnNoError(VFS->status(F.first()), Status)) {
  409. // If the file's buffer is not remapped and we can't stat it,
  410. // assume that something horrible happened.
  411. return false;
  412. }
  413. std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
  414. OverriddenFiles.find(Status.getUniqueID());
  415. if (Overridden != OverriddenFiles.end()) {
  416. // This file was remapped; check whether the newly-mapped file
  417. // matches up with the previous mapping.
  418. if (Overridden->second != F.second)
  419. return false;
  420. continue;
  421. }
  422. // Neither the file's buffer nor the file itself was remapped;
  423. // check whether it has changed on disk.
  424. if (Status.getSize() != uint64_t(F.second.Size) ||
  425. llvm::sys::toTimeT(Status.getLastModificationTime()) !=
  426. F.second.ModTime)
  427. return false;
  428. }
  429. return true;
  430. }
  431. void PrecompiledPreamble::AddImplicitPreamble(
  432. CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
  433. llvm::MemoryBuffer *MainFileBuffer) const {
  434. PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
  435. configurePreamble(Bounds, CI, VFS, MainFileBuffer);
  436. }
  437. void PrecompiledPreamble::OverridePreamble(
  438. CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
  439. llvm::MemoryBuffer *MainFileBuffer) const {
  440. auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), MainFileBuffer, 0);
  441. configurePreamble(Bounds, CI, VFS, MainFileBuffer);
  442. }
  443. PrecompiledPreamble::PrecompiledPreamble(
  444. PCHStorage Storage, std::vector<char> PreambleBytes,
  445. bool PreambleEndsAtStartOfLine,
  446. llvm::StringMap<PreambleFileHash> FilesInPreamble)
  447. : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
  448. PreambleBytes(std::move(PreambleBytes)),
  449. PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
  450. assert(this->Storage.getKind() != PCHStorage::Kind::Empty);
  451. }
  452. llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
  453. PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
  454. // FIXME: This is a hack so that we can override the preamble file during
  455. // crash-recovery testing, which is the only case where the preamble files
  456. // are not necessarily cleaned up.
  457. const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
  458. if (TmpFile)
  459. return TempPCHFile::createFromCustomPath(TmpFile);
  460. return TempPCHFile::createInSystemTempDir("preamble", "pch");
  461. }
  462. llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
  463. PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix,
  464. StringRef Suffix) {
  465. llvm::SmallString<64> File;
  466. // Using a version of createTemporaryFile with a file descriptor guarantees
  467. // that we would never get a race condition in a multi-threaded setting
  468. // (i.e., multiple threads getting the same temporary path).
  469. int FD;
  470. auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, FD, File);
  471. if (EC)
  472. return EC;
  473. // We only needed to make sure the file exists, close the file right away.
  474. llvm::sys::Process::SafelyCloseFileDescriptor(FD);
  475. return TempPCHFile(std::move(File).str());
  476. }
  477. llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
  478. PrecompiledPreamble::TempPCHFile::createFromCustomPath(const Twine &Path) {
  479. return TempPCHFile(Path.str());
  480. }
  481. PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
  482. : FilePath(std::move(FilePath)) {
  483. TemporaryFiles::getInstance().addFile(*this->FilePath);
  484. }
  485. PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
  486. FilePath = std::move(Other.FilePath);
  487. Other.FilePath = None;
  488. }
  489. PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
  490. operator=(TempPCHFile &&Other) {
  491. RemoveFileIfPresent();
  492. FilePath = std::move(Other.FilePath);
  493. Other.FilePath = None;
  494. return *this;
  495. }
  496. PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
  497. void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
  498. if (FilePath) {
  499. TemporaryFiles::getInstance().removeFile(*FilePath);
  500. FilePath = None;
  501. }
  502. }
  503. llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
  504. assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
  505. return *FilePath;
  506. }
  507. PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
  508. : StorageKind(Kind::TempFile) {
  509. new (&asFile()) TempPCHFile(std::move(File));
  510. }
  511. PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
  512. : StorageKind(Kind::InMemory) {
  513. new (&asMemory()) InMemoryPreamble(std::move(Memory));
  514. }
  515. PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
  516. *this = std::move(Other);
  517. }
  518. PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
  519. operator=(PCHStorage &&Other) {
  520. destroy();
  521. StorageKind = Other.StorageKind;
  522. switch (StorageKind) {
  523. case Kind::Empty:
  524. // do nothing;
  525. break;
  526. case Kind::TempFile:
  527. new (&asFile()) TempPCHFile(std::move(Other.asFile()));
  528. break;
  529. case Kind::InMemory:
  530. new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
  531. break;
  532. }
  533. Other.setEmpty();
  534. return *this;
  535. }
  536. PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
  537. PrecompiledPreamble::PCHStorage::Kind
  538. PrecompiledPreamble::PCHStorage::getKind() const {
  539. return StorageKind;
  540. }
  541. PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
  542. assert(getKind() == Kind::TempFile);
  543. return *reinterpret_cast<TempPCHFile *>(Storage.buffer);
  544. }
  545. const PrecompiledPreamble::TempPCHFile &
  546. PrecompiledPreamble::PCHStorage::asFile() const {
  547. return const_cast<PCHStorage *>(this)->asFile();
  548. }
  549. PrecompiledPreamble::InMemoryPreamble &
  550. PrecompiledPreamble::PCHStorage::asMemory() {
  551. assert(getKind() == Kind::InMemory);
  552. return *reinterpret_cast<InMemoryPreamble *>(Storage.buffer);
  553. }
  554. const PrecompiledPreamble::InMemoryPreamble &
  555. PrecompiledPreamble::PCHStorage::asMemory() const {
  556. return const_cast<PCHStorage *>(this)->asMemory();
  557. }
  558. void PrecompiledPreamble::PCHStorage::destroy() {
  559. switch (StorageKind) {
  560. case Kind::Empty:
  561. return;
  562. case Kind::TempFile:
  563. asFile().~TempPCHFile();
  564. return;
  565. case Kind::InMemory:
  566. asMemory().~InMemoryPreamble();
  567. return;
  568. }
  569. }
  570. void PrecompiledPreamble::PCHStorage::setEmpty() {
  571. destroy();
  572. StorageKind = Kind::Empty;
  573. }
  574. PrecompiledPreamble::PreambleFileHash
  575. PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
  576. time_t ModTime) {
  577. PreambleFileHash Result;
  578. Result.Size = Size;
  579. Result.ModTime = ModTime;
  580. Result.MD5 = {};
  581. return Result;
  582. }
  583. PrecompiledPreamble::PreambleFileHash
  584. PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
  585. const llvm::MemoryBuffer *Buffer) {
  586. PreambleFileHash Result;
  587. Result.Size = Buffer->getBufferSize();
  588. Result.ModTime = 0;
  589. llvm::MD5 MD5Ctx;
  590. MD5Ctx.update(Buffer->getBuffer().data());
  591. MD5Ctx.final(Result.MD5);
  592. return Result;
  593. }
  594. void PrecompiledPreamble::configurePreamble(
  595. PreambleBounds Bounds, CompilerInvocation &CI,
  596. IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
  597. llvm::MemoryBuffer *MainFileBuffer) const {
  598. assert(VFS);
  599. auto &PreprocessorOpts = CI.getPreprocessorOpts();
  600. // Remap main file to point to MainFileBuffer.
  601. auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
  602. PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
  603. // Configure ImpicitPCHInclude.
  604. PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
  605. PreprocessorOpts.PrecompiledPreambleBytes.second =
  606. Bounds.PreambleEndsAtStartOfLine;
  607. PreprocessorOpts.DisablePCHValidation = true;
  608. setupPreambleStorage(Storage, PreprocessorOpts, VFS);
  609. }
  610. void PrecompiledPreamble::setupPreambleStorage(
  611. const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
  612. IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) {
  613. if (Storage.getKind() == PCHStorage::Kind::TempFile) {
  614. const TempPCHFile &PCHFile = Storage.asFile();
  615. PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath();
  616. // Make sure we can access the PCH file even if we're using a VFS
  617. IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS =
  618. llvm::vfs::getRealFileSystem();
  619. auto PCHPath = PCHFile.getFilePath();
  620. if (VFS == RealFS || VFS->exists(PCHPath))
  621. return;
  622. auto Buf = RealFS->getBufferForFile(PCHPath);
  623. if (!Buf) {
  624. // We can't read the file even from RealFS, this is clearly an error,
  625. // but we'll just leave the current VFS as is and let clang's code
  626. // figure out what to do with missing PCH.
  627. return;
  628. }
  629. // We have a slight inconsistency here -- we're using the VFS to
  630. // read files, but the PCH was generated in the real file system.
  631. VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
  632. } else {
  633. assert(Storage.getKind() == PCHStorage::Kind::InMemory);
  634. // For in-memory preamble, we have to provide a VFS overlay that makes it
  635. // accessible.
  636. StringRef PCHPath = getInMemoryPreamblePath();
  637. PreprocessorOpts.ImplicitPCHInclude = PCHPath;
  638. auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
  639. VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
  640. }
  641. }
  642. void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
  643. void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
  644. void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
  645. void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
  646. std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
  647. return nullptr;
  648. }
  649. CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
  650. static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
  651. std::error_code clang::make_error_code(BuildPreambleError Error) {
  652. return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
  653. }
  654. const char *BuildPreambleErrorCategory::name() const noexcept {
  655. return "build-preamble.error";
  656. }
  657. std::string BuildPreambleErrorCategory::message(int condition) const {
  658. switch (static_cast<BuildPreambleError>(condition)) {
  659. case BuildPreambleError::CouldntCreateTempFile:
  660. return "Could not create temporary file for PCH";
  661. case BuildPreambleError::CouldntCreateTargetInfo:
  662. return "CreateTargetInfo() return null";
  663. case BuildPreambleError::BeginSourceFileFailed:
  664. return "BeginSourceFile() return an error";
  665. case BuildPreambleError::CouldntEmitPCH:
  666. return "Could not emit PCH";
  667. case BuildPreambleError::BadInputs:
  668. return "Command line arguments must contain exactly one source file";
  669. }
  670. llvm_unreachable("unexpected BuildPreambleError");
  671. }