2 #include "llvm/Transforms/IPO.h"
4 #include "llvm/Module.h"
7 class FunctionExtractorPass : public Pass {
10 FunctionExtractorPass(Function *F = 0) : Named(F) {}
14 Named = M.getMainFunction();
15 if (Named == 0) return false; // No function to extract
18 // Make sure our result is globally accessable...
19 Named->setLinkage(GlobalValue::ExternalLinkage);
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
25 I->setLinkage(GlobalValue::ExternalLinkage);
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.
32 std::vector<Function*> NewFunctions;
34 Function *Last = &M.back(); // Figure out where the last real fn is...
36 for (Module::iterator I = M.begin(); ; ++I) {
38 Function *New = new Function(I->getFunctionType(),
39 GlobalValue::ExternalLinkage,
41 I->setName(""); // Remove Old name
43 // If it's not the named function, delete the body of the function
44 I->dropAllReferences();
46 M.getFunctionList().push_back(New);
47 NewFunctions.push_back(New);
50 if (&*I == Last) break; // Stop after processing the last function
53 // Now that we have replacements all set up, loop through the module,
54 // deleting the old functions, replacing them with the newly created
56 if (!NewFunctions.empty()) {
58 Module::iterator I = M.begin();
61 // Make everything that uses the old function use the new dummy fn
62 I->replaceAllUsesWith(NewFunctions[FuncNum++]);
65 ++I; // Move the iterator to the new function
67 // Delete the old function!
68 M.getFunctionList().erase(Old);
71 ++I; // Skip the function we are extracting
73 } while (&*I != NewFunctions[0]);
80 RegisterPass<FunctionExtractorPass> X("extract", "Function Extractor");
83 Pass *createFunctionExtractionPass(Function *F) {
84 return new FunctionExtractorPass(F);