1 //===- verify-uselistorder.cpp - The LLVM Modular Optimizer ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 // The shuffles are deterministic, but guarantee that use-lists will change.
15 // The algorithm per iteration is as follows:
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.
20 // 2. Visit every Value in a deterministic order.
22 // 3. Assign a random number to each Use in the Value's use-list in order.
24 // 4. If the numbers are already in order, reassign numbers until they aren't.
26 // 5. Sort the use-list using Value::sortUseList(), which is a stable sort.
28 //===----------------------------------------------------------------------===//
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/AsmParser/Parser.h"
33 #include "llvm/Bitcode/ReaderWriter.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/UseListOrder.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/IRReader/IRReader.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/FileUtilities.h"
44 #include "llvm/Support/ManagedStatic.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/PrettyStackTrace.h"
47 #include "llvm/Support/Signals.h"
48 #include "llvm/Support/SourceMgr.h"
49 #include "llvm/Support/SystemUtils.h"
50 #include "llvm/Support/raw_ostream.h"
56 #define DEBUG_TYPE "use-list-order"
58 static cl::opt<std::string> InputFilename(cl::Positional,
59 cl::desc("<input bitcode file>"),
61 cl::value_desc("filename"));
63 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temp files"),
66 static cl::opt<unsigned>
67 NumShuffles("num-shuffles",
68 cl::desc("Number of times to shuffle and verify use-lists"),
76 bool init(const std::string &Ext);
77 bool writeBitcode(const Module &M) const;
78 bool writeAssembly(const Module &M) const;
79 std::unique_ptr<Module> readBitcode(LLVMContext &Context) const;
80 std::unique_ptr<Module> readAssembly(LLVMContext &Context) const;
84 DenseMap<const Value *, unsigned> IDs;
85 std::vector<const Value *> Values;
87 /// \brief Construct a value mapping for module.
89 /// Creates mapping from every value in \c M to an ID. This mapping includes
90 /// un-referencable values.
92 /// Every \a Value that gets serialized in some way should be represented
93 /// here. The order needs to be deterministic, but it's unnecessary to match
94 /// the value-ids in the bitcode writer.
96 /// All constants that are referenced by other values are included in the
97 /// mapping, but others -- which wouldn't be serialized -- are not.
98 ValueMapping(const Module &M);
100 /// \brief Map a value.
102 /// Maps a value. If it's a constant, maps all of its operands first.
103 void map(const Value *V);
104 unsigned lookup(const Value *V) const { return IDs.lookup(V); }
109 bool TempFile::init(const std::string &Ext) {
110 SmallVector<char, 64> Vector;
111 DEBUG(dbgs() << " - create-temp-file\n");
112 if (auto EC = sys::fs::createTemporaryFile("use-list-order", Ext, Vector)) {
114 DEBUG(dbgs() << "error: " << EC.message() << "\n");
117 assert(!Vector.empty());
119 Filename.assign(Vector.data(), Vector.data() + Vector.size());
120 Remover.setFile(Filename, !SaveTemps);
121 DEBUG(dbgs() << " - filename = " << Filename << "\n");
125 bool TempFile::writeBitcode(const Module &M) const {
126 DEBUG(dbgs() << " - write bitcode\n");
128 raw_fd_ostream OS(Filename, EC, sys::fs::F_None);
130 DEBUG(dbgs() << "error: " << EC.message() << "\n");
134 WriteBitcodeToFile(&M, OS);
138 bool TempFile::writeAssembly(const Module &M) const {
139 DEBUG(dbgs() << " - write assembly\n");
141 raw_fd_ostream OS(Filename, EC, sys::fs::F_Text);
143 DEBUG(dbgs() << "error: " << EC.message() << "\n");
151 std::unique_ptr<Module> TempFile::readBitcode(LLVMContext &Context) const {
152 DEBUG(dbgs() << " - read bitcode\n");
153 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOr =
154 MemoryBuffer::getFile(Filename);
156 DEBUG(dbgs() << "error: " << BufferOr.getError().message() << "\n");
160 MemoryBuffer *Buffer = BufferOr.get().get();
161 ErrorOr<Module *> ModuleOr =
162 parseBitcodeFile(Buffer->getMemBufferRef(), Context);
164 DEBUG(dbgs() << "error: " << ModuleOr.getError().message() << "\n");
167 return std::unique_ptr<Module>(ModuleOr.get());
170 std::unique_ptr<Module> TempFile::readAssembly(LLVMContext &Context) const {
171 DEBUG(dbgs() << " - read assembly\n");
173 std::unique_ptr<Module> M = parseAssemblyFile(Filename, Err, Context);
175 DEBUG(dbgs() << "error: "; Err.print("verify-use-list-order", dbgs()));
179 ValueMapping::ValueMapping(const Module &M) {
180 // Every value should be mapped, including things like void instructions and
181 // basic blocks that are kept out of the ValueEnumerator.
183 // The current mapping order makes it easier to debug the tables. It happens
184 // to be similar to the ID mapping when writing ValueEnumerator, but they
185 // aren't (and needn't be) in sync.
188 for (const GlobalVariable &G : M.globals())
190 for (const GlobalAlias &A : M.aliases())
192 for (const Function &F : M)
195 // Constants used by globals.
196 for (const GlobalVariable &G : M.globals())
197 if (G.hasInitializer())
198 map(G.getInitializer());
199 for (const GlobalAlias &A : M.aliases())
201 for (const Function &F : M) {
202 if (F.hasPrefixData())
203 map(F.getPrefixData());
204 if (F.hasPrologueData())
205 map(F.getPrologueData());
209 for (const Function &F : M) {
210 for (const Argument &A : F.args())
212 for (const BasicBlock &BB : F)
214 for (const BasicBlock &BB : F)
215 for (const Instruction &I : BB)
218 // Constants used by instructions.
219 for (const BasicBlock &BB : F)
220 for (const Instruction &I : BB)
221 for (const Value *Op : I.operands())
222 if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
228 void ValueMapping::map(const Value *V) {
232 if (auto *C = dyn_cast<Constant>(V))
233 if (!isa<GlobalValue>(C))
234 for (const Value *Op : C->operands())
238 IDs[V] = Values.size();
242 static void dumpMapping(const ValueMapping &VM) {
243 dbgs() << "value-mapping (size = " << VM.Values.size() << "):\n";
244 for (unsigned I = 0, E = VM.Values.size(); I != E; ++I) {
245 dbgs() << " - id = " << I << ", value = ";
246 VM.Values[I]->dump();
250 static void debugValue(const ValueMapping &M, unsigned I, StringRef Desc) {
251 const Value *V = M.Values[I];
252 dbgs() << " - " << Desc << " value = ";
254 for (const Use &U : V->uses()) {
255 dbgs() << " => use: op = " << U.getOperandNo()
256 << ", user-id = " << M.IDs.lookup(U.getUser()) << ", user = ";
261 static void debugUserMismatch(const ValueMapping &L, const ValueMapping &R,
263 dbgs() << " - fail: user mismatch: ID = " << I << "\n";
264 debugValue(L, I, "LHS");
265 debugValue(R, I, "RHS");
273 static void debugSizeMismatch(const ValueMapping &L, const ValueMapping &R) {
274 dbgs() << " - fail: map size: " << L.Values.size()
275 << " != " << R.Values.size() << "\n";
283 static bool matches(const ValueMapping &LM, const ValueMapping &RM) {
284 DEBUG(dbgs() << "compare value maps\n");
285 if (LM.Values.size() != RM.Values.size()) {
286 DEBUG(debugSizeMismatch(LM, RM));
290 // This mapping doesn't include dangling constant users, since those don't
291 // get serialized. However, checking if users are constant and calling
292 // isConstantUsed() on every one is very expensive. Instead, just check if
293 // the user is mapped.
294 auto skipUnmappedUsers =
295 [&](Value::const_use_iterator &U, Value::const_use_iterator E,
296 const ValueMapping &M) {
297 while (U != E && !M.lookup(U->getUser()))
301 // Iterate through all values, and check that both mappings have the same
303 for (unsigned I = 0, E = LM.Values.size(); I != E; ++I) {
304 const Value *L = LM.Values[I];
305 const Value *R = RM.Values[I];
306 auto LU = L->use_begin(), LE = L->use_end();
307 auto RU = R->use_begin(), RE = R->use_end();
308 skipUnmappedUsers(LU, LE, LM);
309 skipUnmappedUsers(RU, RE, RM);
313 DEBUG(debugUserMismatch(LM, RM, I));
316 if (LM.lookup(LU->getUser()) != RM.lookup(RU->getUser())) {
317 DEBUG(debugUserMismatch(LM, RM, I));
320 if (LU->getOperandNo() != RU->getOperandNo()) {
321 DEBUG(debugUserMismatch(LM, RM, I));
324 skipUnmappedUsers(++LU, LE, LM);
325 skipUnmappedUsers(++RU, RE, RM);
328 DEBUG(debugUserMismatch(LM, RM, I));
336 static void verifyAfterRoundTrip(const Module &M,
337 std::unique_ptr<Module> OtherM) {
339 report_fatal_error("parsing failed");
340 if (verifyModule(*OtherM, &errs()))
341 report_fatal_error("verification failed");
342 if (!matches(ValueMapping(M), ValueMapping(*OtherM)))
343 report_fatal_error("use-list order changed");
345 static void verifyBitcodeUseListOrder(const Module &M) {
346 errs() << "*** verify-use-list-order: bitcode ***\n";
349 report_fatal_error("failed to initialize bitcode file");
351 if (F.writeBitcode(M))
352 report_fatal_error("failed to write bitcode");
355 verifyAfterRoundTrip(M, F.readBitcode(Context));
358 static void verifyAssemblyUseListOrder(const Module &M) {
359 errs() << "*** verify-use-list-order: assembly ***\n";
362 report_fatal_error("failed to initialize assembly file");
364 if (F.writeAssembly(M))
365 report_fatal_error("failed to write assembly");
368 verifyAfterRoundTrip(M, F.readAssembly(Context));
371 static void verifyUseListOrder(const Module &M) {
372 verifyBitcodeUseListOrder(M);
373 verifyAssemblyUseListOrder(M);
376 static void shuffleValueUseLists(Value *V, std::minstd_rand0 &Gen,
377 DenseSet<Value *> &Seen) {
378 if (!Seen.insert(V).second)
381 if (auto *C = dyn_cast<Constant>(V))
382 if (!isa<GlobalValue>(C))
383 for (Value *Op : C->operands())
384 shuffleValueUseLists(Op, Gen, Seen);
386 if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
387 // Nothing to shuffle for 0 or 1 users.
390 // Generate random numbers between 10 and 99, which will line up nicely in
391 // debug output. We're not worried about collisons here.
392 DEBUG(dbgs() << "V = "; V->dump());
393 std::uniform_int_distribution<short> Dist(10, 99);
394 SmallDenseMap<const Use *, short, 16> Order;
396 [&Order](const Use &L, const Use &R) { return Order[&L] < Order[&R]; };
398 for (const Use &U : V->uses()) {
401 DEBUG(dbgs() << " - order: " << I << ", op = " << U.getOperandNo()
403 U.getUser()->dump());
405 } while (std::is_sorted(V->use_begin(), V->use_end(), compareUses));
407 DEBUG(dbgs() << " => shuffle\n");
408 V->sortUseList(compareUses);
411 for (const Use &U : V->uses()) {
412 dbgs() << " - order: " << Order.lookup(&U)
413 << ", op = " << U.getOperandNo() << ", U = ";
419 static void reverseValueUseLists(Value *V, DenseSet<Value *> &Seen) {
420 if (!Seen.insert(V).second)
423 if (auto *C = dyn_cast<Constant>(V))
424 if (!isa<GlobalValue>(C))
425 for (Value *Op : C->operands())
426 reverseValueUseLists(Op, Seen);
428 if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
429 // Nothing to shuffle for 0 or 1 users.
435 for (const Use &U : V->uses()) {
436 dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
439 dbgs() << " => reverse\n";
445 for (const Use &U : V->uses()) {
446 dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
452 template <class Changer>
453 static void changeUseLists(Module &M, Changer changeValueUseList) {
454 // Visit every value that would be serialized to an IR file.
457 for (GlobalVariable &G : M.globals())
458 changeValueUseList(&G);
459 for (GlobalAlias &A : M.aliases())
460 changeValueUseList(&A);
461 for (Function &F : M)
462 changeValueUseList(&F);
464 // Constants used by globals.
465 for (GlobalVariable &G : M.globals())
466 if (G.hasInitializer())
467 changeValueUseList(G.getInitializer());
468 for (GlobalAlias &A : M.aliases())
469 changeValueUseList(A.getAliasee());
470 for (Function &F : M) {
471 if (F.hasPrefixData())
472 changeValueUseList(F.getPrefixData());
473 if (F.hasPrologueData())
474 changeValueUseList(F.getPrologueData());
478 for (Function &F : M) {
479 for (Argument &A : F.args())
480 changeValueUseList(&A);
481 for (BasicBlock &BB : F)
482 changeValueUseList(&BB);
483 for (BasicBlock &BB : F)
484 for (Instruction &I : BB)
485 changeValueUseList(&I);
487 // Constants used by instructions.
488 for (BasicBlock &BB : F)
489 for (Instruction &I : BB)
490 for (Value *Op : I.operands())
491 if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
493 changeValueUseList(Op);
496 if (verifyModule(M, &errs()))
497 report_fatal_error("verification failed");
500 static void shuffleUseLists(Module &M, unsigned SeedOffset) {
501 errs() << "*** shuffle-use-lists ***\n";
502 std::minstd_rand0 Gen(std::minstd_rand0::default_seed + SeedOffset);
503 DenseSet<Value *> Seen;
504 changeUseLists(M, [&](Value *V) { shuffleValueUseLists(V, Gen, Seen); });
505 DEBUG(dbgs() << "\n");
508 static void reverseUseLists(Module &M) {
509 errs() << "*** reverse-use-lists ***\n";
510 DenseSet<Value *> Seen;
511 changeUseLists(M, [&](Value *V) { reverseValueUseLists(V, Seen); });
512 DEBUG(dbgs() << "\n");
515 int main(int argc, char **argv) {
516 sys::PrintStackTraceOnErrorSignal();
517 llvm::PrettyStackTraceProgram X(argc, argv);
519 // Enable debug stream buffering.
520 EnableDebugBuffering = true;
522 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
523 LLVMContext &Context = getGlobalContext();
525 cl::ParseCommandLineOptions(argc, argv,
526 "llvm tool to verify use-list order\n");
530 // Load the input module...
531 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
534 Err.print(argv[0], errs());
537 if (verifyModule(*M, &errs())) {
538 errs() << argv[0] << ": " << InputFilename
539 << ": error: input module is broken!\n";
543 errs() << "*** verify-use-list-order ***\n";
544 // Can't verify if order isn't preserved.
545 if (!shouldPreserveBitcodeUseListOrder()) {
546 errs() << "warning: forcing -preserve-bc-use-list-order\n";
547 setPreserveBitcodeUseListOrder(true);
549 if (!shouldPreserveAssemblyUseListOrder()) {
550 errs() << "warning: forcing -preserve-ll-use-list-order\n";
551 setPreserveAssemblyUseListOrder(true);
554 // Verify the use lists now and after reversing them.
555 verifyUseListOrder(*M);
557 verifyUseListOrder(*M);
559 for (unsigned I = 0, E = NumShuffles; I != E; ++I) {
560 errs() << "*** shuffle iteration: " << I + 1 << " of " << E << " ***\n";
562 // Shuffle with a different (deterministic) seed each time.
563 shuffleUseLists(*M, I);
565 // Verify again before and after reversing.
566 verifyUseListOrder(*M);
568 verifyUseListOrder(*M);