1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/AsmParser/Parser.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IR/UseListOrder.h"
21 #include "llvm/IRReader/IRReader.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/FileUtilities.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/PrettyStackTrace.h"
30 #include "llvm/Support/Signals.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/SystemUtils.h"
36 #define DEBUG_TYPE "use-list-order"
38 static cl::opt<std::string> InputFilename(cl::Positional,
39 cl::desc("<input bitcode file>"),
41 cl::value_desc("filename"));
43 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temp files"),
51 bool init(const std::string &Ext);
52 bool writeBitcode(const Module &M) const;
53 bool writeAssembly(const Module &M) const;
54 std::unique_ptr<Module> readBitcode(LLVMContext &Context) const;
55 std::unique_ptr<Module> readAssembly(LLVMContext &Context) const;
59 DenseMap<const Value *, unsigned> IDs;
60 std::vector<const Value *> Values;
62 /// \brief Construct a value mapping for module.
64 /// Creates mapping from every value in \c M to an ID. This mapping includes
65 /// un-referencable values.
67 /// Every \a Value that gets serialized in some way should be represented
68 /// here. The order needs to be deterministic, but it's unnecessary to match
69 /// the value-ids in the bitcode writer.
71 /// All constants that are referenced by other values are included in the
72 /// mapping, but others -- which wouldn't be serialized -- are not.
73 ValueMapping(const Module &M);
75 /// \brief Map a value.
77 /// Maps a value. If it's a constant, maps all of its operands first.
78 void map(const Value *V);
79 unsigned lookup(const Value *V) const { return IDs.lookup(V); }
84 bool TempFile::init(const std::string &Ext) {
85 SmallVector<char, 64> Vector;
86 DEBUG(dbgs() << " - create-temp-file\n");
87 if (auto EC = sys::fs::createTemporaryFile("use-list-order", Ext, Vector)) {
89 DEBUG(dbgs() << "error: " << EC.message() << "\n");
92 assert(!Vector.empty());
94 Filename.assign(Vector.data(), Vector.data() + Vector.size());
95 Remover.setFile(Filename, !SaveTemps);
96 DEBUG(dbgs() << " - filename = " << Filename << "\n");
100 bool TempFile::writeBitcode(const Module &M) const {
101 DEBUG(dbgs() << " - write bitcode\n");
102 std::string ErrorInfo;
103 raw_fd_ostream OS(Filename.c_str(), ErrorInfo, sys::fs::F_None);
104 if (!ErrorInfo.empty()) {
105 DEBUG(dbgs() << "error: " << ErrorInfo << "\n");
109 WriteBitcodeToFile(&M, OS);
113 bool TempFile::writeAssembly(const Module &M) const {
114 DEBUG(dbgs() << " - write assembly\n");
115 std::string ErrorInfo;
116 raw_fd_ostream OS(Filename.c_str(), ErrorInfo, sys::fs::F_Text);
117 if (!ErrorInfo.empty()) {
118 DEBUG(dbgs() << "error: " << ErrorInfo << "\n");
126 std::unique_ptr<Module> TempFile::readBitcode(LLVMContext &Context) const {
127 DEBUG(dbgs() << " - read bitcode\n");
128 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOr =
129 MemoryBuffer::getFile(Filename);
131 DEBUG(dbgs() << "error: " << BufferOr.getError().message() << "\n");
135 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOr.get());
136 ErrorOr<Module *> ModuleOr = parseBitcodeFile(Buffer.release(), Context);
138 DEBUG(dbgs() << "error: " << ModuleOr.getError().message() << "\n");
141 return std::unique_ptr<Module>(ModuleOr.get());
144 std::unique_ptr<Module> TempFile::readAssembly(LLVMContext &Context) const {
145 DEBUG(dbgs() << " - read assembly\n");
147 std::unique_ptr<Module> M(ParseAssemblyFile(Filename, Err, Context));
149 DEBUG(dbgs() << "error: "; Err.print("verify-use-list-order", dbgs()));
153 ValueMapping::ValueMapping(const Module &M) {
154 // Every value should be mapped, including things like void instructions and
155 // basic blocks that are kept out of the ValueEnumerator.
157 // The current mapping order makes it easier to debug the tables. It happens
158 // to be similar to the ID mapping when writing ValueEnumerator, but they
159 // aren't (and needn't be) in sync.
162 for (const GlobalVariable &G : M.globals())
164 for (const GlobalAlias &A : M.aliases())
166 for (const Function &F : M)
169 // Constants used by globals.
170 for (const GlobalVariable &G : M.globals())
171 if (G.hasInitializer())
172 map(G.getInitializer());
173 for (const GlobalAlias &A : M.aliases())
175 for (const Function &F : M)
176 if (F.hasPrefixData())
177 map(F.getPrefixData());
180 for (const Function &F : M) {
181 for (const Argument &A : F.args())
183 for (const BasicBlock &BB : F)
185 for (const BasicBlock &BB : F)
186 for (const Instruction &I : BB)
189 // Constants used by instructions.
190 for (const BasicBlock &BB : F)
191 for (const Instruction &I : BB)
192 for (const Value *Op : I.operands())
193 if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
199 void ValueMapping::map(const Value *V) {
203 if (auto *C = dyn_cast<Constant>(V))
204 if (!isa<GlobalValue>(C))
205 for (const Value *Op : C->operands())
209 IDs[V] = Values.size();
213 static void dumpMapping(const ValueMapping &VM) {
214 dbgs() << "value-mapping (size = " << VM.Values.size() << "):\n";
215 for (unsigned I = 0, E = VM.Values.size(); I != E; ++I) {
216 dbgs() << " - id = " << I << ", value = ";
217 VM.Values[I]->dump();
221 static void debugValue(const ValueMapping &M, unsigned I, StringRef Desc) {
222 const Value *V = M.Values[I];
223 dbgs() << " - " << Desc << " value = ";
225 for (const Use &U : V->uses()) {
226 dbgs() << " => use: op = " << U.getOperandNo()
227 << ", user-id = " << M.IDs.lookup(U.getUser()) << ", user = ";
232 static void debugUserMismatch(const ValueMapping &L, const ValueMapping &R,
234 dbgs() << " - fail: user mismatch: ID = " << I << "\n";
235 debugValue(L, I, "LHS");
236 debugValue(R, I, "RHS");
244 static void debugSizeMismatch(const ValueMapping &L, const ValueMapping &R) {
245 dbgs() << " - fail: map size: " << L.Values.size()
246 << " != " << R.Values.size() << "\n";
254 static bool matches(const ValueMapping &LM, const ValueMapping &RM) {
255 DEBUG(dbgs() << "compare value maps\n");
256 if (LM.Values.size() != RM.Values.size()) {
257 DEBUG(debugSizeMismatch(LM, RM));
261 // This mapping doesn't include dangling constant users, since those don't
262 // get serialized. However, checking if users are constant and calling
263 // isConstantUsed() on every one is very expensive. Instead, just check if
264 // the user is mapped.
265 auto skipUnmappedUsers =
266 [&](Value::const_use_iterator &U, Value::const_use_iterator E,
267 const ValueMapping &M) {
268 while (U != E && !M.lookup(U->getUser()))
272 // Iterate through all values, and check that both mappings have the same
274 for (unsigned I = 0, E = LM.Values.size(); I != E; ++I) {
275 const Value *L = LM.Values[I];
276 const Value *R = RM.Values[I];
277 auto LU = L->use_begin(), LE = L->use_end();
278 auto RU = R->use_begin(), RE = R->use_end();
279 skipUnmappedUsers(LU, LE, LM);
280 skipUnmappedUsers(RU, RE, RM);
284 DEBUG(debugUserMismatch(LM, RM, I));
287 if (LM.lookup(LU->getUser()) != RM.lookup(RU->getUser())) {
288 DEBUG(debugUserMismatch(LM, RM, I));
291 if (LU->getOperandNo() != RU->getOperandNo()) {
292 DEBUG(debugUserMismatch(LM, RM, I));
295 skipUnmappedUsers(++LU, LE, LM);
296 skipUnmappedUsers(++RU, RE, RM);
299 DEBUG(debugUserMismatch(LM, RM, I));
307 static bool verifyBitcodeUseListOrder(const Module &M) {
308 DEBUG(dbgs() << "*** verify-use-list-order: bitcode ***\n");
313 if (F.writeBitcode(M))
317 std::unique_ptr<Module> OtherM = F.readBitcode(Context);
321 return matches(ValueMapping(M), ValueMapping(*OtherM));
324 static bool verifyAssemblyUseListOrder(const Module &M) {
325 DEBUG(dbgs() << "*** verify-use-list-order: assembly ***\n");
330 if (F.writeAssembly(M))
334 std::unique_ptr<Module> OtherM = F.readAssembly(Context);
338 return matches(ValueMapping(M), ValueMapping(*OtherM));
341 int main(int argc, char **argv) {
342 sys::PrintStackTraceOnErrorSignal();
343 llvm::PrettyStackTraceProgram X(argc, argv);
345 // Enable debug stream buffering.
346 EnableDebugBuffering = true;
348 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
349 LLVMContext &Context = getGlobalContext();
351 cl::ParseCommandLineOptions(argc, argv,
352 "llvm tool to verify use-list order\n");
356 // Load the input module...
357 std::unique_ptr<Module> M;
358 M.reset(ParseIRFile(InputFilename, Err, Context));
361 Err.print(argv[0], errs());
365 DEBUG(dbgs() << "*** verify-use-list-order ***\n");
366 if (!shouldPreserveBitcodeUseListOrder()) {
367 // Can't verify if order isn't preserved.
368 DEBUG(dbgs() << "warning: cannot verify bitcode; "
369 "try -preserve-bc-use-list-order\n");
374 if (!verifyBitcodeUseListOrder(*M))
375 report_fatal_error("bitcode use-list order changed");
377 if (shouldPreserveAssemblyUseListOrder())
378 if (!verifyAssemblyUseListOrder(*M))
379 report_fatal_error("assembly use-list order changed");