Move stuff out of the Optimizations directories into the appropriate Transforms
[oota-llvm.git] / tools / opt / opt.cpp
index 70c2efeff84e44c12c9d286ee253ccf5f6026f67..36de3bfbf73246e69c0ae76e4d9dde295dbe005c 100644 (file)
-//===------------------------------------------------------------------------===
+//===----------------------------------------------------------------------===//
 // LLVM 'OPT' UTILITY 
 //
-// This utility may be invoked in the following manner:
-//  opt --help               - Output information about command line switches
-//  opt [options] -dce       - Run a dead code elimination pass on input 
-//                             bytecodes
-//  opt [options] -constprop - Run a constant propogation pass on input 
-//                             bytecodes
-//  opt [options] -inline    - Run a method inlining pass on input bytecodes
-//  opt [options] -strip     - Strip symbol tables out of methods
-//  opt [options] -mstrip    - Strip module & method symbol tables
-//
 // Optimizations may be specified an arbitrary number of times on the command
 // line, they are run in the order specified.
 //
-// TODO: Add a -all option to keep applying all optimizations until the program
-//       stops permuting.
-//
-//===------------------------------------------------------------------------===
+//===----------------------------------------------------------------------===//
 
-#include <iostream.h>
-#include <fstream.h>
 #include "llvm/Module.h"
 #include "llvm/Bytecode/Reader.h"
 #include "llvm/Bytecode/Writer.h"
-#include "llvm/Tools/CommandLine.h"
-#include "llvm/Optimizations/AllOpts.h"
+#include "llvm/Assembly/PrintModulePass.h"
+#include "llvm/Transforms/ConstantMerge.h"
+#include "llvm/Transforms/CleanupGCCOutput.h"
+#include "llvm/Transforms/LevelChange.h"
+#include "llvm/Transforms/MethodInlining.h"
+#include "llvm/Transforms/SymbolStripping.h"
+#include "llvm/Transforms/IPO/SimpleStructMutation.h"
+#include "llvm/Transforms/IPO/GlobalDCE.h"
+#include "llvm/Transforms/Scalar/DCE.h"
+#include "llvm/Transforms/Scalar/ConstantProp.h"
+#include "llvm/Transforms/Scalar/InductionVars.h"
+#include "llvm/Transforms/Scalar/IndVarSimplify.h"
+#include "llvm/Transforms/Scalar/InstructionCombining.h"
+#include "llvm/Transforms/Instrumentation/TraceValues.h"
+#include "Support/CommandLine.h"
+#include <fstream>
+#include <memory>
+
+
+
+enum Opts {
+  // Basic optimizations
+  dce, constprop, inlining, constmerge, strip, mstrip,
 
-using namespace opt;
+  // Miscellaneous Transformations
+  trace, tracem, print, cleangcc,
+
+  // More powerful optimizations
+  indvars, instcombine, sccp, adce, raise,
+
+  // Interprocedural optimizations...
+  globaldce, swapstructs, sortstructs,
+};
 
 struct {
-  const string ArgName, Name;
-  bool (*OptPtr)(Module *C);
+  enum Opts OptID;
+  Pass *ThePass;
 } OptTable[] = {
-  { "-dce"       , "Dead Code Elimination", DoDeadCodeElimination },
-  { "-constprop" , "Constant Propogation",  DoConstantPropogation }, 
-  { "-inline"    , "Method Inlining",       DoMethodInlining      },
-  { "-strip"     , "Strip Symbols",         DoSymbolStripping     },
-  { "-mstrip"    , "Strip Module Symbols",  DoFullSymbolStripping },
-  { "-indvars"   , "Simplify Induction Vars",DoInductionVariableCannonicalize },
-  { "-sccp"      , "Sparse Conditional Constant Prop", DoSCCP },
-  { "-cpm"       , "Constant Pool Merging", DoConstantPoolMerging },
-  { "-adce"      , "Agressive DCE",         DoADCE },
-  { "-raise"     , "Raise to Higher Level", DoRaiseRepresentation },
+  { dce        , new DeadCodeElimination() },
+  { constprop  , new ConstantPropogation() }, 
+  { inlining   , new MethodInlining() },
+  { constmerge , new ConstantMerge() },
+  { strip      , new SymbolStripping() },
+  { mstrip     , new FullSymbolStripping() },
+  { indvars    , new InductionVariableSimplify() },
+  { instcombine, new InstructionCombining() },
+  { sccp       , new SCCPPass() },
+  { adce       , new AgressiveDCE() },
+  { raise      , new RaisePointerReferences() },
+  { trace      , new InsertTraceCode(true, true) },
+  { tracem     , new InsertTraceCode(false, true) },
+  { print      , new PrintMethodPass("Current Method: \n",&cerr) },
+  { cleangcc   , new CleanupGCCOutput() },
+  { globaldce  , new GlobalDCE() },
+  { swapstructs, new SimpleStructMutation(SimpleStructMutation::SwapElements) },
+  { sortstructs, new SimpleStructMutation(SimpleStructMutation::SortElements) },
 };
 
