verify-uselistorder: Reverse use-lists at every verification
[oota-llvm.git] / tools / verify-uselistorder / verify-uselistorder.cpp
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.
13 //
14 // The shuffles are deterministic, but guarantee that use-lists will change.
15 // The algorithm per iteration is as follows:
16 //
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.
19 //
20 //  2. Visit every Value in a deterministic order.
21 //
22 //  3. Assign a random number to each Use in the Value's use-list in order.
23 //
24 //  4. If the numbers are already in order, reassign numbers until they aren't.
25 //
26 //  5. Sort the use-list using Value::sortUseList(), which is a stable sort.
27 //
28 //===----------------------------------------------------------------------===//
29
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/IRReader/IRReader.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/FileUtilities.h"
43 #include "llvm/Support/ManagedStatic.h"
44 #include "llvm/Support/MemoryBuffer.h"
45 #include "llvm/Support/PrettyStackTrace.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/SystemUtils.h"
49 #include <random>
50 #include <vector>
51
52 using namespace llvm;
53
54 #define DEBUG_TYPE "use-list-order"
55
56 static cl::opt<std::string> InputFilename(cl::Positional,
57                                           cl::desc("<input bitcode file>"),
58                                           cl::init("-"),
59                                           cl::value_desc("filename"));
60
61 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temp files"),
62                                cl::init(false));
63
64 static cl::opt<unsigned>
65     NumShuffles("num-shuffles",
66                 cl::desc("Number of times to shuffle and verify use-lists"),
67                 cl::init(1));
68
69 namespace {
70
71 struct TempFile {
72   std::string Filename;
73   FileRemover Remover;
74   bool init(const std::string &Ext);
75   bool writeBitcode(const Module &M) const;
76   bool writeAssembly(const Module &M) const;
77   std::unique_ptr<Module> readBitcode(LLVMContext &Context) const;
78   std::unique_ptr<Module> readAssembly(LLVMContext &Context) const;
79 };
80
81 struct ValueMapping {
82   DenseMap<const Value *, unsigned> IDs;
83   std::vector<const Value *> Values;
84
85   /// \brief Construct a value mapping for module.
86   ///
87   /// Creates mapping from every value in \c M to an ID.  This mapping includes
88   /// un-referencable values.
89   ///
90   /// Every \a Value that gets serialized in some way should be represented
91   /// here.  The order needs to be deterministic, but it's unnecessary to match
92   /// the value-ids in the bitcode writer.
93   ///
94   /// All constants that are referenced by other values are included in the
95   /// mapping, but others -- which wouldn't be serialized -- are not.
96   ValueMapping(const Module &M);
97
98   /// \brief Map a value.
99   ///
100   /// Maps a value.  If it's a constant, maps all of its operands first.
101   void map(const Value *V);
102   unsigned lookup(const Value *V) const { return IDs.lookup(V); }
103 };
104
105 } // end namespace
106
107 bool TempFile::init(const std::string &Ext) {
108   SmallVector<char, 64> Vector;
109   DEBUG(dbgs() << " - create-temp-file\n");
110   if (auto EC = sys::fs::createTemporaryFile("use-list-order", Ext, Vector)) {
111     (void)EC;
112     DEBUG(dbgs() << "error: " << EC.message() << "\n");
113     return true;
114   }
115   assert(!Vector.empty());
116
117   Filename.assign(Vector.data(), Vector.data() + Vector.size());
118   Remover.setFile(Filename, !SaveTemps);
119   DEBUG(dbgs() << " - filename = " << Filename << "\n");
120   return false;
121 }
122
123 bool TempFile::writeBitcode(const Module &M) const {
124   DEBUG(dbgs() << " - write bitcode\n");
125   std::string ErrorInfo;
126   raw_fd_ostream OS(Filename.c_str(), ErrorInfo, sys::fs::F_None);
127   if (!ErrorInfo.empty()) {
128     DEBUG(dbgs() << "error: " << ErrorInfo << "\n");
129     return true;
130   }
131
132   WriteBitcodeToFile(&M, OS);
133   return false;
134 }
135
136 bool TempFile::writeAssembly(const Module &M) const {
137   DEBUG(dbgs() << " - write assembly\n");
138   std::string ErrorInfo;
139   raw_fd_ostream OS(Filename.c_str(), ErrorInfo, sys::fs::F_Text);
140   if (!ErrorInfo.empty()) {
141     DEBUG(dbgs() << "error: " << ErrorInfo << "\n");
142     return true;
143   }
144
145   OS << M;
146   return false;
147 }
148
149 std::unique_ptr<Module> TempFile::readBitcode(LLVMContext &Context) const {
150   DEBUG(dbgs() << " - read bitcode\n");
151   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOr =
152       MemoryBuffer::getFile(Filename);
153   if (!BufferOr) {
154     DEBUG(dbgs() << "error: " << BufferOr.getError().message() << "\n");
155     return nullptr;
156   }
157
158   MemoryBuffer *Buffer = BufferOr.get().get();
159   ErrorOr<Module *> ModuleOr = parseBitcodeFile(Buffer, Context);
160   if (!ModuleOr) {
161     DEBUG(dbgs() << "error: " << ModuleOr.getError().message() << "\n");
162     return nullptr;
163   }
164   return std::unique_ptr<Module>(ModuleOr.get());
165 }
166
167 std::unique_ptr<Module> TempFile::readAssembly(LLVMContext &Context) const {
168   DEBUG(dbgs() << " - read assembly\n");
169   SMDiagnostic Err;
170   std::unique_ptr<Module> M(ParseAssemblyFile(Filename, Err, Context));
171   if (!M.get())
172     DEBUG(dbgs() << "error: "; Err.print("verify-use-list-order", dbgs()));
173   return M;
174 }
175
176 ValueMapping::ValueMapping(const Module &M) {
177   // Every value should be mapped, including things like void instructions and
178   // basic blocks that are kept out of the ValueEnumerator.
179   //
180   // The current mapping order makes it easier to debug the tables.  It happens
181   // to be similar to the ID mapping when writing ValueEnumerator, but they
182   // aren't (and needn't be) in sync.
183
184   // Globals.
185   for (const GlobalVariable &G : M.globals())
186     map(&G);
187   for (const GlobalAlias &A : M.aliases())
188     map(&A);
189   for (const Function &F : M)
190     map(&F);
191
192   // Constants used by globals.
193   for (const GlobalVariable &G : M.globals())
194     if (G.hasInitializer())
195       map(G.getInitializer());
196   for (const GlobalAlias &A : M.aliases())
197     map(A.getAliasee());
198   for (const Function &F : M)
199     if (F.hasPrefixData())
200       map(F.getPrefixData());
201
202   // Function bodies.
203   for (const Function &F : M) {
204     for (const Argument &A : F.args())
205       map(&A);
206     for (const BasicBlock &BB : F)
207       map(&BB);
208     for (const BasicBlock &BB : F)
209       for (const Instruction &I : BB)
210         map(&I);
211
212     // Constants used by instructions.
213     for (const BasicBlock &BB : F)
214       for (const Instruction &I : BB)
215         for (const Value *Op : I.operands())
216           if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
217               isa<InlineAsm>(Op))
218             map(Op);
219   }
220 }
221
222 void ValueMapping::map(const Value *V) {
223   if (IDs.lookup(V))
224     return;
225
226   if (auto *C = dyn_cast<Constant>(V))
227     if (!isa<GlobalValue>(C))
228       for (const Value *Op : C->operands())
229         map(Op);
230
231   Values.push_back(V);
232   IDs[V] = Values.size();
233 }
234
235 #ifndef NDEBUG
236 static void dumpMapping(const ValueMapping &VM) {
237   dbgs() << "value-mapping (size = " << VM.Values.size() << "):\n";
238   for (unsigned I = 0, E = VM.Values.size(); I != E; ++I) {
239     dbgs() << " - id = " << I << ", value = ";
240     VM.Values[I]->dump();
241   }
242 }
243
244 static void debugValue(const ValueMapping &M, unsigned I, StringRef Desc) {
245   const Value *V = M.Values[I];
246   dbgs() << " - " << Desc << " value = ";
247   V->dump();
248   for (const Use &U : V->uses()) {
249     dbgs() << "   => use: op = " << U.getOperandNo()
250            << ", user-id = " << M.IDs.lookup(U.getUser()) << ", user = ";
251     U.getUser()->dump();
252   }
253 }
254
255 static void debugUserMismatch(const ValueMapping &L, const ValueMapping &R,
256                               unsigned I) {
257   dbgs() << " - fail: user mismatch: ID = " << I << "\n";
258   debugValue(L, I, "LHS");
259   debugValue(R, I, "RHS");
260
261   dbgs() << "\nlhs-";
262   dumpMapping(L);
263   dbgs() << "\nrhs-";
264   dumpMapping(R);
265 }
266
267 static void debugSizeMismatch(const ValueMapping &L, const ValueMapping &R) {
268   dbgs() << " - fail: map size: " << L.Values.size()
269          << " != " << R.Values.size() << "\n";
270   dbgs() << "\nlhs-";
271   dumpMapping(L);
272   dbgs() << "\nrhs-";
273   dumpMapping(R);
274 }
275 #endif
276
277 static bool matches(const ValueMapping &LM, const ValueMapping &RM) {
278   DEBUG(dbgs() << "compare value maps\n");
279   if (LM.Values.size() != RM.Values.size()) {
280     DEBUG(debugSizeMismatch(LM, RM));
281     return false;
282   }
283
284   // This mapping doesn't include dangling constant users, since those don't
285   // get serialized.  However, checking if users are constant and calling
286   // isConstantUsed() on every one is very expensive.  Instead, just check if
287   // the user is mapped.
288   auto skipUnmappedUsers =
289       [&](Value::const_use_iterator &U, Value::const_use_iterator E,
290           const ValueMapping &M) {
291     while (U != E && !M.lookup(U->getUser()))
292       ++U;
293   };
294
295   // Iterate through all values, and check that both mappings have the same
296   // users.
297   for (unsigned I = 0, E = LM.Values.size(); I != E; ++I) {
298     const Value *L = LM.Values[I];
299     const Value *R = RM.Values[I];
300     auto LU = L->use_begin(), LE = L->use_end();
301     auto RU = R->use_begin(), RE = R->use_end();
302     skipUnmappedUsers(LU, LE, LM);
303     skipUnmappedUsers(RU, RE, RM);
304
305     while (LU != LE) {
306       if (RU == RE) {
307         DEBUG(debugUserMismatch(LM, RM, I));
308         return false;
309       }
310       if (LM.lookup(LU->getUser()) != RM.lookup(RU->getUser())) {
311         DEBUG(debugUserMismatch(LM, RM, I));
312         return false;
313       }
314       if (LU->getOperandNo() != RU->getOperandNo()) {
315         DEBUG(debugUserMismatch(LM, RM, I));
316         return false;
317       }
318       skipUnmappedUsers(++LU, LE, LM);
319       skipUnmappedUsers(++RU, RE, RM);
320     }
321     if (RU != RE) {
322       DEBUG(debugUserMismatch(LM, RM, I));
323       return false;
324     }
325   }
326
327   return true;
328 }
329
330 static bool verifyBitcodeUseListOrder(const Module &M) {
331   DEBUG(dbgs() << "*** verify-use-list-order: bitcode ***\n");
332   TempFile F;
333   if (F.init("bc"))
334     return false;
335
336   if (F.writeBitcode(M))
337     return false;
338
339   LLVMContext Context;
340   std::unique_ptr<Module> OtherM = F.readBitcode(Context);
341   if (!OtherM)
342     return false;
343
344   return matches(ValueMapping(M), ValueMapping(*OtherM));
345 }
346
347 static bool verifyAssemblyUseListOrder(const Module &M) {
348   DEBUG(dbgs() << "*** verify-use-list-order: assembly ***\n");
349   TempFile F;
350   if (F.init("ll"))
351     return false;
352
353   if (F.writeAssembly(M))
354     return false;
355
356   LLVMContext Context;
357   std::unique_ptr<Module> OtherM = F.readAssembly(Context);
358   if (!OtherM)
359     return false;
360
361   return matches(ValueMapping(M), ValueMapping(*OtherM));
362 }
363
364 static void verifyUseListOrder(const Module &M) {
365   if (!verifyBitcodeUseListOrder(M))
366     report_fatal_error("bitcode use-list order changed");
367
368   if (shouldPreserveAssemblyUseListOrder())
369     if (!verifyAssemblyUseListOrder(M))
370       report_fatal_error("assembly use-list order changed");
371 }
372
373 static void shuffleValueUseLists(Value *V, std::minstd_rand0 &Gen,
374                                  DenseSet<Value *> &Seen) {
375   if (!Seen.insert(V).second)
376     return;
377
378   if (auto *C = dyn_cast<Constant>(V))
379     if (!isa<GlobalValue>(C))
380       for (Value *Op : C->operands())
381         shuffleValueUseLists(Op, Gen, Seen);
382
383   if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
384     // Nothing to shuffle for 0 or 1 users.
385     return;
386
387   // Generate random numbers between 10 and 99, which will line up nicely in
388   // debug output.  We're not worried about collisons here.
389   DEBUG(dbgs() << "V = "; V->dump());
390   std::uniform_int_distribution<short> Dist(10, 99);
391   SmallDenseMap<const Use *, short, 16> Order;
392   auto compareUses =
393       [&Order](const Use &L, const Use &R) { return Order[&L] < Order[&R]; };
394   do {
395     for (const Use &U : V->uses()) {
396       auto I = Dist(Gen);
397       Order[&U] = I;
398       DEBUG(dbgs() << " - order: " << I << ", op = " << U.getOperandNo()
399                    << ", U = ";
400             U.getUser()->dump());
401     }
402   } while (std::is_sorted(V->use_begin(), V->use_end(), compareUses));
403
404   DEBUG(dbgs() << " => shuffle\n");
405   V->sortUseList(compareUses);
406
407   DEBUG({
408     for (const Use &U : V->uses()) {
409       dbgs() << " - order: " << Order.lookup(&U)
410              << ", op = " << U.getOperandNo() << ", U = ";
411       U.getUser()->dump();
412     }
413   });
414 }
415
416 static void reverseValueUseLists(Value *V, DenseSet<Value *> &Seen) {
417   if (!Seen.insert(V).second)
418     return;
419
420   if (auto *C = dyn_cast<Constant>(V))
421     if (!isa<GlobalValue>(C))
422       for (Value *Op : C->operands())
423         reverseValueUseLists(Op, Seen);
424
425   if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
426     // Nothing to shuffle for 0 or 1 users.
427     return;
428
429   DEBUG({
430     dbgs() << "V = ";
431     V->dump();
432     for (const Use &U : V->uses()) {
433       dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
434       U.getUser()->dump();
435     }
436     dbgs() << " => reverse\n";
437   });
438
439   V->reverseUseList();
440
441   DEBUG({
442     for (const Use &U : V->uses()) {
443       dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
444       U.getUser()->dump();
445     }
446   });
447 }
448
449 template <class Changer>
450 static void changeUseLists(Module &M, Changer changeValueUseList) {
451   // Visit every value that would be serialized to an IR file.
452   //
453   // Globals.
454   for (GlobalVariable &G : M.globals())
455     changeValueUseList(&G);
456   for (GlobalAlias &A : M.aliases())
457     changeValueUseList(&A);
458   for (Function &F : M)
459     changeValueUseList(&F);
460
461   // Constants used by globals.
462   for (GlobalVariable &G : M.globals())
463     if (G.hasInitializer())
464       changeValueUseList(G.getInitializer());
465   for (GlobalAlias &A : M.aliases())
466     changeValueUseList(A.getAliasee());
467   for (Function &F : M)
468     if (F.hasPrefixData())
469       changeValueUseList(F.getPrefixData());
470
471   // Function bodies.
472   for (Function &F : M) {
473     for (Argument &A : F.args())
474       changeValueUseList(&A);
475     for (BasicBlock &BB : F)
476       changeValueUseList(&BB);
477     for (BasicBlock &BB : F)
478       for (Instruction &I : BB)
479         changeValueUseList(&I);
480
481     // Constants used by instructions.
482     for (BasicBlock &BB : F)
483       for (Instruction &I : BB)
484         for (Value *Op : I.operands())
485           if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
486               isa<InlineAsm>(Op))
487             changeValueUseList(Op);
488   }
489 }
490
491 static void shuffleUseLists(Module &M, unsigned SeedOffset) {
492   DEBUG(dbgs() << "*** shuffle-use-lists ***\n");
493   std::minstd_rand0 Gen(std::minstd_rand0::default_seed + SeedOffset);
494   DenseSet<Value *> Seen;
495   changeUseLists(M, [&](Value *V) { shuffleValueUseLists(V, Gen, Seen); });
496   DEBUG(dbgs() << "\n");
497 }
498
499 static void reverseUseLists(Module &M) {
500   DEBUG(dbgs() << "*** reverse-use-lists ***\n");
501   DenseSet<Value *> Seen;
502   changeUseLists(M, [&](Value *V) { reverseValueUseLists(V, Seen); });
503   DEBUG(dbgs() << "\n");
504 }
505
506 int main(int argc, char **argv) {
507   sys::PrintStackTraceOnErrorSignal();
508   llvm::PrettyStackTraceProgram X(argc, argv);
509
510   // Enable debug stream buffering.
511   EnableDebugBuffering = true;
512
513   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
514   LLVMContext &Context = getGlobalContext();
515
516   cl::ParseCommandLineOptions(argc, argv,
517                               "llvm tool to verify use-list order\n");
518
519   SMDiagnostic Err;
520
521   // Load the input module...
522   std::unique_ptr<Module> M;
523   M.reset(ParseIRFile(InputFilename, Err, Context));
524
525   if (!M.get()) {
526     Err.print(argv[0], errs());
527     return 1;
528   }
529
530   DEBUG(dbgs() << "*** verify-use-list-order ***\n");
531   if (!shouldPreserveBitcodeUseListOrder()) {
532     // Can't verify if order isn't preserved.
533     DEBUG(dbgs() << "warning: cannot verify bitcode; "
534                     "try -preserve-bc-use-list-order\n");
535     return 0;
536   }
537
538   // Verify the use lists now and after reversing them.
539   verifyUseListOrder(*M);
540   reverseUseLists(*M);
541   verifyUseListOrder(*M);
542
543   for (unsigned I = 0, E = NumShuffles; I != E; ++I) {
544     DEBUG(dbgs() << "*** iteration: " << I << " ***\n");
545
546     // Shuffle with a different (deterministic) seed each time.
547     shuffleUseLists(*M, I);
548
549     // Verify again before and after reversing.
550     verifyUseListOrder(*M);
551     reverseUseLists(*M);
552     verifyUseListOrder(*M);
553   }
554
555   return 0;
556 }