[llvm-objcopy] [COFF] Fix warnings abuilt missing field initialization. NFC.
[llvm-complete.git] / tools / verify-uselistorder / verify-uselistorder.cpp
blob99c7007e4e990cc75562b529fa376a6b39869fd2
1 //===- verify-uselistorder.cpp - The LLVM Modular Optimizer ---------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/BitcodeReader.h"
34 #include "llvm/Bitcode/BitcodeWriter.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/UseListOrder.h"
38 #include "llvm/IR/Verifier.h"
39 #include "llvm/IRReader/IRReader.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/FileUtilities.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/SystemUtils.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include <random>
51 #include <vector>
53 using namespace llvm;
55 #define DEBUG_TYPE "uselistorder"
57 static cl::opt<std::string> InputFilename(cl::Positional,
58 cl::desc("<input bitcode file>"),
59 cl::init("-"),
60 cl::value_desc("filename"));
62 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temp files"),
63 cl::init(false));
65 static cl::opt<unsigned>
66 NumShuffles("num-shuffles",
67 cl::desc("Number of times to shuffle and verify use-lists"),
68 cl::init(1));
70 namespace {
72 struct TempFile {
73 std::string Filename;
74 FileRemover Remover;
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;
82 struct ValueMapping {
83 DenseMap<const Value *, unsigned> IDs;
84 std::vector<const Value *> Values;
86 /// Construct a value mapping for module.
87 ///
88 /// Creates mapping from every value in \c M to an ID. This mapping includes
89 /// un-referencable values.
90 ///
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.
94 ///
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 /// 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); }
106 } // end namespace
108 bool TempFile::init(const std::string &Ext) {
109 SmallVector<char, 64> Vector;
110 LLVM_DEBUG(dbgs() << " - create-temp-file\n");
111 if (auto EC = sys::fs::createTemporaryFile("uselistorder", Ext, Vector)) {
112 errs() << "verify-uselistorder: error: " << EC.message() << "\n";
113 return true;
115 assert(!Vector.empty());
117 Filename.assign(Vector.data(), Vector.data() + Vector.size());
118 Remover.setFile(Filename, !SaveTemps);
119 if (SaveTemps)
120 outs() << " - filename = " << Filename << "\n";
121 return false;
124 bool TempFile::writeBitcode(const Module &M) const {
125 LLVM_DEBUG(dbgs() << " - write bitcode\n");
126 std::error_code EC;
127 raw_fd_ostream OS(Filename, EC, sys::fs::F_None);
128 if (EC) {
129 errs() << "verify-uselistorder: error: " << EC.message() << "\n";
130 return true;
133 WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
134 return false;
137 bool TempFile::writeAssembly(const Module &M) const {
138 LLVM_DEBUG(dbgs() << " - write assembly\n");
139 std::error_code EC;
140 raw_fd_ostream OS(Filename, EC, sys::fs::F_Text);
141 if (EC) {
142 errs() << "verify-uselistorder: error: " << EC.message() << "\n";
143 return true;
146 M.print(OS, nullptr, /* ShouldPreserveUseListOrder */ true);
147 return false;
150 std::unique_ptr<Module> TempFile::readBitcode(LLVMContext &Context) const {
151 LLVM_DEBUG(dbgs() << " - read bitcode\n");
152 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOr =
153 MemoryBuffer::getFile(Filename);
154 if (!BufferOr) {
155 errs() << "verify-uselistorder: error: " << BufferOr.getError().message()
156 << "\n";
157 return nullptr;
160 MemoryBuffer *Buffer = BufferOr.get().get();
161 Expected<std::unique_ptr<Module>> ModuleOr =
162 parseBitcodeFile(Buffer->getMemBufferRef(), Context);
163 if (!ModuleOr) {
164 logAllUnhandledErrors(ModuleOr.takeError(), errs(),
165 "verify-uselistorder: error: ");
166 return nullptr;
168 return std::move(ModuleOr.get());
171 std::unique_ptr<Module> TempFile::readAssembly(LLVMContext &Context) const {
172 LLVM_DEBUG(dbgs() << " - read assembly\n");
173 SMDiagnostic Err;
174 std::unique_ptr<Module> M = parseAssemblyFile(Filename, Err, Context);
175 if (!M.get())
176 Err.print("verify-uselistorder", errs());
177 return M;
180 ValueMapping::ValueMapping(const Module &M) {
181 // Every value should be mapped, including things like void instructions and
182 // basic blocks that are kept out of the ValueEnumerator.
184 // The current mapping order makes it easier to debug the tables. It happens
185 // to be similar to the ID mapping when writing ValueEnumerator, but they
186 // aren't (and needn't be) in sync.
188 // Globals.
189 for (const GlobalVariable &G : M.globals())
190 map(&G);
191 for (const GlobalAlias &A : M.aliases())
192 map(&A);
193 for (const GlobalIFunc &IF : M.ifuncs())
194 map(&IF);
195 for (const Function &F : M)
196 map(&F);
198 // Constants used by globals.
199 for (const GlobalVariable &G : M.globals())
200 if (G.hasInitializer())
201 map(G.getInitializer());
202 for (const GlobalAlias &A : M.aliases())
203 map(A.getAliasee());
204 for (const GlobalIFunc &IF : M.ifuncs())
205 map(IF.getResolver());
206 for (const Function &F : M) {
207 if (F.hasPrefixData())
208 map(F.getPrefixData());
209 if (F.hasPrologueData())
210 map(F.getPrologueData());
211 if (F.hasPersonalityFn())
212 map(F.getPersonalityFn());
215 // Function bodies.
216 for (const Function &F : M) {
217 for (const Argument &A : F.args())
218 map(&A);
219 for (const BasicBlock &BB : F)
220 map(&BB);
221 for (const BasicBlock &BB : F)
222 for (const Instruction &I : BB)
223 map(&I);
225 // Constants used by instructions.
226 for (const BasicBlock &BB : F)
227 for (const Instruction &I : BB)
228 for (const Value *Op : I.operands())
229 if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
230 isa<InlineAsm>(Op))
231 map(Op);
235 void ValueMapping::map(const Value *V) {
236 if (IDs.lookup(V))
237 return;
239 if (auto *C = dyn_cast<Constant>(V))
240 if (!isa<GlobalValue>(C))
241 for (const Value *Op : C->operands())
242 map(Op);
244 Values.push_back(V);
245 IDs[V] = Values.size();
248 #ifndef NDEBUG
249 static void dumpMapping(const ValueMapping &VM) {
250 dbgs() << "value-mapping (size = " << VM.Values.size() << "):\n";
251 for (unsigned I = 0, E = VM.Values.size(); I != E; ++I) {
252 dbgs() << " - id = " << I << ", value = ";
253 VM.Values[I]->dump();
257 static void debugValue(const ValueMapping &M, unsigned I, StringRef Desc) {
258 const Value *V = M.Values[I];
259 dbgs() << " - " << Desc << " value = ";
260 V->dump();
261 for (const Use &U : V->uses()) {
262 dbgs() << " => use: op = " << U.getOperandNo()
263 << ", user-id = " << M.IDs.lookup(U.getUser()) << ", user = ";
264 U.getUser()->dump();
268 static void debugUserMismatch(const ValueMapping &L, const ValueMapping &R,
269 unsigned I) {
270 dbgs() << " - fail: user mismatch: ID = " << I << "\n";
271 debugValue(L, I, "LHS");
272 debugValue(R, I, "RHS");
274 dbgs() << "\nlhs-";
275 dumpMapping(L);
276 dbgs() << "\nrhs-";
277 dumpMapping(R);
280 static void debugSizeMismatch(const ValueMapping &L, const ValueMapping &R) {
281 dbgs() << " - fail: map size: " << L.Values.size()
282 << " != " << R.Values.size() << "\n";
283 dbgs() << "\nlhs-";
284 dumpMapping(L);
285 dbgs() << "\nrhs-";
286 dumpMapping(R);
288 #endif
290 static bool matches(const ValueMapping &LM, const ValueMapping &RM) {
291 LLVM_DEBUG(dbgs() << "compare value maps\n");
292 if (LM.Values.size() != RM.Values.size()) {
293 LLVM_DEBUG(debugSizeMismatch(LM, RM));
294 return false;
297 // This mapping doesn't include dangling constant users, since those don't
298 // get serialized. However, checking if users are constant and calling
299 // isConstantUsed() on every one is very expensive. Instead, just check if
300 // the user is mapped.
301 auto skipUnmappedUsers =
302 [&](Value::const_use_iterator &U, Value::const_use_iterator E,
303 const ValueMapping &M) {
304 while (U != E && !M.lookup(U->getUser()))
305 ++U;
308 // Iterate through all values, and check that both mappings have the same
309 // users.
310 for (unsigned I = 0, E = LM.Values.size(); I != E; ++I) {
311 const Value *L = LM.Values[I];
312 const Value *R = RM.Values[I];
313 auto LU = L->use_begin(), LE = L->use_end();
314 auto RU = R->use_begin(), RE = R->use_end();
315 skipUnmappedUsers(LU, LE, LM);
316 skipUnmappedUsers(RU, RE, RM);
318 while (LU != LE) {
319 if (RU == RE) {
320 LLVM_DEBUG(debugUserMismatch(LM, RM, I));
321 return false;
323 if (LM.lookup(LU->getUser()) != RM.lookup(RU->getUser())) {
324 LLVM_DEBUG(debugUserMismatch(LM, RM, I));
325 return false;
327 if (LU->getOperandNo() != RU->getOperandNo()) {
328 LLVM_DEBUG(debugUserMismatch(LM, RM, I));
329 return false;
331 skipUnmappedUsers(++LU, LE, LM);
332 skipUnmappedUsers(++RU, RE, RM);
334 if (RU != RE) {
335 LLVM_DEBUG(debugUserMismatch(LM, RM, I));
336 return false;
340 return true;
343 static void verifyAfterRoundTrip(const Module &M,
344 std::unique_ptr<Module> OtherM) {
345 if (!OtherM)
346 report_fatal_error("parsing failed");
347 if (verifyModule(*OtherM, &errs()))
348 report_fatal_error("verification failed");
349 if (!matches(ValueMapping(M), ValueMapping(*OtherM)))
350 report_fatal_error("use-list order changed");
353 static void verifyBitcodeUseListOrder(const Module &M) {
354 TempFile F;
355 if (F.init("bc"))
356 report_fatal_error("failed to initialize bitcode file");
358 if (F.writeBitcode(M))
359 report_fatal_error("failed to write bitcode");
361 LLVMContext Context;
362 verifyAfterRoundTrip(M, F.readBitcode(Context));
365 static void verifyAssemblyUseListOrder(const Module &M) {
366 TempFile F;
367 if (F.init("ll"))
368 report_fatal_error("failed to initialize assembly file");
370 if (F.writeAssembly(M))
371 report_fatal_error("failed to write assembly");
373 LLVMContext Context;
374 verifyAfterRoundTrip(M, F.readAssembly(Context));
377 static void verifyUseListOrder(const Module &M) {
378 outs() << "verify bitcode\n";
379 verifyBitcodeUseListOrder(M);
380 outs() << "verify assembly\n";
381 verifyAssemblyUseListOrder(M);
384 static void shuffleValueUseLists(Value *V, std::minstd_rand0 &Gen,
385 DenseSet<Value *> &Seen) {
386 if (!Seen.insert(V).second)
387 return;
389 if (auto *C = dyn_cast<Constant>(V))
390 if (!isa<GlobalValue>(C))
391 for (Value *Op : C->operands())
392 shuffleValueUseLists(Op, Gen, Seen);
394 if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
395 // Nothing to shuffle for 0 or 1 users.
396 return;
398 // Generate random numbers between 10 and 99, which will line up nicely in
399 // debug output. We're not worried about collisons here.
400 LLVM_DEBUG(dbgs() << "V = "; V->dump());
401 std::uniform_int_distribution<short> Dist(10, 99);
402 SmallDenseMap<const Use *, short, 16> Order;
403 auto compareUses =
404 [&Order](const Use &L, const Use &R) { return Order[&L] < Order[&R]; };
405 do {
406 for (const Use &U : V->uses()) {
407 auto I = Dist(Gen);
408 Order[&U] = I;
409 LLVM_DEBUG(dbgs() << " - order: " << I << ", op = " << U.getOperandNo()
410 << ", U = ";
411 U.getUser()->dump());
413 } while (std::is_sorted(V->use_begin(), V->use_end(), compareUses));
415 LLVM_DEBUG(dbgs() << " => shuffle\n");
416 V->sortUseList(compareUses);
418 LLVM_DEBUG({
419 for (const Use &U : V->uses()) {
420 dbgs() << " - order: " << Order.lookup(&U)
421 << ", op = " << U.getOperandNo() << ", U = ";
422 U.getUser()->dump();
427 static void reverseValueUseLists(Value *V, DenseSet<Value *> &Seen) {
428 if (!Seen.insert(V).second)
429 return;
431 if (auto *C = dyn_cast<Constant>(V))
432 if (!isa<GlobalValue>(C))
433 for (Value *Op : C->operands())
434 reverseValueUseLists(Op, Seen);
436 if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
437 // Nothing to shuffle for 0 or 1 users.
438 return;
440 LLVM_DEBUG({
441 dbgs() << "V = ";
442 V->dump();
443 for (const Use &U : V->uses()) {
444 dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
445 U.getUser()->dump();
447 dbgs() << " => reverse\n";
450 V->reverseUseList();
452 LLVM_DEBUG({
453 for (const Use &U : V->uses()) {
454 dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
455 U.getUser()->dump();
460 template <class Changer>
461 static void changeUseLists(Module &M, Changer changeValueUseList) {
462 // Visit every value that would be serialized to an IR file.
464 // Globals.
465 for (GlobalVariable &G : M.globals())
466 changeValueUseList(&G);
467 for (GlobalAlias &A : M.aliases())
468 changeValueUseList(&A);
469 for (GlobalIFunc &IF : M.ifuncs())
470 changeValueUseList(&IF);
471 for (Function &F : M)
472 changeValueUseList(&F);
474 // Constants used by globals.
475 for (GlobalVariable &G : M.globals())
476 if (G.hasInitializer())
477 changeValueUseList(G.getInitializer());
478 for (GlobalAlias &A : M.aliases())
479 changeValueUseList(A.getAliasee());
480 for (GlobalIFunc &IF : M.ifuncs())
481 changeValueUseList(IF.getResolver());
482 for (Function &F : M) {
483 if (F.hasPrefixData())
484 changeValueUseList(F.getPrefixData());
485 if (F.hasPrologueData())
486 changeValueUseList(F.getPrologueData());
487 if (F.hasPersonalityFn())
488 changeValueUseList(F.getPersonalityFn());
491 // Function bodies.
492 for (Function &F : M) {
493 for (Argument &A : F.args())
494 changeValueUseList(&A);
495 for (BasicBlock &BB : F)
496 changeValueUseList(&BB);
497 for (BasicBlock &BB : F)
498 for (Instruction &I : BB)
499 changeValueUseList(&I);
501 // Constants used by instructions.
502 for (BasicBlock &BB : F)
503 for (Instruction &I : BB)
504 for (Value *Op : I.operands())
505 if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
506 isa<InlineAsm>(Op))
507 changeValueUseList(Op);
510 if (verifyModule(M, &errs()))
511 report_fatal_error("verification failed");
514 static void shuffleUseLists(Module &M, unsigned SeedOffset) {
515 std::minstd_rand0 Gen(std::minstd_rand0::default_seed + SeedOffset);
516 DenseSet<Value *> Seen;
517 changeUseLists(M, [&](Value *V) { shuffleValueUseLists(V, Gen, Seen); });
518 LLVM_DEBUG(dbgs() << "\n");
521 static void reverseUseLists(Module &M) {
522 DenseSet<Value *> Seen;
523 changeUseLists(M, [&](Value *V) { reverseValueUseLists(V, Seen); });
524 LLVM_DEBUG(dbgs() << "\n");
527 int main(int argc, char **argv) {
528 InitLLVM X(argc, argv);
530 // Enable debug stream buffering.
531 EnableDebugBuffering = true;
533 LLVMContext Context;
535 cl::ParseCommandLineOptions(argc, argv,
536 "llvm tool to verify use-list order\n");
538 SMDiagnostic Err;
540 // Load the input module...
541 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
543 if (!M.get()) {
544 Err.print(argv[0], errs());
545 return 1;
547 if (verifyModule(*M, &errs())) {
548 errs() << argv[0] << ": " << InputFilename
549 << ": error: input module is broken!\n";
550 return 1;
553 // Verify the use lists now and after reversing them.
554 outs() << "*** verify-uselistorder ***\n";
555 verifyUseListOrder(*M);
556 outs() << "reverse\n";
557 reverseUseLists(*M);
558 verifyUseListOrder(*M);
560 for (unsigned I = 0, E = NumShuffles; I != E; ++I) {
561 outs() << "\n";
563 // Shuffle with a different (deterministic) seed each time.
564 outs() << "shuffle (" << I + 1 << " of " << E << ")\n";
565 shuffleUseLists(*M, I);
567 // Verify again before and after reversing.
568 verifyUseListOrder(*M);
569 outs() << "reverse\n";
570 reverseUseLists(*M);
571 verifyUseListOrder(*M);
574 return 0;