-int main(int argc, char **argv) {
-  ToolCommandLine Opts(argc, argv, false);
-  bool Quiet = false;
-
-  for (int i = 1; i < argc; i++) {
-    if (string(argv[i]) == string("--help")) {
-      cerr << argv[0] << " usage:\n"
-           << "  " << argv[0] << " --help  - Print this usage information\n";
-      for (unsigned j = 0; j < sizeof(OptTable)/sizeof(OptTable[0]); ++j) {
-       cerr << "\t" << OptTable[j].ArgName << "\t - Enable " 
-            << OptTable[j].Name << endl;
-      }
-      return 1;
-    } else if (string(argv[i]) == string("-q")) {
-      Quiet = true; argv[i] = 0;
+cl::String InputFilename ("", "Load <arg> file to optimize", cl::NoFlags, "-");
+cl::String OutputFilename("o", "Override output filename", cl::NoFlags, "");
+cl::Flag   Force         ("f", "Overwrite output files", cl::NoFlags, false);
+cl::Flag   Quiet         ("q", "Don't print modifying pass names", 0, false);
+cl::Alias  QuietA        ("quiet", "Alias for -q", cl::NoFlags, Quiet);
+cl::EnumList<enum Opts> OptimizationList(cl::NoFlags,
+  clEnumVal(dce        , "Dead Code Elimination"),
+  clEnumVal(constprop  , "Simple Constant Propogation"),
+ clEnumValN(inlining   , "inline", "Method Integration"),
+  clEnumVal(constmerge , "Merge identical global constants"),
+  clEnumVal(strip      , "Strip Symbols"),
+  clEnumVal(mstrip     , "Strip Module Symbols"),
+  clEnumVal(indvars    , "Simplify Induction Variables"),
+  clEnumVal(instcombine, "Simplify Induction Variables"),
+  clEnumVal(sccp       , "Sparse Conditional Constant Propogation"),
+  clEnumVal(adce       , "Agressive DCE"),
+
+  clEnumVal(globaldce  , "Remove unreachable globals"),
+  clEnumVal(swapstructs, "Swap structure types around"),
+  clEnumVal(sortstructs, "Sort structure elements"),
+
+  clEnumVal(cleangcc   , "Cleanup GCC Output"),
+  clEnumVal(raise      , "Raise to Higher Level"),
+  clEnumVal(trace      , "Insert BB & Method trace code"),
+  clEnumVal(tracem     , "Insert Method trace code only"),
+  clEnumVal(print      , "Print working method to stderr"),
+0);
+
+static void RunOptimization(Module *M, enum Opts Opt) {
+  for (unsigned j = 0; j < sizeof(OptTable)/sizeof(OptTable[0]); ++j)
+    if (Opt == OptTable[j].OptID) {
+      if (OptTable[j].ThePass->run(M) && !Quiet)
+       cerr << OptimizationList.getArgName(Opt)
+            << " pass made modifications!\n";
+      return;
     }
-  }
   
-  ostream *Out = &cout;  // Default to printing to stdout...
+  cerr << "Optimization tables inconsistent!!\n";
+}
 
-  Module *C = ParseBytecodeFile(Opts.getInputFilename());
-  if (C == 0) {
+int main(int argc, char **argv) {
+  cl::ParseCommandLineOptions(argc, argv,
+                             " llvm .bc -> .bc modular optimizer\n");
+  std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
+  if (M.get() == 0) {
     cerr << "bytecode didn't read correctly.\n";
     return 1;
   }
 
+  PassManager Passes;
 
-  for (int i = 1; i < argc; i++) {
-    if (argv[i] == 0) continue;
-    unsigned j;
-    for (j = 0; j < sizeof(OptTable)/sizeof(OptTable[0]); j++) {
-      if (string(argv[i]) == OptTable[j].ArgName) {
-        if (OptTable[j].OptPtr(C) && !Quiet)
-          cerr << OptTable[j].Name << " pass made modifications!\n";
-        break;
-      }
-    }
+  // Run all of the optimizations specified on the command line
+  for (unsigned i = 0; i < OptimizationList.size(); ++i)
+    RunOptimization(M.get(), OptimizationList[i]);
 
-    if (j == sizeof(OptTable)/sizeof(OptTable[0])) 
-      cerr << "'" << argv[i] << "' argument unrecognized: ignored\n";
-  }
+  std::ostream *Out = &std::cout;  // Default to printing to stdout...
+  if (OutputFilename != "") {
+    if (!Force && !std::ifstream(OutputFilename.c_str())) {
+      // If force is not specified, make sure not to overwrite a file!
+      cerr << "Error opening '" << OutputFilename << "': File exists!\n"
+           << "Use -f command line argument to force output\n";
+      return 1;
+    }
+    Out = new std::ofstream(OutputFilename.c_str());
 
-  if (Opts.getOutputFilename() != "-") {
-    Out = new ofstream(Opts.getOutputFilename().c_str(), 
-                       (Opts.getForce() ? 0 : ios::noreplace)|ios::out);
     if (!Out->good()) {
-      cerr << "Error opening " << Opts.getOutputFilename() 
-           << "!\n";
-      delete C;
+      cerr << "Error opening " << OutputFilename << "!\n";
       return 1;
     }
   }
 
   // Okay, we're done now... write out result...
-  WriteBytecodeToFile(C, *Out);
-  delete C;
+  WriteBytecodeToFile(M.get(), *Out);
 
   if (Out != &cout) delete Out;
   return 0;