DependencyInfo.h 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //===-- DependencyInfo.h --------------------------------------------------===//
  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. #include "llvm/ADT/StringRef.h"
  9. #include "llvm/Support/FileSystem.h"
  10. #include "llvm/Support/WithColor.h"
  11. #include "llvm/Support/raw_ostream.h"
  12. #include <set>
  13. class DependencyInfo {
  14. public:
  15. explicit DependencyInfo(std::string DependencyInfoPath)
  16. : DependencyInfoPath(DependencyInfoPath) {}
  17. virtual ~DependencyInfo(){};
  18. virtual void addMissingInput(llvm::StringRef Path) {
  19. NotFounds.insert(Path.str());
  20. }
  21. // Writes the dependencies to specified path. The content is first sorted by
  22. // OpCode and then by the filename (in alphabetical order).
  23. virtual void write(llvm::Twine Version,
  24. const std::vector<std::string> &Inputs,
  25. std::string Output) {
  26. std::error_code EC;
  27. llvm::raw_fd_ostream OS(DependencyInfoPath, EC, llvm::sys::fs::OF_None);
  28. if (EC) {
  29. llvm::WithColor::defaultErrorHandler(llvm::createStringError(
  30. EC,
  31. "failed to write to " + DependencyInfoPath + ": " + EC.message()));
  32. return;
  33. }
  34. auto AddDep = [&OS](DependencyInfoOpcode Opcode,
  35. const llvm::StringRef &Path) {
  36. OS << static_cast<uint8_t>(Opcode);
  37. OS << Path;
  38. OS << '\0';
  39. };
  40. AddDep(DependencyInfoOpcode::Tool, Version.str());
  41. // Sort the input by its names.
  42. std::vector<llvm::StringRef> InputNames;
  43. InputNames.reserve(Inputs.size());
  44. for (const auto &F : Inputs)
  45. InputNames.push_back(F);
  46. llvm::sort(InputNames);
  47. for (const auto &In : InputNames)
  48. AddDep(DependencyInfoOpcode::InputFound, In);
  49. for (const std::string &F : NotFounds)
  50. AddDep(DependencyInfoOpcode::InputMissing, F);
  51. AddDep(DependencyInfoOpcode::Output, Output);
  52. }
  53. private:
  54. enum DependencyInfoOpcode : uint8_t {
  55. Tool = 0x00,
  56. InputFound = 0x10,
  57. InputMissing = 0x11,
  58. Output = 0x40,
  59. };
  60. const std::string DependencyInfoPath;
  61. std::set<std::string> NotFounds;
  62. };
  63. // Subclass to avoid any overhead when not using this feature
  64. class DummyDependencyInfo : public DependencyInfo {
  65. public:
  66. DummyDependencyInfo() : DependencyInfo("") {}
  67. void addMissingInput(llvm::StringRef Path) override {}
  68. void write(llvm::Twine Version, const std::vector<std::string> &Inputs,
  69. std::string Output) override {}
  70. };