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