1 //===-- ExtractFunction.cpp - Function extraction pass --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Transforms/IPO.h"
11 #include "llvm/Pass.h"
12 #include "llvm/Module.h"
16 class FunctionExtractorPass : public Pass {
19 FunctionExtractorPass(Function *F = 0) : Named(F) {}
23 Named = M.getMainFunction();
24 if (Named == 0) return false; // No function to extract
27 // Make sure our result is globally accessible...
28 Named->setLinkage(GlobalValue::ExternalLinkage);
30 // Mark all global variables internal
31 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
32 if (!I->isExternal()) {
33 I->setInitializer(0); // Make all variables external
34 I->setLinkage(GlobalValue::ExternalLinkage);
37 // All of the functions may be used by global variables or the named
38 // function. Loop through them and create a new, external functions that
39 // can be "used", instead of ones with bodies.
41 std::vector<Function*> NewFunctions;
43 Function *Last = &M.back(); // Figure out where the last real fn is...
45 for (Module::iterator I = M.begin(); ; ++I) {
47 Function *New = new Function(I->getFunctionType(),
48 GlobalValue::ExternalLinkage,
50 I->setName(""); // Remove Old name
52 // If it's not the named function, delete the body of the function
53 I->dropAllReferences();
55 M.getFunctionList().push_back(New);
56 NewFunctions.push_back(New);
59 if (&*I == Last) break; // Stop after processing the last function
62 // Now that we have replacements all set up, loop through the module,
63 // deleting the old functions, replacing them with the newly created
65 if (!NewFunctions.empty()) {
67 Module::iterator I = M.begin();
70 // Make everything that uses the old function use the new dummy fn
71 I->replaceAllUsesWith(NewFunctions[FuncNum++]);
74 ++I; // Move the iterator to the new function
76 // Delete the old function!
77 M.getFunctionList().erase(Old);
80 ++I; // Skip the function we are extracting
82 } while (&*I != NewFunctions[0]);
89 RegisterPass<FunctionExtractorPass> X("extract", "Function Extractor");
92 Pass *llvm::createFunctionExtractionPass(Function *F) {
93 return new FunctionExtractorPass(F);