LLVM API Documentation

Internalize.cpp
Go to the documentation of this file.
00001 //===-- Internalize.cpp - Mark functions internal -------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass loops over all of the functions and variables in the input module.
00011 // If the function or variable is not in the list of external names given to
00012 // the pass it is marked as internal.
00013 //
00014 // This transformation would not be legal in a regular compilation, but it gets
00015 // extra information from the linker about what is safe.
00016 //
00017 // For example: Internalizing a function with external linkage. Only if we are
00018 // told it is only used from within this module, it is safe to do it.
00019 //
00020 //===----------------------------------------------------------------------===//
00021 
00022 #include "llvm/Transforms/IPO.h"
00023 #include "llvm/ADT/SmallPtrSet.h"
00024 #include "llvm/ADT/Statistic.h"
00025 #include "llvm/Analysis/CallGraph.h"
00026 #include "llvm/IR/Module.h"
00027 #include "llvm/Pass.h"
00028 #include "llvm/Support/CommandLine.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include "llvm/Transforms/Utils/GlobalStatus.h"
00032 #include "llvm/Transforms/Utils/ModuleUtils.h"
00033 #include <fstream>
00034 #include <set>
00035 using namespace llvm;
00036 
00037 #define DEBUG_TYPE "internalize"
00038 
00039 STATISTIC(NumAliases  , "Number of aliases internalized");
00040 STATISTIC(NumFunctions, "Number of functions internalized");
00041 STATISTIC(NumGlobals  , "Number of global vars internalized");
00042 
00043 // APIFile - A file which contains a list of symbols that should not be marked
00044 // external.
00045 static cl::opt<std::string>
00046 APIFile("internalize-public-api-file", cl::value_desc("filename"),
00047         cl::desc("A file containing list of symbol names to preserve"));
00048 
00049 // APIList - A list of symbols that should not be marked internal.
00050 static cl::list<std::string>
00051 APIList("internalize-public-api-list", cl::value_desc("list"),
00052         cl::desc("A list of symbol names to preserve"),
00053         cl::CommaSeparated);
00054 
00055 namespace {
00056   class InternalizePass : public ModulePass {
00057     std::set<std::string> ExternalNames;
00058   public:
00059     static char ID; // Pass identification, replacement for typeid
00060     explicit InternalizePass();
00061     explicit InternalizePass(ArrayRef<const char *> ExportList);
00062     void LoadFile(const char *Filename);
00063     bool runOnModule(Module &M) override;
00064 
00065     void getAnalysisUsage(AnalysisUsage &AU) const override {
00066       AU.setPreservesCFG();
00067       AU.addPreserved<CallGraphWrapperPass>();
00068     }
00069   };
00070 } // end anonymous namespace
00071 
00072 char InternalizePass::ID = 0;
00073 INITIALIZE_PASS(InternalizePass, "internalize",
00074                 "Internalize Global Symbols", false, false)
00075 
00076 InternalizePass::InternalizePass() : ModulePass(ID) {
00077   initializeInternalizePassPass(*PassRegistry::getPassRegistry());
00078   if (!APIFile.empty())           // If a filename is specified, use it.
00079     LoadFile(APIFile.c_str());
00080   ExternalNames.insert(APIList.begin(), APIList.end());
00081 }
00082 
00083 InternalizePass::InternalizePass(ArrayRef<const char *> ExportList)
00084     : ModulePass(ID) {
00085   initializeInternalizePassPass(*PassRegistry::getPassRegistry());
00086   for(ArrayRef<const char *>::const_iterator itr = ExportList.begin();
00087         itr != ExportList.end(); itr++) {
00088     ExternalNames.insert(*itr);
00089   }
00090 }
00091 
00092 void InternalizePass::LoadFile(const char *Filename) {
00093   // Load the APIFile...
00094   std::ifstream In(Filename);
00095   if (!In.good()) {
00096     errs() << "WARNING: Internalize couldn't load file '" << Filename
00097          << "'! Continuing as if it's empty.\n";
00098     return; // Just continue as if the file were empty
00099   }
00100   while (In) {
00101     std::string Symbol;
00102     In >> Symbol;
00103     if (!Symbol.empty())
00104       ExternalNames.insert(Symbol);
00105   }
00106 }
00107 
00108 static bool shouldInternalize(const GlobalValue &GV,
00109                               const std::set<std::string> &ExternalNames) {
00110   // Function must be defined here
00111   if (GV.isDeclaration())
00112     return false;
00113 
00114   // Available externally is really just a "declaration with a body".
00115   if (GV.hasAvailableExternallyLinkage())
00116     return false;
00117 
00118   // Assume that dllexported symbols are referenced elsewhere
00119   if (GV.hasDLLExportStorageClass())
00120     return false;
00121 
00122   // Already has internal linkage
00123   if (GV.hasLocalLinkage())
00124     return false;
00125 
00126   // Marked to keep external?
00127   if (ExternalNames.count(GV.getName()))
00128     return false;
00129 
00130   return true;
00131 }
00132 
00133 bool InternalizePass::runOnModule(Module &M) {
00134   CallGraphWrapperPass *CGPass = getAnalysisIfAvailable<CallGraphWrapperPass>();
00135   CallGraph *CG = CGPass ? &CGPass->getCallGraph() : 0;
00136   CallGraphNode *ExternalNode = CG ? CG->getExternalCallingNode() : 0;
00137   bool Changed = false;
00138 
00139   SmallPtrSet<GlobalValue *, 8> Used;
00140   collectUsedGlobalVariables(M, Used, false);
00141 
00142   // We must assume that globals in llvm.used have a reference that not even
00143   // the linker can see, so we don't internalize them.
00144   // For llvm.compiler.used the situation is a bit fuzzy. The assembler and
00145   // linker can drop those symbols. If this pass is running as part of LTO,
00146   // one might think that it could just drop llvm.compiler.used. The problem
00147   // is that even in LTO llvm doesn't see every reference. For example,
00148   // we don't see references from function local inline assembly. To be
00149   // conservative, we internalize symbols in llvm.compiler.used, but we
00150   // keep llvm.compiler.used so that the symbol is not deleted by llvm.
00151   for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.begin(), E = Used.end();
00152        I != E; ++I) {
00153     GlobalValue *V = *I;
00154     ExternalNames.insert(V->getName());
00155   }
00156 
00157   // Mark all functions not in the api as internal.
00158   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00159     if (!shouldInternalize(*I, ExternalNames))
00160       continue;
00161 
00162     I->setLinkage(GlobalValue::InternalLinkage);
00163 
00164     if (ExternalNode)
00165       // Remove a callgraph edge from the external node to this function.
00166       ExternalNode->removeOneAbstractEdgeTo((*CG)[I]);
00167 
00168     Changed = true;
00169     ++NumFunctions;
00170     DEBUG(dbgs() << "Internalizing func " << I->getName() << "\n");
00171   }
00172 
00173   // Never internalize the llvm.used symbol.  It is used to implement
00174   // attribute((used)).
00175   // FIXME: Shouldn't this just filter on llvm.metadata section??
00176   ExternalNames.insert("llvm.used");
00177   ExternalNames.insert("llvm.compiler.used");
00178 
00179   // Never internalize anchors used by the machine module info, else the info
00180   // won't find them.  (see MachineModuleInfo.)
00181   ExternalNames.insert("llvm.global_ctors");
00182   ExternalNames.insert("llvm.global_dtors");
00183   ExternalNames.insert("llvm.global.annotations");
00184 
00185   // Never internalize symbols code-gen inserts.
00186   // FIXME: We should probably add this (and the __stack_chk_guard) via some
00187   // type of call-back in CodeGen.
00188   ExternalNames.insert("__stack_chk_fail");
00189   ExternalNames.insert("__stack_chk_guard");
00190 
00191   // Mark all global variables with initializers that are not in the api as
00192   // internal as well.
00193   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00194        I != E; ++I) {
00195     if (!shouldInternalize(*I, ExternalNames))
00196       continue;
00197 
00198     I->setLinkage(GlobalValue::InternalLinkage);
00199     Changed = true;
00200     ++NumGlobals;
00201     DEBUG(dbgs() << "Internalized gvar " << I->getName() << "\n");
00202   }
00203 
00204   // Mark all aliases that are not in the api as internal as well.
00205   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
00206        I != E; ++I) {
00207     if (!shouldInternalize(*I, ExternalNames))
00208       continue;
00209 
00210     I->setLinkage(GlobalValue::InternalLinkage);
00211     Changed = true;
00212     ++NumAliases;
00213     DEBUG(dbgs() << "Internalized alias " << I->getName() << "\n");
00214   }
00215 
00216   return Changed;
00217 }
00218 
00219 ModulePass *llvm::createInternalizePass() { return new InternalizePass(); }
00220 
00221 ModulePass *llvm::createInternalizePass(ArrayRef<const char *> ExportList) {
00222   return new InternalizePass(ExportList);
00223 }