* Fix extract to work with constant pointer refs correctly
[oota-llvm.git] / tools / llvm-extract / llvm-extract.cpp
1 //===----------------------------------------------------------------------===//
2 // LLVM extract Utility
3 //
4 // This utility changes the input module to only contain a single function,
5 // which is primarily used for debugging transformations.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Module.h"
10 #include "llvm/PassManager.h"
11 #include "llvm/Bytecode/Reader.h"
12 #include "llvm/Bytecode/WriteBytecodePass.h"
13 #include "llvm/Transforms/IPO.h"
14 #include "Support/CommandLine.h"
15 #include <memory>
16
17 // InputFilename - The filename to read from.
18 static cl::opt<std::string>
19 InputFilename(cl::Positional, cl::desc("<input bytecode file>"),
20               cl::init("-"), cl::value_desc("filename"));
21               
22
23 // ExtractFunc - The function to extract from the module... defaults to main.
24 static cl::opt<std::string>
25 ExtractFunc("func", cl::desc("Specify function to extract"), cl::init("main"),
26             cl::value_desc("function"));
27
28
29 struct FunctionExtractorPass : public Pass {
30   bool run(Module &M) {
31     // Mark all global variables to be internal
32     for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
33       if (!I->isExternal()) {
34         I->setInitializer(0);  // Make all variables external
35         I->setInternalLinkage(false); // Make sure it's not internal
36       }
37
38     Function *Named = 0;
39
40     // Loop over all of the functions in the module, dropping all references in
41     // functions that are not the named function.
42     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
43       // Check to see if this is the named function!
44       if (I->getName() == ExtractFunc && !I->isExternal()) {
45         if (Named) {                            // Two functions, same name?
46           std::cerr << "extract ERROR: Two functions named: '" << ExtractFunc
47                     << "' found!\n";
48           exit(1);
49         }
50
51         // Yes, it is.  Keep track of it...
52         Named = I;
53
54         // Make sure it's globally accessable...
55         Named->setInternalLinkage(false);
56       }
57     
58     if (Named == 0) {
59       std::cerr << "Warning: Function '" << ExtractFunc << "' not found!\n";
60       return false;
61     }
62     
63     // All of the functions may be used by global variables or the named
64     // function.  Loop through them and create a new, external functions that
65     // can be "used", instead of ones with bodies.
66     //
67     std::vector<Function*> NewFunctions;
68     
69     Function *Last = &M.back();  // Figure out where the last real fn is...
70
71     for (Module::iterator I = M.begin(); ; ++I) {
72       if (I->getName() != ExtractFunc) {
73         Function *New = new Function(I->getFunctionType(), false, I->getName());
74         I->setName("");  // Remove Old name
75
76         // If it's not the named function, delete the body of the function
77         I->dropAllReferences();
78
79         M.getFunctionList().push_back(New);
80         NewFunctions.push_back(New);
81       }
82
83       if (&*I == Last) break;  // Stop after processing the last function
84     }
85
86     // Now that we have replacements all set up, loop through the module,
87     // deleting the old functions, replacing them with the newly created
88     // functions.
89     if (!NewFunctions.empty()) {
90       unsigned FuncNum = 0;
91       Module::iterator I = M.begin();
92       do {
93         if (I->getName() != ExtractFunc) {
94           // Make everything that uses the old function use the new dummy fn
95           I->replaceAllUsesWith(NewFunctions[FuncNum++]);
96           
97           Function *Old = I;
98           ++I;  // Move the iterator to the new function
99
100           // Delete the old function!
101           M.getFunctionList().erase(Old);
102
103         } else {
104           ++I;  // Skip the function we are extracting
105         }
106       } while (&*I != NewFunctions[0]);
107     }
108     
109     return true;
110   }
111 };
112
113
114 static RegisterPass<FunctionExtractorPass> X("extract", "Function Extractor");
115
116
117 int main(int argc, char **argv) {
118   cl::ParseCommandLineOptions(argc, argv, " llvm extractor\n");
119
120   std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
121   if (M.get() == 0) {
122     std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
123     return 1;
124   }
125
126   // In addition to just parsing the input from GCC, we also want to spiff it up
127   // a little bit.  Do this now.
128   //
129   PassManager Passes;
130   Passes.add(new FunctionExtractorPass());
131   Passes.add(createGlobalDCEPass());              // Delete unreachable globals
132   Passes.add(createFunctionResolvingPass());      // Delete prototypes
133   Passes.add(createConstantMergePass());          // Merge dup global constants
134   Passes.add(createDeadTypeEliminationPass());    // Remove dead types...
135   Passes.add(new WriteBytecodePass(&std::cout));  // Write bytecode to file...
136
137   Passes.run(*M.get());
138   return 0;
139 }