verify-uselistorder.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. //===- verify-uselistorder.cpp - The LLVM Modular Optimizer ---------------===//
  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. // Verify that use-list order can be serialized correctly. After reading the
  10. // provided IR, this tool shuffles the use-lists and then writes and reads to a
  11. // separate Module whose use-list orders are compared to the original.
  12. //
  13. // The shuffles are deterministic, but guarantee that use-lists will change.
  14. // The algorithm per iteration is as follows:
  15. //
  16. // 1. Seed the random number generator. The seed is different for each
  17. // shuffle. Shuffle 0 uses default+0, shuffle 1 uses default+1, and so on.
  18. //
  19. // 2. Visit every Value in a deterministic order.
  20. //
  21. // 3. Assign a random number to each Use in the Value's use-list in order.
  22. //
  23. // 4. If the numbers are already in order, reassign numbers until they aren't.
  24. //
  25. // 5. Sort the use-list using Value::sortUseList(), which is a stable sort.
  26. //
  27. //===----------------------------------------------------------------------===//
  28. #include "llvm/ADT/DenseMap.h"
  29. #include "llvm/ADT/DenseSet.h"
  30. #include "llvm/AsmParser/Parser.h"
  31. #include "llvm/Bitcode/BitcodeReader.h"
  32. #include "llvm/Bitcode/BitcodeWriter.h"
  33. #include "llvm/IR/LLVMContext.h"
  34. #include "llvm/IR/Module.h"
  35. #include "llvm/IR/UseListOrder.h"
  36. #include "llvm/IR/Verifier.h"
  37. #include "llvm/IRReader/IRReader.h"
  38. #include "llvm/Support/CommandLine.h"
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Support/FileSystem.h"
  42. #include "llvm/Support/FileUtilities.h"
  43. #include "llvm/Support/InitLLVM.h"
  44. #include "llvm/Support/MemoryBuffer.h"
  45. #include "llvm/Support/SourceMgr.h"
  46. #include "llvm/Support/SystemUtils.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include <random>
  49. #include <vector>
  50. using namespace llvm;
  51. #define DEBUG_TYPE "uselistorder"
  52. static cl::OptionCategory Cat("verify-uselistorder Options");
  53. static cl::opt<std::string> InputFilename(cl::Positional,
  54. cl::desc("<input bitcode file>"),
  55. cl::init("-"),
  56. cl::value_desc("filename"));
  57. static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temp files"),
  58. cl::cat(Cat));
  59. static cl::opt<unsigned>
  60. NumShuffles("num-shuffles",
  61. cl::desc("Number of times to shuffle and verify use-lists"),
  62. cl::init(1), cl::cat(Cat));
  63. namespace {
  64. struct TempFile {
  65. std::string Filename;
  66. FileRemover Remover;
  67. bool init(const std::string &Ext);
  68. bool writeBitcode(const Module &M) const;
  69. bool writeAssembly(const Module &M) const;
  70. std::unique_ptr<Module> readBitcode(LLVMContext &Context) const;
  71. std::unique_ptr<Module> readAssembly(LLVMContext &Context) const;
  72. };
  73. struct ValueMapping {
  74. DenseMap<const Value *, unsigned> IDs;
  75. std::vector<const Value *> Values;
  76. /// Construct a value mapping for module.
  77. ///
  78. /// Creates mapping from every value in \c M to an ID. This mapping includes
  79. /// un-referencable values.
  80. ///
  81. /// Every \a Value that gets serialized in some way should be represented
  82. /// here. The order needs to be deterministic, but it's unnecessary to match
  83. /// the value-ids in the bitcode writer.
  84. ///
  85. /// All constants that are referenced by other values are included in the
  86. /// mapping, but others -- which wouldn't be serialized -- are not.
  87. ValueMapping(const Module &M);
  88. /// Map a value.
  89. ///
  90. /// Maps a value. If it's a constant, maps all of its operands first.
  91. void map(const Value *V);
  92. unsigned lookup(const Value *V) const { return IDs.lookup(V); }
  93. };
  94. } // end namespace
  95. bool TempFile::init(const std::string &Ext) {
  96. SmallVector<char, 64> Vector;
  97. LLVM_DEBUG(dbgs() << " - create-temp-file\n");
  98. if (auto EC = sys::fs::createTemporaryFile("uselistorder", Ext, Vector)) {
  99. errs() << "verify-uselistorder: error: " << EC.message() << "\n";
  100. return true;
  101. }
  102. assert(!Vector.empty());
  103. Filename.assign(Vector.data(), Vector.data() + Vector.size());
  104. Remover.setFile(Filename, !SaveTemps);
  105. if (SaveTemps)
  106. outs() << " - filename = " << Filename << "\n";
  107. return false;
  108. }
  109. bool TempFile::writeBitcode(const Module &M) const {
  110. LLVM_DEBUG(dbgs() << " - write bitcode\n");
  111. std::error_code EC;
  112. raw_fd_ostream OS(Filename, EC, sys::fs::OF_None);
  113. if (EC) {
  114. errs() << "verify-uselistorder: error: " << EC.message() << "\n";
  115. return true;
  116. }
  117. WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
  118. return false;
  119. }
  120. bool TempFile::writeAssembly(const Module &M) const {
  121. LLVM_DEBUG(dbgs() << " - write assembly\n");
  122. std::error_code EC;
  123. raw_fd_ostream OS(Filename, EC, sys::fs::OF_TextWithCRLF);
  124. if (EC) {
  125. errs() << "verify-uselistorder: error: " << EC.message() << "\n";
  126. return true;
  127. }
  128. M.print(OS, nullptr, /* ShouldPreserveUseListOrder */ true);
  129. return false;
  130. }
  131. std::unique_ptr<Module> TempFile::readBitcode(LLVMContext &Context) const {
  132. LLVM_DEBUG(dbgs() << " - read bitcode\n");
  133. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOr =
  134. MemoryBuffer::getFile(Filename);
  135. if (!BufferOr) {
  136. errs() << "verify-uselistorder: error: " << BufferOr.getError().message()
  137. << "\n";
  138. return nullptr;
  139. }
  140. MemoryBuffer *Buffer = BufferOr.get().get();
  141. Expected<std::unique_ptr<Module>> ModuleOr =
  142. parseBitcodeFile(Buffer->getMemBufferRef(), Context);
  143. if (!ModuleOr) {
  144. logAllUnhandledErrors(ModuleOr.takeError(), errs(),
  145. "verify-uselistorder: error: ");
  146. return nullptr;
  147. }
  148. return std::move(ModuleOr.get());
  149. }
  150. std::unique_ptr<Module> TempFile::readAssembly(LLVMContext &Context) const {
  151. LLVM_DEBUG(dbgs() << " - read assembly\n");
  152. SMDiagnostic Err;
  153. std::unique_ptr<Module> M = parseAssemblyFile(Filename, Err, Context);
  154. if (!M.get())
  155. Err.print("verify-uselistorder", errs());
  156. return M;
  157. }
  158. ValueMapping::ValueMapping(const Module &M) {
  159. // Every value should be mapped, including things like void instructions and
  160. // basic blocks that are kept out of the ValueEnumerator.
  161. //
  162. // The current mapping order makes it easier to debug the tables. It happens
  163. // to be similar to the ID mapping when writing ValueEnumerator, but they
  164. // aren't (and needn't be) in sync.
  165. // Globals.
  166. for (const GlobalVariable &G : M.globals())
  167. map(&G);
  168. for (const GlobalAlias &A : M.aliases())
  169. map(&A);
  170. for (const GlobalIFunc &IF : M.ifuncs())
  171. map(&IF);
  172. for (const Function &F : M)
  173. map(&F);
  174. // Constants used by globals.
  175. for (const GlobalVariable &G : M.globals())
  176. if (G.hasInitializer())
  177. map(G.getInitializer());
  178. for (const GlobalAlias &A : M.aliases())
  179. map(A.getAliasee());
  180. for (const GlobalIFunc &IF : M.ifuncs())
  181. map(IF.getResolver());
  182. for (const Function &F : M)
  183. for (Value *Op : F.operands())
  184. map(Op);
  185. // Function bodies.
  186. for (const Function &F : M) {
  187. for (const Argument &A : F.args())
  188. map(&A);
  189. for (const BasicBlock &BB : F)
  190. map(&BB);
  191. for (const BasicBlock &BB : F)
  192. for (const Instruction &I : BB)
  193. map(&I);
  194. // Constants used by instructions.
  195. for (const BasicBlock &BB : F)
  196. for (const Instruction &I : BB)
  197. for (const Value *Op : I.operands()) {
  198. // Look through a metadata wrapper.
  199. if (const auto *MAV = dyn_cast<MetadataAsValue>(Op))
  200. if (const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
  201. Op = VAM->getValue();
  202. if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
  203. isa<InlineAsm>(Op))
  204. map(Op);
  205. }
  206. }
  207. }
  208. void ValueMapping::map(const Value *V) {
  209. if (IDs.lookup(V))
  210. return;
  211. if (auto *C = dyn_cast<Constant>(V))
  212. if (!isa<GlobalValue>(C))
  213. for (const Value *Op : C->operands())
  214. map(Op);
  215. Values.push_back(V);
  216. IDs[V] = Values.size();
  217. }
  218. #ifndef NDEBUG
  219. static void dumpMapping(const ValueMapping &VM) {
  220. dbgs() << "value-mapping (size = " << VM.Values.size() << "):\n";
  221. for (unsigned I = 0, E = VM.Values.size(); I != E; ++I) {
  222. dbgs() << " - id = " << I << ", value = ";
  223. VM.Values[I]->dump();
  224. }
  225. }
  226. static void debugValue(const ValueMapping &M, unsigned I, StringRef Desc) {
  227. const Value *V = M.Values[I];
  228. dbgs() << " - " << Desc << " value = ";
  229. V->dump();
  230. for (const Use &U : V->uses()) {
  231. dbgs() << " => use: op = " << U.getOperandNo()
  232. << ", user-id = " << M.IDs.lookup(U.getUser()) << ", user = ";
  233. U.getUser()->dump();
  234. }
  235. }
  236. static void debugUserMismatch(const ValueMapping &L, const ValueMapping &R,
  237. unsigned I) {
  238. dbgs() << " - fail: user mismatch: ID = " << I << "\n";
  239. debugValue(L, I, "LHS");
  240. debugValue(R, I, "RHS");
  241. dbgs() << "\nlhs-";
  242. dumpMapping(L);
  243. dbgs() << "\nrhs-";
  244. dumpMapping(R);
  245. }
  246. static void debugSizeMismatch(const ValueMapping &L, const ValueMapping &R) {
  247. dbgs() << " - fail: map size: " << L.Values.size()
  248. << " != " << R.Values.size() << "\n";
  249. dbgs() << "\nlhs-";
  250. dumpMapping(L);
  251. dbgs() << "\nrhs-";
  252. dumpMapping(R);
  253. }
  254. #endif
  255. static bool matches(const ValueMapping &LM, const ValueMapping &RM) {
  256. LLVM_DEBUG(dbgs() << "compare value maps\n");
  257. if (LM.Values.size() != RM.Values.size()) {
  258. LLVM_DEBUG(debugSizeMismatch(LM, RM));
  259. return false;
  260. }
  261. // This mapping doesn't include dangling constant users, since those don't
  262. // get serialized. However, checking if users are constant and calling
  263. // isConstantUsed() on every one is very expensive. Instead, just check if
  264. // the user is mapped.
  265. auto skipUnmappedUsers =
  266. [&](Value::const_use_iterator &U, Value::const_use_iterator E,
  267. const ValueMapping &M) {
  268. while (U != E && !M.lookup(U->getUser()))
  269. ++U;
  270. };
  271. // Iterate through all values, and check that both mappings have the same
  272. // users.
  273. for (unsigned I = 0, E = LM.Values.size(); I != E; ++I) {
  274. const Value *L = LM.Values[I];
  275. const Value *R = RM.Values[I];
  276. auto LU = L->use_begin(), LE = L->use_end();
  277. auto RU = R->use_begin(), RE = R->use_end();
  278. skipUnmappedUsers(LU, LE, LM);
  279. skipUnmappedUsers(RU, RE, RM);
  280. while (LU != LE) {
  281. if (RU == RE) {
  282. LLVM_DEBUG(debugUserMismatch(LM, RM, I));
  283. return false;
  284. }
  285. if (LM.lookup(LU->getUser()) != RM.lookup(RU->getUser())) {
  286. LLVM_DEBUG(debugUserMismatch(LM, RM, I));
  287. return false;
  288. }
  289. if (LU->getOperandNo() != RU->getOperandNo()) {
  290. LLVM_DEBUG(debugUserMismatch(LM, RM, I));
  291. return false;
  292. }
  293. skipUnmappedUsers(++LU, LE, LM);
  294. skipUnmappedUsers(++RU, RE, RM);
  295. }
  296. if (RU != RE) {
  297. LLVM_DEBUG(debugUserMismatch(LM, RM, I));
  298. return false;
  299. }
  300. }
  301. return true;
  302. }
  303. static void verifyAfterRoundTrip(const Module &M,
  304. std::unique_ptr<Module> OtherM) {
  305. if (!OtherM)
  306. report_fatal_error("parsing failed");
  307. if (verifyModule(*OtherM, &errs()))
  308. report_fatal_error("verification failed");
  309. if (!matches(ValueMapping(M), ValueMapping(*OtherM)))
  310. report_fatal_error("use-list order changed");
  311. }
  312. static void verifyBitcodeUseListOrder(const Module &M) {
  313. TempFile F;
  314. if (F.init("bc"))
  315. report_fatal_error("failed to initialize bitcode file");
  316. if (F.writeBitcode(M))
  317. report_fatal_error("failed to write bitcode");
  318. LLVMContext Context;
  319. verifyAfterRoundTrip(M, F.readBitcode(Context));
  320. }
  321. static void verifyAssemblyUseListOrder(const Module &M) {
  322. TempFile F;
  323. if (F.init("ll"))
  324. report_fatal_error("failed to initialize assembly file");
  325. if (F.writeAssembly(M))
  326. report_fatal_error("failed to write assembly");
  327. LLVMContext Context;
  328. verifyAfterRoundTrip(M, F.readAssembly(Context));
  329. }
  330. static void verifyUseListOrder(const Module &M) {
  331. outs() << "verify bitcode\n";
  332. verifyBitcodeUseListOrder(M);
  333. outs() << "verify assembly\n";
  334. verifyAssemblyUseListOrder(M);
  335. }
  336. static void shuffleValueUseLists(Value *V, std::minstd_rand0 &Gen,
  337. DenseSet<Value *> &Seen) {
  338. if (!Seen.insert(V).second)
  339. return;
  340. if (auto *C = dyn_cast<Constant>(V))
  341. if (!isa<GlobalValue>(C))
  342. for (Value *Op : C->operands())
  343. shuffleValueUseLists(Op, Gen, Seen);
  344. if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
  345. // Nothing to shuffle for 0 or 1 users.
  346. return;
  347. // Generate random numbers between 10 and 99, which will line up nicely in
  348. // debug output. We're not worried about collisions here.
  349. LLVM_DEBUG(dbgs() << "V = "; V->dump());
  350. std::uniform_int_distribution<short> Dist(10, 99);
  351. SmallDenseMap<const Use *, short, 16> Order;
  352. auto compareUses =
  353. [&Order](const Use &L, const Use &R) { return Order[&L] < Order[&R]; };
  354. do {
  355. for (const Use &U : V->uses()) {
  356. auto I = Dist(Gen);
  357. Order[&U] = I;
  358. LLVM_DEBUG(dbgs() << " - order: " << I << ", op = " << U.getOperandNo()
  359. << ", U = ";
  360. U.getUser()->dump());
  361. }
  362. } while (std::is_sorted(V->use_begin(), V->use_end(), compareUses));
  363. LLVM_DEBUG(dbgs() << " => shuffle\n");
  364. V->sortUseList(compareUses);
  365. LLVM_DEBUG({
  366. for (const Use &U : V->uses()) {
  367. dbgs() << " - order: " << Order.lookup(&U)
  368. << ", op = " << U.getOperandNo() << ", U = ";
  369. U.getUser()->dump();
  370. }
  371. });
  372. }
  373. static void reverseValueUseLists(Value *V, DenseSet<Value *> &Seen) {
  374. if (!Seen.insert(V).second)
  375. return;
  376. if (auto *C = dyn_cast<Constant>(V))
  377. if (!isa<GlobalValue>(C))
  378. for (Value *Op : C->operands())
  379. reverseValueUseLists(Op, Seen);
  380. if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
  381. // Nothing to shuffle for 0 or 1 users.
  382. return;
  383. LLVM_DEBUG({
  384. dbgs() << "V = ";
  385. V->dump();
  386. for (const Use &U : V->uses()) {
  387. dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
  388. U.getUser()->dump();
  389. }
  390. dbgs() << " => reverse\n";
  391. });
  392. V->reverseUseList();
  393. LLVM_DEBUG({
  394. for (const Use &U : V->uses()) {
  395. dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
  396. U.getUser()->dump();
  397. }
  398. });
  399. }
  400. template <class Changer>
  401. static void changeUseLists(Module &M, Changer changeValueUseList) {
  402. // Visit every value that would be serialized to an IR file.
  403. //
  404. // Globals.
  405. for (GlobalVariable &G : M.globals())
  406. changeValueUseList(&G);
  407. for (GlobalAlias &A : M.aliases())
  408. changeValueUseList(&A);
  409. for (GlobalIFunc &IF : M.ifuncs())
  410. changeValueUseList(&IF);
  411. for (Function &F : M)
  412. changeValueUseList(&F);
  413. // Constants used by globals.
  414. for (GlobalVariable &G : M.globals())
  415. if (G.hasInitializer())
  416. changeValueUseList(G.getInitializer());
  417. for (GlobalAlias &A : M.aliases())
  418. changeValueUseList(A.getAliasee());
  419. for (GlobalIFunc &IF : M.ifuncs())
  420. changeValueUseList(IF.getResolver());
  421. for (Function &F : M)
  422. for (Value *Op : F.operands())
  423. changeValueUseList(Op);
  424. // Function bodies.
  425. for (Function &F : M) {
  426. for (Argument &A : F.args())
  427. changeValueUseList(&A);
  428. for (BasicBlock &BB : F)
  429. changeValueUseList(&BB);
  430. for (BasicBlock &BB : F)
  431. for (Instruction &I : BB)
  432. changeValueUseList(&I);
  433. // Constants used by instructions.
  434. for (BasicBlock &BB : F)
  435. for (Instruction &I : BB)
  436. for (Value *Op : I.operands()) {
  437. // Look through a metadata wrapper.
  438. if (auto *MAV = dyn_cast<MetadataAsValue>(Op))
  439. if (auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
  440. Op = VAM->getValue();
  441. if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
  442. isa<InlineAsm>(Op))
  443. changeValueUseList(Op);
  444. }
  445. }
  446. if (verifyModule(M, &errs()))
  447. report_fatal_error("verification failed");
  448. }
  449. static void shuffleUseLists(Module &M, unsigned SeedOffset) {
  450. std::minstd_rand0 Gen(std::minstd_rand0::default_seed + SeedOffset);
  451. DenseSet<Value *> Seen;
  452. changeUseLists(M, [&](Value *V) { shuffleValueUseLists(V, Gen, Seen); });
  453. LLVM_DEBUG(dbgs() << "\n");
  454. }
  455. static void reverseUseLists(Module &M) {
  456. DenseSet<Value *> Seen;
  457. changeUseLists(M, [&](Value *V) { reverseValueUseLists(V, Seen); });
  458. LLVM_DEBUG(dbgs() << "\n");
  459. }
  460. int main(int argc, char **argv) {
  461. InitLLVM X(argc, argv);
  462. // Enable debug stream buffering.
  463. EnableDebugBuffering = true;
  464. cl::HideUnrelatedOptions(Cat);
  465. cl::ParseCommandLineOptions(argc, argv,
  466. "llvm tool to verify use-list order\n");
  467. LLVMContext Context;
  468. SMDiagnostic Err;
  469. // Load the input module...
  470. std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
  471. if (!M.get()) {
  472. Err.print(argv[0], errs());
  473. return 1;
  474. }
  475. if (verifyModule(*M, &errs())) {
  476. errs() << argv[0] << ": " << InputFilename
  477. << ": error: input module is broken!\n";
  478. return 1;
  479. }
  480. // Verify the use lists now and after reversing them.
  481. outs() << "*** verify-uselistorder ***\n";
  482. verifyUseListOrder(*M);
  483. outs() << "reverse\n";
  484. reverseUseLists(*M);
  485. verifyUseListOrder(*M);
  486. for (unsigned I = 0, E = NumShuffles; I != E; ++I) {
  487. outs() << "\n";
  488. // Shuffle with a different (deterministic) seed each time.
  489. outs() << "shuffle (" << I + 1 << " of " << E << ")\n";
  490. shuffleUseLists(*M, I);
  491. // Verify again before and after reversing.
  492. verifyUseListOrder(*M);
  493. outs() << "reverse\n";
  494. reverseUseLists(*M);
  495. verifyUseListOrder(*M);
  496. }
  497. return 0;
  498. }