PrecompiledPreamble.cpp 27 KB

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