1 //===- verify-uselistorder.cpp - The LLVM Modular Optimizer ---------------===//
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
7 //===----------------------------------------------------------------------===//
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.
13 // The shuffles are deterministic, but guarantee that use-lists will change.
14 // The algorithm per iteration is as follows:
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.
19 // 2. Visit every Value in a deterministic order.
21 // 3. Assign a random number to each Use in the Value's use-list in order.
23 // 4. If the numbers are already in order, reassign numbers until they aren't.
25 // 5. Sort the use-list using Value::sortUseList(), which is a stable sort.
27 //===----------------------------------------------------------------------===//
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"
54 #define DEBUG_TYPE "uselistorder"
56 static cl::OptionCategory
Cat("verify-uselistorder Options");
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"),
69 cl::init(1), cl::cat(Cat
));
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 /// 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
);
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 LLVM_DEBUG(dbgs() << " - create-temp-file\n");
112 if (auto EC
= sys::fs::createTemporaryFile("uselistorder", Ext
, Vector
)) {
113 errs() << "verify-uselistorder: error: " << EC
.message() << "\n";
116 assert(!Vector
.empty());
118 Filename
.assign(Vector
.data(), Vector
.data() + Vector
.size());
119 Remover
.setFile(Filename
, !SaveTemps
);
121 outs() << " - filename = " << Filename
<< "\n";
125 bool TempFile::writeBitcode(const Module
&M
) const {
126 LLVM_DEBUG(dbgs() << " - write bitcode\n");
128 raw_fd_ostream
OS(Filename
, EC
, sys::fs::OF_None
);
130 errs() << "verify-uselistorder: error: " << EC
.message() << "\n";
134 WriteBitcodeToFile(M
, OS
, /* ShouldPreserveUseListOrder */ true);
138 bool TempFile::writeAssembly(const Module
&M
) const {
139 LLVM_DEBUG(dbgs() << " - write assembly\n");
141 raw_fd_ostream
OS(Filename
, EC
, sys::fs::OF_TextWithCRLF
);
143 errs() << "verify-uselistorder: error: " << EC
.message() << "\n";
147 M
.print(OS
, nullptr, /* ShouldPreserveUseListOrder */ true);
151 std::unique_ptr
<Module
> TempFile::readBitcode(LLVMContext
&Context
) const {
152 LLVM_DEBUG(dbgs() << " - read bitcode\n");
153 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferOr
=
154 MemoryBuffer::getFile(Filename
);
156 errs() << "verify-uselistorder: error: " << BufferOr
.getError().message()
161 MemoryBuffer
*Buffer
= BufferOr
.get().get();
162 Expected
<std::unique_ptr
<Module
>> ModuleOr
=
163 parseBitcodeFile(Buffer
->getMemBufferRef(), Context
);
165 logAllUnhandledErrors(ModuleOr
.takeError(), errs(),
166 "verify-uselistorder: error: ");
169 return std::move(ModuleOr
.get());
172 std::unique_ptr
<Module
> TempFile::readAssembly(LLVMContext
&Context
) const {
173 LLVM_DEBUG(dbgs() << " - read assembly\n");
175 std::unique_ptr
<Module
> M
= parseAssemblyFile(Filename
, Err
, Context
);
177 Err
.print("verify-uselistorder", errs());
181 ValueMapping::ValueMapping(const Module
&M
) {
182 // Every value should be mapped, including things like void instructions and
183 // basic blocks that are kept out of the ValueEnumerator.
185 // The current mapping order makes it easier to debug the tables. It happens
186 // to be similar to the ID mapping when writing ValueEnumerator, but they
187 // aren't (and needn't be) in sync.
190 for (const GlobalVariable
&G
: M
.globals())
192 for (const GlobalAlias
&A
: M
.aliases())
194 for (const GlobalIFunc
&IF
: M
.ifuncs())
196 for (const Function
&F
: M
)
199 // Constants used by globals.
200 for (const GlobalVariable
&G
: M
.globals())
201 if (G
.hasInitializer())
202 map(G
.getInitializer());
203 for (const GlobalAlias
&A
: M
.aliases())
205 for (const GlobalIFunc
&IF
: M
.ifuncs())
206 map(IF
.getResolver());
207 for (const Function
&F
: M
)
208 for (Value
*Op
: F
.operands())
212 for (const Function
&F
: M
) {
213 for (const Argument
&A
: F
.args())
215 for (const BasicBlock
&BB
: F
)
217 for (const BasicBlock
&BB
: F
)
218 for (const Instruction
&I
: BB
)
221 // Constants used by instructions.
222 for (const BasicBlock
&BB
: F
)
223 for (const Instruction
&I
: BB
)
224 for (const Value
*Op
: I
.operands()) {
225 // Look through a metadata wrapper.
226 if (const auto *MAV
= dyn_cast
<MetadataAsValue
>(Op
))
227 if (const auto *VAM
= dyn_cast
<ValueAsMetadata
>(MAV
->getMetadata()))
228 Op
= VAM
->getValue();
230 if ((isa
<Constant
>(Op
) && !isa
<GlobalValue
>(*Op
)) ||
237 void ValueMapping::map(const Value
*V
) {
241 if (auto *C
= dyn_cast
<Constant
>(V
))
242 if (!isa
<GlobalValue
>(C
))
243 for (const Value
*Op
: C
->operands())
247 IDs
[V
] = Values
.size();
251 static void dumpMapping(const ValueMapping
&VM
) {
252 dbgs() << "value-mapping (size = " << VM
.Values
.size() << "):\n";
253 for (unsigned I
= 0, E
= VM
.Values
.size(); I
!= E
; ++I
) {
254 dbgs() << " - id = " << I
<< ", value = ";
255 VM
.Values
[I
]->dump();
259 static void debugValue(const ValueMapping
&M
, unsigned I
, StringRef Desc
) {
260 const Value
*V
= M
.Values
[I
];
261 dbgs() << " - " << Desc
<< " value = ";
263 for (const Use
&U
: V
->uses()) {
264 dbgs() << " => use: op = " << U
.getOperandNo()
265 << ", user-id = " << M
.IDs
.lookup(U
.getUser()) << ", user = ";
270 static void debugUserMismatch(const ValueMapping
&L
, const ValueMapping
&R
,
272 dbgs() << " - fail: user mismatch: ID = " << I
<< "\n";
273 debugValue(L
, I
, "LHS");
274 debugValue(R
, I
, "RHS");
282 static void debugSizeMismatch(const ValueMapping
&L
, const ValueMapping
&R
) {
283 dbgs() << " - fail: map size: " << L
.Values
.size()
284 << " != " << R
.Values
.size() << "\n";
292 static bool matches(const ValueMapping
&LM
, const ValueMapping
&RM
) {
293 LLVM_DEBUG(dbgs() << "compare value maps\n");
294 if (LM
.Values
.size() != RM
.Values
.size()) {
295 LLVM_DEBUG(debugSizeMismatch(LM
, RM
));
299 // This mapping doesn't include dangling constant users, since those don't
300 // get serialized. However, checking if users are constant and calling
301 // isConstantUsed() on every one is very expensive. Instead, just check if
302 // the user is mapped.
303 auto skipUnmappedUsers
=
304 [&](Value::const_use_iterator
&U
, Value::const_use_iterator E
,
305 const ValueMapping
&M
) {
306 while (U
!= E
&& !M
.lookup(U
->getUser()))
310 // Iterate through all values, and check that both mappings have the same
312 for (unsigned I
= 0, E
= LM
.Values
.size(); I
!= E
; ++I
) {
313 const Value
*L
= LM
.Values
[I
];
314 const Value
*R
= RM
.Values
[I
];
315 auto LU
= L
->use_begin(), LE
= L
->use_end();
316 auto RU
= R
->use_begin(), RE
= R
->use_end();
317 skipUnmappedUsers(LU
, LE
, LM
);
318 skipUnmappedUsers(RU
, RE
, RM
);
322 LLVM_DEBUG(debugUserMismatch(LM
, RM
, I
));
325 if (LM
.lookup(LU
->getUser()) != RM
.lookup(RU
->getUser())) {
326 LLVM_DEBUG(debugUserMismatch(LM
, RM
, I
));
329 if (LU
->getOperandNo() != RU
->getOperandNo()) {
330 LLVM_DEBUG(debugUserMismatch(LM
, RM
, I
));
333 skipUnmappedUsers(++LU
, LE
, LM
);
334 skipUnmappedUsers(++RU
, RE
, RM
);
337 LLVM_DEBUG(debugUserMismatch(LM
, RM
, I
));
345 static void verifyAfterRoundTrip(const Module
&M
,
346 std::unique_ptr
<Module
> OtherM
) {
348 report_fatal_error("parsing failed");
349 if (verifyModule(*OtherM
, &errs()))
350 report_fatal_error("verification failed");
351 if (!matches(ValueMapping(M
), ValueMapping(*OtherM
)))
352 report_fatal_error("use-list order changed");
355 static void verifyBitcodeUseListOrder(const Module
&M
) {
358 report_fatal_error("failed to initialize bitcode file");
360 if (F
.writeBitcode(M
))
361 report_fatal_error("failed to write bitcode");
364 verifyAfterRoundTrip(M
, F
.readBitcode(Context
));
367 static void verifyAssemblyUseListOrder(const Module
&M
) {
370 report_fatal_error("failed to initialize assembly file");
372 if (F
.writeAssembly(M
))
373 report_fatal_error("failed to write assembly");
376 verifyAfterRoundTrip(M
, F
.readAssembly(Context
));
379 static void verifyUseListOrder(const Module
&M
) {
380 outs() << "verify bitcode\n";
381 verifyBitcodeUseListOrder(M
);
382 outs() << "verify assembly\n";
383 verifyAssemblyUseListOrder(M
);
386 static void shuffleValueUseLists(Value
*V
, std::minstd_rand0
&Gen
,
387 DenseSet
<Value
*> &Seen
) {
388 if (!Seen
.insert(V
).second
)
391 if (auto *C
= dyn_cast
<Constant
>(V
))
392 if (!isa
<GlobalValue
>(C
))
393 for (Value
*Op
: C
->operands())
394 shuffleValueUseLists(Op
, Gen
, Seen
);
396 if (V
->use_empty() || std::next(V
->use_begin()) == V
->use_end())
397 // Nothing to shuffle for 0 or 1 users.
400 // Generate random numbers between 10 and 99, which will line up nicely in
401 // debug output. We're not worried about collisions here.
402 LLVM_DEBUG(dbgs() << "V = "; V
->dump());
403 std::uniform_int_distribution
<short> Dist(10, 99);
404 SmallDenseMap
<const Use
*, short, 16> Order
;
406 [&Order
](const Use
&L
, const Use
&R
) { return Order
[&L
] < Order
[&R
]; };
408 for (const Use
&U
: V
->uses()) {
411 LLVM_DEBUG(dbgs() << " - order: " << I
<< ", op = " << U
.getOperandNo()
413 U
.getUser()->dump());
415 } while (std::is_sorted(V
->use_begin(), V
->use_end(), compareUses
));
417 LLVM_DEBUG(dbgs() << " => shuffle\n");
418 V
->sortUseList(compareUses
);
421 for (const Use
&U
: V
->uses()) {
422 dbgs() << " - order: " << Order
.lookup(&U
)
423 << ", op = " << U
.getOperandNo() << ", U = ";
429 static void reverseValueUseLists(Value
*V
, DenseSet
<Value
*> &Seen
) {
430 if (!Seen
.insert(V
).second
)
433 if (auto *C
= dyn_cast
<Constant
>(V
))
434 if (!isa
<GlobalValue
>(C
))
435 for (Value
*Op
: C
->operands())
436 reverseValueUseLists(Op
, Seen
);
438 if (V
->use_empty() || std::next(V
->use_begin()) == V
->use_end())
439 // Nothing to shuffle for 0 or 1 users.
445 for (const Use
&U
: V
->uses()) {
446 dbgs() << " - order: op = " << U
.getOperandNo() << ", U = ";
449 dbgs() << " => reverse\n";
455 for (const Use
&U
: V
->uses()) {
456 dbgs() << " - order: op = " << U
.getOperandNo() << ", U = ";
462 template <class Changer
>
463 static void changeUseLists(Module
&M
, Changer changeValueUseList
) {
464 // Visit every value that would be serialized to an IR file.
467 for (GlobalVariable
&G
: M
.globals())
468 changeValueUseList(&G
);
469 for (GlobalAlias
&A
: M
.aliases())
470 changeValueUseList(&A
);
471 for (GlobalIFunc
&IF
: M
.ifuncs())
472 changeValueUseList(&IF
);
473 for (Function
&F
: M
)
474 changeValueUseList(&F
);
476 // Constants used by globals.
477 for (GlobalVariable
&G
: M
.globals())
478 if (G
.hasInitializer())
479 changeValueUseList(G
.getInitializer());
480 for (GlobalAlias
&A
: M
.aliases())
481 changeValueUseList(A
.getAliasee());
482 for (GlobalIFunc
&IF
: M
.ifuncs())
483 changeValueUseList(IF
.getResolver());
484 for (Function
&F
: M
)
485 for (Value
*Op
: F
.operands())
486 changeValueUseList(Op
);
489 for (Function
&F
: M
) {
490 for (Argument
&A
: F
.args())
491 changeValueUseList(&A
);
492 for (BasicBlock
&BB
: F
)
493 changeValueUseList(&BB
);
494 for (BasicBlock
&BB
: F
)
495 for (Instruction
&I
: BB
)
496 changeValueUseList(&I
);
498 // Constants used by instructions.
499 for (BasicBlock
&BB
: F
)
500 for (Instruction
&I
: BB
)
501 for (Value
*Op
: I
.operands()) {
502 // Look through a metadata wrapper.
503 if (auto *MAV
= dyn_cast
<MetadataAsValue
>(Op
))
504 if (auto *VAM
= dyn_cast
<ValueAsMetadata
>(MAV
->getMetadata()))
505 Op
= VAM
->getValue();
506 if ((isa
<Constant
>(Op
) && !isa
<GlobalValue
>(*Op
)) ||
508 changeValueUseList(Op
);
512 if (verifyModule(M
, &errs()))
513 report_fatal_error("verification failed");
516 static void shuffleUseLists(Module
&M
, unsigned SeedOffset
) {
517 std::minstd_rand0
Gen(std::minstd_rand0::default_seed
+ SeedOffset
);
518 DenseSet
<Value
*> Seen
;
519 changeUseLists(M
, [&](Value
*V
) { shuffleValueUseLists(V
, Gen
, Seen
); });
520 LLVM_DEBUG(dbgs() << "\n");
523 static void reverseUseLists(Module
&M
) {
524 DenseSet
<Value
*> Seen
;
525 changeUseLists(M
, [&](Value
*V
) { reverseValueUseLists(V
, Seen
); });
526 LLVM_DEBUG(dbgs() << "\n");
529 int main(int argc
, char **argv
) {
530 InitLLVM
X(argc
, argv
);
532 // Enable debug stream buffering.
533 EnableDebugBuffering
= true;
535 cl::HideUnrelatedOptions(Cat
);
536 cl::ParseCommandLineOptions(argc
, argv
,
537 "llvm tool to verify use-list order\n");
542 // Load the input module...
543 std::unique_ptr
<Module
> M
= parseIRFile(InputFilename
, Err
, Context
);
546 Err
.print(argv
[0], errs());
549 if (verifyModule(*M
, &errs())) {
550 errs() << argv
[0] << ": " << InputFilename
551 << ": error: input module is broken!\n";
555 // Verify the use lists now and after reversing them.
556 outs() << "*** verify-uselistorder ***\n";
557 verifyUseListOrder(*M
);
558 outs() << "reverse\n";
560 verifyUseListOrder(*M
);
562 for (unsigned I
= 0, E
= NumShuffles
; I
!= E
; ++I
) {
565 // Shuffle with a different (deterministic) seed each time.
566 outs() << "shuffle (" << I
+ 1 << " of " << E
<< ")\n";
567 shuffleUseLists(*M
, I
);
569 // Verify again before and after reversing.
570 verifyUseListOrder(*M
);
571 outs() << "reverse\n";
573 verifyUseListOrder(*M
);