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"
55 #define DEBUG_TYPE "use-list-order"
57 static cl::opt<std::string> InputFilename(cl::Positional,
58 cl::desc("<input bitcode file>"),
60 cl::value_desc("filename"));
62 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temp files"),
65 static cl::opt<unsigned>
66 NumShuffles("num-shuffles",
67 cl::desc("Number of times to shuffle and verify use-lists"),
75 bool init(const std::string &Ext);
76 bool writeBitcode(const Module &M) const;
77 bool writeAssembly(const Module &M) const;
78 std::unique_ptr<Module> readBitcode(LLVMContext &Context) const;
79 std::unique_ptr<Module> readAssembly(LLVMContext &Context) const;
83 DenseMap<const Value *, unsigned> IDs;
84 std::vector<const Value *> Values;
86 /// \brief Construct a value mapping for module.
88 /// Creates mapping from every value in \c M to an ID. This mapping includes
89 /// un-referencable values.
91 /// Every \a Value that gets serialized in some way should be represented
92 /// here. The order needs to be deterministic, but it's unnecessary to match
93 /// the value-ids in the bitcode writer.
95 /// All constants that are referenced by other values are included in the
96 /// mapping, but others -- which wouldn't be serialized -- are not.
97 ValueMapping(const Module &M);
99 /// \brief Map a value.
101 /// Maps a value. If it's a constant, maps all of its operands first.
102 void map(const Value *V);
103 unsigned lookup(const Value *V) const { return IDs.lookup(V); }
108 bool TempFile::init(const std::string &Ext) {
109 SmallVector<char, 64> Vector;
110 DEBUG(dbgs() << " - create-temp-file\n");
111 if (auto EC = sys::fs::createTemporaryFile("use-list-order", Ext, Vector)) {
113 DEBUG(dbgs() << "error: " << EC.message() << "\n");
116 assert(!Vector.empty());
118 Filename.assign(Vector.data(), Vector.data() + Vector.size());
119 Remover.setFile(Filename, !SaveTemps);
120 DEBUG(dbgs() << " - filename = " << Filename << "\n");
124 bool TempFile::writeBitcode(const Module &M) const {
125 DEBUG(dbgs() << " - write bitcode\n");
127 raw_fd_ostream OS(Filename, EC, sys::fs::F_None);
129 DEBUG(dbgs() << "error: " << EC.message() << "\n");
133 WriteBitcodeToFile(&M, OS);
137 bool TempFile::writeAssembly(const Module &M) const {
138 DEBUG(dbgs() << " - write assembly\n");
140 raw_fd_ostream OS(Filename, EC, sys::fs::F_Text);
142 DEBUG(dbgs() << "error: " << EC.message() << "\n");
150 std::unique_ptr<Module> TempFile::readBitcode(LLVMContext &Context) const {
151 DEBUG(dbgs() << " - read bitcode\n");
152 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOr =
153 MemoryBuffer::getFile(Filename);
155 DEBUG(dbgs() << "error: " << BufferOr.getError().message() << "\n");
159 MemoryBuffer *Buffer = BufferOr.get().get();
160 ErrorOr<Module *> ModuleOr =
161 parseBitcodeFile(Buffer->getMemBufferRef(), Context);
163 DEBUG(dbgs() << "error: " << ModuleOr.getError().message() << "\n");
166 return std::unique_ptr<Module>(ModuleOr.get());
169 std::unique_ptr<Module> TempFile::readAssembly(LLVMContext &Context) const {
170 DEBUG(dbgs() << " - read assembly\n");
172 std::unique_ptr<Module> M = parseAssemblyFile(Filename, Err, Context);
174 DEBUG(dbgs() << "error: "; Err.print("verify-use-list-order", dbgs()));
178 ValueMapping::ValueMapping(const Module &M) {
179 // Every value should be mapped, including things like void instructions and
180 // basic blocks that are kept out of the ValueEnumerator.
182 // The current mapping order makes it easier to debug the tables. It happens
183 // to be similar to the ID mapping when writing ValueEnumerator, but they
184 // aren't (and needn't be) in sync.
187 for (const GlobalVariable &G : M.globals())
189 for (const GlobalAlias &A : M.aliases())
191 for (const Function &F : M)
194 // Constants used by globals.
195 for (const GlobalVariable &G : M.globals())
196 if (G.hasInitializer())
197 map(G.getInitializer());
198 for (const GlobalAlias &A : M.aliases())
200 for (const Function &F : M)
201 if (F.hasPrefixData())
202 map(F.getPrefixData());
205 for (const Function &F : M) {
206 for (const Argument &A : F.args())
208 for (const BasicBlock &BB : F)
210 for (const BasicBlock &BB : F)
211 for (const Instruction &I : BB)
214 // Constants used by instructions.
215 for (const BasicBlock &BB : F)
216 for (const Instruction &I : BB)
217 for (const Value *Op : I.operands())
218 if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
224 void ValueMapping::map(const Value *V) {
228 if (auto *C = dyn_cast<Constant>(V))
229 if (!isa<GlobalValue>(C))
230 for (const Value *Op : C->operands())
234 IDs[V] = Values.size();
238 static void dumpMapping(const ValueMapping &VM) {
239 dbgs() << "value-mapping (size = " << VM.Values.size() << "):\n";
240 for (unsigned I = 0, E = VM.Values.size(); I != E; ++I) {
241 dbgs() << " - id = " << I << ", value = ";
242 VM.Values[I]->dump();
246 static void debugValue(const ValueMapping &M, unsigned I, StringRef Desc) {
247 const Value *V = M.Values[I];
248 dbgs() << " - " << Desc << " value = ";
250 for (const Use &U : V->uses()) {
251 dbgs() << " => use: op = " << U.getOperandNo()
252 << ", user-id = " << M.IDs.lookup(U.getUser()) << ", user = ";
257 static void debugUserMismatch(const ValueMapping &L, const ValueMapping &R,
259 dbgs() << " - fail: user mismatch: ID = " << I << "\n";
260 debugValue(L, I, "LHS");
261 debugValue(R, I, "RHS");
269 static void debugSizeMismatch(const ValueMapping &L, const ValueMapping &R) {
270 dbgs() << " - fail: map size: " << L.Values.size()
271 << " != " << R.Values.size() << "\n";
279 static bool matches(const ValueMapping &LM, const ValueMapping &RM) {
280 DEBUG(dbgs() << "compare value maps\n");
281 if (LM.Values.size() != RM.Values.size()) {
282 DEBUG(debugSizeMismatch(LM, RM));
286 // This mapping doesn't include dangling constant users, since those don't
287 // get serialized. However, checking if users are constant and calling
288 // isConstantUsed() on every one is very expensive. Instead, just check if
289 // the user is mapped.
290 auto skipUnmappedUsers =
291 [&](Value::const_use_iterator &U, Value::const_use_iterator E,
292 const ValueMapping &M) {
293 while (U != E && !M.lookup(U->getUser()))
297 // Iterate through all values, and check that both mappings have the same
299 for (unsigned I = 0, E = LM.Values.size(); I != E; ++I) {
300 const Value *L = LM.Values[I];
301 const Value *R = RM.Values[I];
302 auto LU = L->use_begin(), LE = L->use_end();
303 auto RU = R->use_begin(), RE = R->use_end();
304 skipUnmappedUsers(LU, LE, LM);
305 skipUnmappedUsers(RU, RE, RM);
309 DEBUG(debugUserMismatch(LM, RM, I));
312 if (LM.lookup(LU->getUser()) != RM.lookup(RU->getUser())) {
313 DEBUG(debugUserMismatch(LM, RM, I));
316 if (LU->getOperandNo() != RU->getOperandNo()) {
317 DEBUG(debugUserMismatch(LM, RM, I));
320 skipUnmappedUsers(++LU, LE, LM);
321 skipUnmappedUsers(++RU, RE, RM);
324 DEBUG(debugUserMismatch(LM, RM, I));
332 static void verifyAfterRoundTrip(const Module &M,
333 std::unique_ptr<Module> OtherM) {
335 report_fatal_error("parsing failed");
336 if (verifyModule(*OtherM, &errs()))
337 report_fatal_error("verification failed");
338 if (!matches(ValueMapping(M), ValueMapping(*OtherM)))
339 report_fatal_error("use-list order changed");
341 static void verifyBitcodeUseListOrder(const Module &M) {
342 errs() << "*** verify-use-list-order: bitcode ***\n";
345 report_fatal_error("failed to initialize bitcode file");
347 if (F.writeBitcode(M))
348 report_fatal_error("failed to write bitcode");
351 verifyAfterRoundTrip(M, F.readBitcode(Context));
354 static void verifyAssemblyUseListOrder(const Module &M) {
355 errs() << "*** verify-use-list-order: assembly ***\n";
358 report_fatal_error("failed to initialize assembly file");
360 if (F.writeAssembly(M))
361 report_fatal_error("failed to write assembly");
364 verifyAfterRoundTrip(M, F.readAssembly(Context));
367 static void verifyUseListOrder(const Module &M) {
368 verifyBitcodeUseListOrder(M);
369 verifyAssemblyUseListOrder(M);
372 static void shuffleValueUseLists(Value *V, std::minstd_rand0 &Gen,
373 DenseSet<Value *> &Seen) {
374 if (!Seen.insert(V).second)
377 if (auto *C = dyn_cast<Constant>(V))
378 if (!isa<GlobalValue>(C))
379 for (Value *Op : C->operands())
380 shuffleValueUseLists(Op, Gen, Seen);
382 if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
383 // Nothing to shuffle for 0 or 1 users.
386 // Generate random numbers between 10 and 99, which will line up nicely in
387 // debug output. We're not worried about collisons here.
388 DEBUG(dbgs() << "V = "; V->dump());
389 std::uniform_int_distribution<short> Dist(10, 99);
390 SmallDenseMap<const Use *, short, 16> Order;
392 [&Order](const Use &L, const Use &R) { return Order[&L] < Order[&R]; };
394 for (const Use &U : V->uses()) {
397 DEBUG(dbgs() << " - order: " << I << ", op = " << U.getOperandNo()
399 U.getUser()->dump());
401 } while (std::is_sorted(V->use_begin(), V->use_end(), compareUses));
403 DEBUG(dbgs() << " => shuffle\n");
404 V->sortUseList(compareUses);
407 for (const Use &U : V->uses()) {
408 dbgs() << " - order: " << Order.lookup(&U)
409 << ", op = " << U.getOperandNo() << ", U = ";
415 static void reverseValueUseLists(Value *V, DenseSet<Value *> &Seen) {
416 if (!Seen.insert(V).second)
419 if (auto *C = dyn_cast<Constant>(V))
420 if (!isa<GlobalValue>(C))
421 for (Value *Op : C->operands())
422 reverseValueUseLists(Op, Seen);
424 if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
425 // Nothing to shuffle for 0 or 1 users.
431 for (const Use &U : V->uses()) {
432 dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
435 dbgs() << " => reverse\n";
441 for (const Use &U : V->uses()) {
442 dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
448 template <class Changer>
449 static void changeUseLists(Module &M, Changer changeValueUseList) {
450 // Visit every value that would be serialized to an IR file.
453 for (GlobalVariable &G : M.globals())
454 changeValueUseList(&G);
455 for (GlobalAlias &A : M.aliases())
456 changeValueUseList(&A);
457 for (Function &F : M)
458 changeValueUseList(&F);
460 // Constants used by globals.
461 for (GlobalVariable &G : M.globals())
462 if (G.hasInitializer())
463 changeValueUseList(G.getInitializer());
464 for (GlobalAlias &A : M.aliases())
465 changeValueUseList(A.getAliasee());
466 for (Function &F : M)
467 if (F.hasPrefixData())
468 changeValueUseList(F.getPrefixData());
471 for (Function &F : M) {
472 for (Argument &A : F.args())
473 changeValueUseList(&A);
474 for (BasicBlock &BB : F)
475 changeValueUseList(&BB);
476 for (BasicBlock &BB : F)
477 for (Instruction &I : BB)
478 changeValueUseList(&I);
480 // Constants used by instructions.
481 for (BasicBlock &BB : F)
482 for (Instruction &I : BB)
483 for (Value *Op : I.operands())
484 if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
486 changeValueUseList(Op);
489 if (verifyModule(M, &errs()))
490 report_fatal_error("verification failed");
493 static void shuffleUseLists(Module &M, unsigned SeedOffset) {
494 errs() << "*** shuffle-use-lists ***\n";
495 std::minstd_rand0 Gen(std::minstd_rand0::default_seed + SeedOffset);
496 DenseSet<Value *> Seen;
497 changeUseLists(M, [&](Value *V) { shuffleValueUseLists(V, Gen, Seen); });
498 DEBUG(dbgs() << "\n");
501 static void reverseUseLists(Module &M) {
502 errs() << "*** reverse-use-lists ***\n";
503 DenseSet<Value *> Seen;
504 changeUseLists(M, [&](Value *V) { reverseValueUseLists(V, Seen); });
505 DEBUG(dbgs() << "\n");
508 int main(int argc, char **argv) {
509 sys::PrintStackTraceOnErrorSignal();
510 llvm::PrettyStackTraceProgram X(argc, argv);
512 // Enable debug stream buffering.
513 EnableDebugBuffering = true;
515 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
516 LLVMContext &Context = getGlobalContext();
518 cl::ParseCommandLineOptions(argc, argv,
519 "llvm tool to verify use-list order\n");
523 // Load the input module...
524 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
527 Err.print(argv[0], errs());
530 if (verifyModule(*M, &errs()))
531 report_fatal_error("verification failed");
533 errs() << "*** verify-use-list-order ***\n";
534 // Can't verify if order isn't preserved.
535 if (!shouldPreserveBitcodeUseListOrder()) {
536 errs() << "warning: forcing -preserve-bc-use-list-order\n";
537 setPreserveBitcodeUseListOrder(true);
539 if (!shouldPreserveAssemblyUseListOrder()) {
540 errs() << "warning: forcing -preserve-ll-use-list-order\n";
541 setPreserveAssemblyUseListOrder(true);
544 // Verify the use lists now and after reversing them.
545 verifyUseListOrder(*M);
547 verifyUseListOrder(*M);
549 for (unsigned I = 0, E = NumShuffles; I != E; ++I) {
550 errs() << "*** shuffle iteration: " << I + 1 << " of " << E << " ***\n";
552 // Shuffle with a different (deterministic) seed each time.
553 shuffleUseLists(*M, I);
555 // Verify again before and after reversing.
556 verifyUseListOrder(*M);
558 verifyUseListOrder(*M);