1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Function import based on summaries.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/IPO/FunctionImport.h"
16 #include "llvm/ADT/StringSet.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/DiagnosticPrinter.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IRReader/IRReader.h"
22 #include "llvm/Linker/Linker.h"
23 #include "llvm/Object/FunctionIndexObjectFile.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/SourceMgr.h"
32 #define DEBUG_TYPE "function-import"
34 /// Limit on instruction count of imported functions.
35 static cl::opt<unsigned> ImportInstrLimit(
36 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
37 cl::desc("Only import functions with less than N instructions"));
39 // Load lazily a module from \p FileName in \p Context.
40 static std::unique_ptr<Module> loadFile(const std::string &FileName,
41 LLVMContext &Context) {
43 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
44 std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
46 Err.print("function-import", errs());
50 Result->materializeMetadata();
51 UpgradeDebugInfo(*Result);
57 /// Helper to load on demand a Module from file and cache it for subsequent
58 /// queries. It can be used with the FunctionImporter.
59 class ModuleLazyLoaderCache {
60 /// Cache of lazily loaded module for import.
61 StringMap<std::unique_ptr<Module>> ModuleMap;
63 /// Retrieve a Module from the cache or lazily load it on demand.
64 std::function<std::unique_ptr<Module>(StringRef FileName)> createLazyModule;
67 /// Create the loader, Module will be initialized in \p Context.
68 ModuleLazyLoaderCache(std::function<
69 std::unique_ptr<Module>(StringRef FileName)> createLazyModule)
70 : createLazyModule(createLazyModule) {}
72 /// Retrieve a Module from the cache or lazily load it on demand.
73 Module &operator()(StringRef FileName);
76 // Get a Module for \p FileName from the cache, or load it lazily.
77 Module &ModuleLazyLoaderCache::operator()(StringRef Identifier) {
78 auto &Module = ModuleMap[Identifier];
80 Module = createLazyModule(Identifier);
83 } // anonymous namespace
85 /// Walk through the instructions in \p F looking for external
86 /// calls not already in the \p CalledFunctions set. If any are
87 /// found they are added to the \p Worklist for importing.
88 static void findExternalCalls(const Module &DestModule, Function &F,
89 const FunctionInfoIndex &Index,
90 StringSet<> &CalledFunctions,
91 SmallVector<StringRef, 64> &Worklist) {
92 // We need to suffix internal function calls imported from other modules,
93 // prepare the suffix ahead of time.
95 if (F.getParent() != &DestModule)
98 Twine(Index.getModuleId(F.getParent()->getModuleIdentifier()))).str();
102 if (isa<CallInst>(I)) {
103 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
104 // Insert any new external calls that have not already been
105 // added to set/worklist.
106 if (!CalledFunction || !CalledFunction->hasName())
108 // Ignore intrinsics early
109 if (CalledFunction->isIntrinsic()) {
110 assert(CalledFunction->getIntrinsicID() != 0);
113 auto ImportedName = CalledFunction->getName();
114 auto Renamed = (ImportedName + Suffix).str();
115 // Rename internal functions
116 if (CalledFunction->hasInternalLinkage()) {
117 ImportedName = Renamed;
119 auto It = CalledFunctions.insert(ImportedName);
121 // This is a call to a function we already considered, skip.
124 // Ignore functions already present in the destination module
125 auto *SrcGV = DestModule.getNamedValue(ImportedName);
127 assert(isa<Function>(SrcGV) && "Name collision during import");
128 if (!cast<Function>(SrcGV)->isDeclaration()) {
129 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Ignoring "
130 << ImportedName << " already in DestinationModule\n");
135 Worklist.push_back(It.first->getKey());
136 DEBUG(dbgs() << DestModule.getModuleIdentifier()
137 << ": Adding callee for : " << ImportedName << " : "
138 << F.getName() << "\n");
144 // Helper function: given a worklist and an index, will process all the worklist
145 // and decide what to import based on the summary information.
147 // Nothing is actually imported, functions are materialized in their source
148 // module and analyzed there.
150 // \p ModuleToFunctionsToImportMap is filled with the set of Function to import
152 static void GetImportList(
153 Module &DestModule, SmallVector<StringRef, 64> &Worklist,
154 StringSet<> &CalledFunctions,
155 std::map<StringRef, std::pair<Module *, DenseSet<const GlobalValue *>>> &
156 ModuleToFunctionsToImportMap,
157 const FunctionInfoIndex &Index, ModuleLazyLoaderCache &ModuleLoaderCache) {
158 while (!Worklist.empty()) {
159 auto CalledFunctionName = Worklist.pop_back_val();
160 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Process import for "
161 << CalledFunctionName << "\n");
163 // Try to get a summary for this function call.
164 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
165 if (InfoList == Index.end()) {
166 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": No summary for "
167 << CalledFunctionName << " Ignoring.\n");
170 assert(!InfoList->second.empty() && "No summary, error at import?");
172 // Comdat can have multiple entries, FIXME: what do we do with them?
173 auto &Info = InfoList->second[0];
174 assert(Info && "Nullptr in list, error importing summaries?\n");
176 auto *Summary = Info->functionSummary();
178 // FIXME: in case we are lazyloading summaries, we can do it now.
179 DEBUG(dbgs() << DestModule.getModuleIdentifier()
180 << ": Missing summary for " << CalledFunctionName
181 << ", error at import?\n");
182 llvm_unreachable("Missing summary");
185 if (Summary->instCount() > ImportInstrLimit) {
186 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Skip import of "
187 << CalledFunctionName << " with " << Summary->instCount()
188 << " instructions (limit " << ImportInstrLimit << ")\n");
192 // Get the module path from the summary.
193 auto ModuleIdentifier = Summary->modulePath();
194 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Importing "
195 << CalledFunctionName << " from " << ModuleIdentifier << "\n");
197 auto &SrcModule = ModuleLoaderCache(ModuleIdentifier);
199 // The function that we will import!
200 GlobalValue *SGV = SrcModule.getNamedValue(CalledFunctionName);
203 // The destination module is referencing function using their renamed name
204 // when importing a function that was originally local in the source
205 // module. The source module we have might not have been renamed so we try
206 // to remove the suffix added during the renaming to recover the original
207 // name in the source module.
208 std::pair<StringRef, StringRef> Split =
209 CalledFunctionName.split(".llvm.");
210 SGV = SrcModule.getNamedValue(Split.first);
211 assert(SGV && "Can't find function to import in source module");
214 report_fatal_error(Twine("Can't load function '") + CalledFunctionName +
215 "' in Module '" + SrcModule.getModuleIdentifier() +
216 "', error in the summary?\n");
219 Function *F = dyn_cast<Function>(SGV);
220 if (!F && isa<GlobalAlias>(SGV)) {
221 auto *SGA = dyn_cast<GlobalAlias>(SGV);
222 F = dyn_cast<Function>(SGA->getBaseObject());
223 CalledFunctionName = F->getName();
225 assert(F && "Imported Function is ... not a Function");
227 // We cannot import weak_any functions/aliases without possibly affecting
228 // the order they are seen and selected by the linker, changing program
230 if (SGV->hasWeakAnyLinkage()) {
231 DEBUG(dbgs() << DestModule.getModuleIdentifier()
232 << ": Ignoring import request for weak-any "
233 << (isa<Function>(SGV) ? "function " : "alias ")
234 << CalledFunctionName << " from "
235 << SrcModule.getModuleIdentifier() << "\n");
239 // Add the function to the import list
240 auto &Entry = ModuleToFunctionsToImportMap[SrcModule.getModuleIdentifier()];
241 Entry.first = &SrcModule;
242 Entry.second.insert(F);
244 // Process the newly imported functions and add callees to the worklist.
246 findExternalCalls(DestModule, *F, Index, CalledFunctions, Worklist);
250 // Automatically import functions in Module \p DestModule based on the summaries
253 // The current implementation imports every called functions that exists in the
255 bool FunctionImporter::importFunctions(Module &DestModule) {
256 DEBUG(dbgs() << "Starting import for Module "
257 << DestModule.getModuleIdentifier() << "\n");
258 unsigned ImportedCount = 0;
260 /// First step is collecting the called external functions.
261 StringSet<> CalledFunctions;
262 SmallVector<StringRef, 64> Worklist;
263 for (auto &F : DestModule) {
264 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
266 findExternalCalls(DestModule, F, Index, CalledFunctions, Worklist);
268 if (Worklist.empty())
271 /// Second step: for every call to an external function, try to import it.
273 // Linker that will be used for importing function
274 Linker TheLinker(DestModule);
276 // Map of Module -> List of Function to import from the Module
277 std::map<StringRef, std::pair<Module *, DenseSet<const GlobalValue *>>>
278 ModuleToFunctionsToImportMap;
280 // Analyze the summaries and get the list of functions to import by
281 // populating ModuleToFunctionsToImportMap
282 ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
283 GetImportList(DestModule, Worklist, CalledFunctions,
284 ModuleToFunctionsToImportMap, Index, ModuleLoaderCache);
285 assert(Worklist.empty() && "Worklist hasn't been flushed in GetImportList");
287 // Do the actual import of functions now, one Module at a time
288 for (auto &FunctionsToImportPerModule : ModuleToFunctionsToImportMap) {
289 // Get the module for the import
290 auto &FunctionsToImport = FunctionsToImportPerModule.second.second;
291 auto *SrcModule = FunctionsToImportPerModule.second.first;
292 assert(&DestModule.getContext() == &SrcModule->getContext() &&
295 // Link in the specified functions.
296 if (TheLinker.linkInModule(*SrcModule, Linker::Flags::None, &Index,
298 report_fatal_error("Function Import: link error");
300 ImportedCount += FunctionsToImport.size();
302 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
303 << DestModule.getModuleIdentifier() << "\n");
304 return ImportedCount;
307 /// Summary file to use for function importing when using -function-import from
308 /// the command line.
309 static cl::opt<std::string>
310 SummaryFile("summary-file",
311 cl::desc("The summary file to use for function importing."));
313 static void diagnosticHandler(const DiagnosticInfo &DI) {
314 raw_ostream &OS = errs();
315 DiagnosticPrinterRawOStream DP(OS);
320 /// Parse the function index out of an IR file and return the function
321 /// index object if found, or nullptr if not.
322 static std::unique_ptr<FunctionInfoIndex>
323 getFunctionIndexForFile(StringRef Path, std::string &Error,
324 DiagnosticHandlerFunction DiagnosticHandler) {
325 std::unique_ptr<MemoryBuffer> Buffer;
326 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
327 MemoryBuffer::getFile(Path);
328 if (std::error_code EC = BufferOrErr.getError()) {
329 Error = EC.message();
332 Buffer = std::move(BufferOrErr.get());
333 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
334 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
336 if (std::error_code EC = ObjOrErr.getError()) {
337 Error = EC.message();
340 return (*ObjOrErr)->takeIndex();
343 /// Pass that performs cross-module function import provided a summary file.
344 class FunctionImportPass : public ModulePass {
345 /// Optional function summary index to use for importing, otherwise
346 /// the summary-file option must be specified.
347 const FunctionInfoIndex *Index;
350 /// Pass identification, replacement for typeid
353 /// Specify pass name for debug output
354 const char *getPassName() const override {
355 return "Function Importing";
358 explicit FunctionImportPass(const FunctionInfoIndex *Index = nullptr)
359 : ModulePass(ID), Index(Index) {}
361 bool runOnModule(Module &M) override {
362 if (SummaryFile.empty() && !Index)
363 report_fatal_error("error: -function-import requires -summary-file or "
364 "file from frontend\n");
365 std::unique_ptr<FunctionInfoIndex> IndexPtr;
366 if (!SummaryFile.empty()) {
368 report_fatal_error("error: -summary-file and index from frontend\n");
370 IndexPtr = getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
372 errs() << "Error loading file '" << SummaryFile << "': " << Error
376 Index = IndexPtr.get();
379 // Perform the import now.
380 auto ModuleLoader = [&M](StringRef Identifier) {
381 return loadFile(Identifier, M.getContext());
383 FunctionImporter Importer(*Index, ModuleLoader);
384 return Importer.importFunctions(M);
390 char FunctionImportPass::ID = 0;
391 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
392 "Summary Based Function Import", false, false)
393 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
394 "Summary Based Function Import", false, false)
397 Pass *createFunctionImportPass(const FunctionInfoIndex *Index = nullptr) {
398 return new FunctionImportPass(Index);