verify-uselistorder.cpp 17 KB

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