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