PrecompiledPreamble.cpp 26 KB

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