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