verify-uselistorder.cpp 17 KB

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