blob: 51c4e00987e1ab6277812ce2f94f701f2f4ec9e8 [file] [log] [blame]
Chris Lattner5113eb02002-11-19 18:42:59 +00001
2#include "llvm/Transforms/IPO.h"
3#include "llvm/Pass.h"
4#include "llvm/Module.h"
5
6namespace {
7 class FunctionExtractorPass : public Pass {
8 Function *Named;
9 public:
10 FunctionExtractorPass(Function *F = 0) : Named(F) {}
11
12 bool run(Module &M) {
13 if (Named == 0) {
14 Named = M.getMainFunction();
15 if (Named == 0) return false; // No function to extract
16 }
17
Misha Brukmancf00c4a2003-10-10 17:57:28 +000018 // Make sure our result is globally accessible...
Chris Lattner4ad02e72003-04-16 20:28:45 +000019 Named->setLinkage(GlobalValue::ExternalLinkage);
Chris Lattner5113eb02002-11-19 18:42:59 +000020
21 // Mark all global variables internal
22 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
23 if (!I->isExternal()) {
24 I->setInitializer(0); // Make all variables external
Chris Lattner4ad02e72003-04-16 20:28:45 +000025 I->setLinkage(GlobalValue::ExternalLinkage);
Chris Lattner5113eb02002-11-19 18:42:59 +000026 }
27
28 // All of the functions may be used by global variables or the named
29 // function. Loop through them and create a new, external functions that
30 // can be "used", instead of ones with bodies.
31 //
32 std::vector<Function*> NewFunctions;
33
34 Function *Last = &M.back(); // Figure out where the last real fn is...
35
36 for (Module::iterator I = M.begin(); ; ++I) {
37 if (&*I != Named) {
Chris Lattner4ad02e72003-04-16 20:28:45 +000038 Function *New = new Function(I->getFunctionType(),
39 GlobalValue::ExternalLinkage,
40 I->getName());
Chris Lattner5113eb02002-11-19 18:42:59 +000041 I->setName(""); // Remove Old name
42
43 // If it's not the named function, delete the body of the function
44 I->dropAllReferences();
45
46 M.getFunctionList().push_back(New);
47 NewFunctions.push_back(New);
48 }
49
50 if (&*I == Last) break; // Stop after processing the last function
51 }
52
53 // Now that we have replacements all set up, loop through the module,
54 // deleting the old functions, replacing them with the newly created
55 // functions.
56 if (!NewFunctions.empty()) {
57 unsigned FuncNum = 0;
58 Module::iterator I = M.begin();
59 do {
60 if (&*I != Named) {
61 // Make everything that uses the old function use the new dummy fn
62 I->replaceAllUsesWith(NewFunctions[FuncNum++]);
63
64 Function *Old = I;
65 ++I; // Move the iterator to the new function
66
67 // Delete the old function!
68 M.getFunctionList().erase(Old);
69
70 } else {
71 ++I; // Skip the function we are extracting
72 }
73 } while (&*I != NewFunctions[0]);
74 }
75
76 return true;
77 }
78 };
79
80 RegisterPass<FunctionExtractorPass> X("extract", "Function Extractor");
81}
82
83Pass *createFunctionExtractionPass(Function *F) {
84 return new FunctionExtractorPass(F);
85}