ExtractGV.cpp revision d245a8ae470e2ee84d138379f793095646c590e5
1//===-- ExtractGV.cpp - Global Value extraction pass ----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass extracts global values
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Instructions.h"
15#include "llvm/Module.h"
16#include "llvm/Pass.h"
17#include "llvm/Constants.h"
18#include "llvm/Transforms/IPO.h"
19#include "llvm/Support/Compiler.h"
20using namespace llvm;
21
22namespace {
23  /// @brief A pass to extract specific functions and their dependencies.
24  class VISIBILITY_HIDDEN GVExtractorPass : public ModulePass {
25    std::vector<GlobalValue*> Named;
26    bool deleteStuff;
27    bool reLink;
28  public:
29    static char ID; // Pass identification, replacement for typeid
30
31    /// FunctionExtractorPass - If deleteFn is true, this pass deletes as the
32    /// specified function. Otherwise, it deletes as much of the module as
33    /// possible, except for the function specified.
34    ///
35    explicit GVExtractorPass(std::vector<GlobalValue*>& GVs, bool deleteS = true,
36                             bool relinkCallees = false)
37      : ModulePass((intptr_t)&ID), Named(GVs), deleteStuff(deleteS),
38        reLink(relinkCallees) {}
39
40    bool runOnModule(Module &M) {
41      if (Named.size() == 0) {
42        return false;  // Nothing to extract
43      }
44
45      if (deleteStuff)
46        return deleteGV();
47      M.setModuleInlineAsm("");
48      return isolateGV(M);
49    }
50
51    bool deleteGV() {
52      for (std::vector<GlobalValue*>::iterator GI = Named.begin(),
53             GE = Named.end(); GI != GE; ++GI) {
54        if (Function* NamedFunc = dyn_cast<Function>(&*GI)) {
55         // If we're in relinking mode, set linkage of all internal callees to
56         // external. This will allow us extract function, and then - link
57         // everything together
58         if (reLink) {
59           for (Function::iterator B = NamedFunc->begin(), BE = NamedFunc->end();
60                B != BE; ++B) {
61             for (BasicBlock::iterator I = B->begin(), E = B->end();
62                  I != E; ++I) {
63               if (CallInst* callInst = dyn_cast<CallInst>(&*I)) {
64                 Function* Callee = callInst->getCalledFunction();
65                 if (Callee && Callee->hasInternalLinkage())
66                   Callee->setLinkage(GlobalValue::ExternalLinkage);
67               }
68             }
69           }
70         }
71
72         NamedFunc->setLinkage(GlobalValue::ExternalLinkage);
73         NamedFunc->deleteBody();
74         assert(NamedFunc->isDeclaration() && "This didn't make the function external!");
75       } else {
76          if (!(*GI)->isDeclaration()) {
77            cast<GlobalVariable>(*GI)->setInitializer(0);  //clear the initializer
78            (*GI)->setLinkage(GlobalValue::ExternalLinkage);
79          }
80        }
81      }
82      return true;
83    }
84
85    bool isolateGV(Module &M) {
86      // Mark all globals internal
87      for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
88        if (!I->isDeclaration()) {
89          I->setLinkage(GlobalValue::InternalLinkage);
90        }
91      for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
92        if (!I->isDeclaration()) {
93          I->setLinkage(GlobalValue::InternalLinkage);
94        }
95
96      // Make sure our result is globally accessible...
97      // by putting them in the used array
98      {
99        std::vector<Constant *> AUGs;
100        const Type *SBP= PointerType::getUnqual(Type::Int8Ty);
101        for (std::vector<GlobalValue*>::iterator GI = Named.begin(),
102               GE = Named.end(); GI != GE; ++GI) {
103          (*GI)->setLinkage(GlobalValue::ExternalLinkage);
104          AUGs.push_back(ConstantExpr::getBitCast(*GI, SBP));
105        }
106        ArrayType *AT = ArrayType::get(SBP, AUGs.size());
107        Constant *Init = ConstantArray::get(AT, AUGs);
108        GlobalValue *gv = new GlobalVariable(AT, false,
109                                             GlobalValue::AppendingLinkage,
110                                             Init, "llvm.used", &M);
111        gv->setSection("llvm.metadata");
112      }
113
114      // All of the functions may be used by global variables or the named
115      // globals.  Loop through them and create a new, external functions that
116      // can be "used", instead of ones with bodies.
117      std::vector<Function*> NewFunctions;
118
119      Function *Last = --M.end();  // Figure out where the last real fn is.
120
121      for (Module::iterator I = M.begin(); ; ++I) {
122        if (std::find(Named.begin(), Named.end(), &*I) == Named.end()) {
123          Function *New = new Function(I->getFunctionType(),
124                                       GlobalValue::ExternalLinkage);
125          New->setCallingConv(I->getCallingConv());
126          New->setParamAttrs(I->getParamAttrs());
127          if (I->hasCollector())
128            New->setCollector(I->getCollector());
129
130          // If it's not the named function, delete the body of the function
131          I->dropAllReferences();
132
133          M.getFunctionList().push_back(New);
134          NewFunctions.push_back(New);
135          New->takeName(I);
136        }
137
138        if (&*I == Last) break;  // Stop after processing the last function
139      }
140
141      // Now that we have replacements all set up, loop through the module,
142      // deleting the old functions, replacing them with the newly created
143      // functions.
144      if (!NewFunctions.empty()) {
145        unsigned FuncNum = 0;
146        Module::iterator I = M.begin();
147        do {
148          if (std::find(Named.begin(), Named.end(), &*I) == Named.end()) {
149            // Make everything that uses the old function use the new dummy fn
150            I->replaceAllUsesWith(NewFunctions[FuncNum++]);
151
152            Function *Old = I;
153            ++I;  // Move the iterator to the new function
154
155            // Delete the old function!
156            M.getFunctionList().erase(Old);
157
158          } else {
159            ++I;  // Skip the function we are extracting
160          }
161        } while (&*I != NewFunctions[0]);
162      }
163
164      return true;
165    }
166  };
167
168  char GVExtractorPass::ID = 0;
169}
170
171ModulePass *llvm::createGVExtractionPass(std::vector<GlobalValue*>& GVs,
172                                         bool deleteFn, bool relinkCallees) {
173  return new GVExtractorPass(GVs, deleteFn, relinkCallees);
174}
175