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