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"
33 #define DEBUG_TYPE "function-import"
35 /// Limit on instruction count of imported functions.
36 static cl::opt<unsigned> ImportInstrLimit(
37 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
38 cl::desc("Only import functions with less than N instructions"));
40 // Load lazily a module from \p FileName in \p Context.
41 static std::unique_ptr<Module> loadFile(const std::string &FileName,
42 LLVMContext &Context) {
44 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
45 std::unique_ptr<Module> Result = getLazyIRFileModule(FileName, Err, Context);
47 Err.print("function-import", errs());
51 Result->materializeMetadata();
52 UpgradeDebugInfo(*Result);
58 /// Helper to load on demand a Module from file and cache it for subsequent
59 /// queries. It can be used with the FunctionImporter.
60 class ModuleLazyLoaderCache {
61 /// Cache of lazily loaded module for import.
62 StringMap<std::unique_ptr<Module>> ModuleMap;
64 /// Retrieve a Module from the cache or lazily load it on demand.
65 std::function<std::unique_ptr<Module>(StringRef FileName)> createLazyModule;
68 /// Create the loader, Module will be initialized in \p Context.
69 ModuleLazyLoaderCache(std::function<
70 std::unique_ptr<Module>(StringRef FileName)> createLazyModule)
71 : createLazyModule(createLazyModule) {}
73 /// Retrieve a Module from the cache or lazily load it on demand.
74 Module &operator()(StringRef FileName);
77 // Get a Module for \p FileName from the cache, or load it lazily.
78 Module &ModuleLazyLoaderCache::operator()(StringRef Identifier) {
79 auto &Module = ModuleMap[Identifier];
81 Module = createLazyModule(Identifier);
84 } // anonymous namespace
86 /// Walk through the instructions in \p F looking for external
87 /// calls not already in the \p CalledFunctions set. If any are
88 /// found they are added to the \p Worklist for importing.
89 static void findExternalCalls(const Module &DestModule, Function &F,
90 const FunctionInfoIndex &Index,
91 StringSet<> &CalledFunctions,
92 SmallVector<StringRef, 64> &Worklist) {
93 // We need to suffix internal function calls imported from other modules,
94 // prepare the suffix ahead of time.
96 if (F.getParent() != &DestModule)
99 Twine(Index.getModuleId(F.getParent()->getModuleIdentifier()))).str();
103 if (isa<CallInst>(I)) {
104 auto CalledFunction = cast<CallInst>(I).getCalledFunction();
105 // Insert any new external calls that have not already been
106 // added to set/worklist.
107 if (!CalledFunction || !CalledFunction->hasName())
109 // Ignore intrinsics early
110 if (CalledFunction->isIntrinsic()) {
111 assert(CalledFunction->getIntrinsicID() != 0);
114 auto ImportedName = CalledFunction->getName();
115 auto Renamed = (ImportedName + Suffix).str();
116 // Rename internal functions
117 if (CalledFunction->hasInternalLinkage()) {
118 ImportedName = Renamed;
120 auto It = CalledFunctions.insert(ImportedName);
122 // This is a call to a function we already considered, skip.
125 // Ignore functions already present in the destination module
126 auto *SrcGV = DestModule.getNamedValue(ImportedName);
128 assert(isa<Function>(SrcGV) && "Name collision during import");
129 if (!cast<Function>(SrcGV)->isDeclaration()) {
130 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Ignoring "
131 << ImportedName << " already in DestinationModule\n");
136 Worklist.push_back(It.first->getKey());
137 DEBUG(dbgs() << DestModule.getModuleIdentifier()
138 << ": Adding callee for : " << ImportedName << " : "
139 << F.getName() << "\n");
145 // Helper function: given a worklist and an index, will process all the worklist
146 // and decide what to import based on the summary information.
148 // Nothing is actually imported, functions are materialized in their source
149 // module and analyzed there.
151 // \p ModuleToFunctionsToImportMap is filled with the set of Function to import
153 static void GetImportList(
154 Module &DestModule, SmallVector<StringRef, 64> &Worklist,
155 StringSet<> &CalledFunctions,
156 std::map<StringRef, std::pair<Module *, DenseSet<const GlobalValue *>>> &
157 ModuleToFunctionsToImportMap,
158 const FunctionInfoIndex &Index, ModuleLazyLoaderCache &ModuleLoaderCache) {
159 while (!Worklist.empty()) {
160 auto CalledFunctionName = Worklist.pop_back_val();
161 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Process import for "
162 << CalledFunctionName << "\n");
164 // Try to get a summary for this function call.
165 auto InfoList = Index.findFunctionInfoList(CalledFunctionName);
166 if (InfoList == Index.end()) {
167 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": No summary for "
168 << CalledFunctionName << " Ignoring.\n");
171 assert(!InfoList->second.empty() && "No summary, error at import?");
173 // Comdat can have multiple entries, FIXME: what do we do with them?
174 auto &Info = InfoList->second[0];
175 assert(Info && "Nullptr in list, error importing summaries?\n");
177 auto *Summary = Info->functionSummary();
179 // FIXME: in case we are lazyloading summaries, we can do it now.
180 DEBUG(dbgs() << DestModule.getModuleIdentifier()
181 << ": Missing summary for " << CalledFunctionName
182 << ", error at import?\n");
183 llvm_unreachable("Missing summary");
186 if (Summary->instCount() > ImportInstrLimit) {
187 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Skip import of "
188 << CalledFunctionName << " with " << Summary->instCount()
189 << " instructions (limit " << ImportInstrLimit << ")\n");
193 // Get the module path from the summary.
194 auto ModuleIdentifier = Summary->modulePath();
195 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Importing "
196 << CalledFunctionName << " from " << ModuleIdentifier << "\n");
198 auto &SrcModule = ModuleLoaderCache(ModuleIdentifier);
200 // The function that we will import!
201 GlobalValue *SGV = SrcModule.getNamedValue(CalledFunctionName);
204 // The destination module is referencing function using their renamed name
205 // when importing a function that was originally local in the source
206 // module. The source module we have might not have been renamed so we try
207 // to remove the suffix added during the renaming to recover the original
208 // name in the source module.
209 std::pair<StringRef, StringRef> Split =
210 CalledFunctionName.split(".llvm.");
211 SGV = SrcModule.getNamedValue(Split.first);
212 assert(SGV && "Can't find function to import in source module");
215 report_fatal_error(Twine("Can't load function '") + CalledFunctionName +
216 "' in Module '" + SrcModule.getModuleIdentifier() +
217 "', error in the summary?\n");
220 Function *F = dyn_cast<Function>(SGV);
221 if (!F && isa<GlobalAlias>(SGV)) {
222 auto *SGA = dyn_cast<GlobalAlias>(SGV);
223 F = dyn_cast<Function>(SGA->getBaseObject());
224 CalledFunctionName = F->getName();
226 assert(F && "Imported Function is ... not a Function");
228 // We cannot import weak_any functions/aliases without possibly affecting
229 // the order they are seen and selected by the linker, changing program
231 if (SGV->hasWeakAnyLinkage()) {
232 DEBUG(dbgs() << DestModule.getModuleIdentifier()
233 << ": Ignoring import request for weak-any "
234 << (isa<Function>(SGV) ? "function " : "alias ")
235 << CalledFunctionName << " from "
236 << SrcModule.getModuleIdentifier() << "\n");
240 // Add the function to the import list
241 auto &Entry = ModuleToFunctionsToImportMap[SrcModule.getModuleIdentifier()];
242 Entry.first = &SrcModule;
243 Entry.second.insert(F);
245 // Process the newly imported functions and add callees to the worklist.
247 findExternalCalls(DestModule, *F, Index, CalledFunctions, Worklist);
251 // Automatically import functions in Module \p DestModule based on the summaries
254 // The current implementation imports every called functions that exists in the
256 bool FunctionImporter::importFunctions(Module &DestModule) {
257 DEBUG(dbgs() << "Starting import for Module "
258 << DestModule.getModuleIdentifier() << "\n");
259 unsigned ImportedCount = 0;
261 /// First step is collecting the called external functions.
262 StringSet<> CalledFunctions;
263 SmallVector<StringRef, 64> Worklist;
264 for (auto &F : DestModule) {
265 if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
267 findExternalCalls(DestModule, F, Index, CalledFunctions, Worklist);
269 if (Worklist.empty())
272 /// Second step: for every call to an external function, try to import it.
274 // Linker that will be used for importing function
275 Linker TheLinker(DestModule);
277 // Map of Module -> List of Function to import from the Module
278 std::map<StringRef, std::pair<Module *, DenseSet<const GlobalValue *>>>
279 ModuleToFunctionsToImportMap;
281 // Analyze the summaries and get the list of functions to import by
282 // populating ModuleToFunctionsToImportMap
283 ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
284 GetImportList(DestModule, Worklist, CalledFunctions,
285 ModuleToFunctionsToImportMap, Index, ModuleLoaderCache);
286 assert(Worklist.empty() && "Worklist hasn't been flushed in GetImportList");
288 // Do the actual import of functions now, one Module at a time
289 for (auto &FunctionsToImportPerModule : ModuleToFunctionsToImportMap) {
290 // Get the module for the import
291 auto &FunctionsToImport = FunctionsToImportPerModule.second.second;
292 auto *SrcModule = FunctionsToImportPerModule.second.first;
293 assert(&DestModule.getContext() == &SrcModule->getContext() &&
296 // Link in the specified functions.
297 if (TheLinker.linkInModule(*SrcModule, Linker::Flags::None, &Index,
299 report_fatal_error("Function Import: link error");
301 ImportedCount += FunctionsToImport.size();
303 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
304 << DestModule.getModuleIdentifier() << "\n");
305 return ImportedCount;
308 /// Summary file to use for function importing when using -function-import from
309 /// the command line.
310 static cl::opt<std::string>
311 SummaryFile("summary-file",
312 cl::desc("The summary file to use for function importing."));
314 static void diagnosticHandler(const DiagnosticInfo &DI) {
315 raw_ostream &OS = errs();
316 DiagnosticPrinterRawOStream DP(OS);
321 /// Parse the function index out of an IR file and return the function
322 /// index object if found, or nullptr if not.
323 static std::unique_ptr<FunctionInfoIndex>
324 getFunctionIndexForFile(StringRef Path, std::string &Error,
325 DiagnosticHandlerFunction DiagnosticHandler) {
326 std::unique_ptr<MemoryBuffer> Buffer;
327 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
328 MemoryBuffer::getFile(Path);
329 if (std::error_code EC = BufferOrErr.getError()) {
330 Error = EC.message();
333 Buffer = std::move(BufferOrErr.get());
334 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
335 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
337 if (std::error_code EC = ObjOrErr.getError()) {
338 Error = EC.message();
341 return (*ObjOrErr)->takeIndex();
344 /// Pass that performs cross-module function import provided a summary file.
345 class FunctionImportPass : public ModulePass {
346 /// Optional function summary index to use for importing, otherwise
347 /// the summary-file option must be specified.
348 const FunctionInfoIndex *Index;
351 /// Pass identification, replacement for typeid
354 /// Specify pass name for debug output
355 const char *getPassName() const override {
356 return "Function Importing";
359 explicit FunctionImportPass(const FunctionInfoIndex *Index = nullptr)
360 : ModulePass(ID), Index(Index) {}
362 bool runOnModule(Module &M) override {
363 if (SummaryFile.empty() && !Index)
364 report_fatal_error("error: -function-import requires -summary-file or "
365 "file from frontend\n");
366 std::unique_ptr<FunctionInfoIndex> IndexPtr;
367 if (!SummaryFile.empty()) {
369 report_fatal_error("error: -summary-file and index from frontend\n");
371 IndexPtr = getFunctionIndexForFile(SummaryFile, Error, diagnosticHandler);
373 errs() << "Error loading file '" << SummaryFile << "': " << Error
377 Index = IndexPtr.get();
380 // Perform the import now.
381 auto ModuleLoader = [&M](StringRef Identifier) {
382 return loadFile(Identifier, M.getContext());
384 FunctionImporter Importer(*Index, ModuleLoader);
385 return Importer.importFunctions(M);
391 char FunctionImportPass::ID = 0;
392 INITIALIZE_PASS_BEGIN(FunctionImportPass, "function-import",
393 "Summary Based Function Import", false, false)
394 INITIALIZE_PASS_END(FunctionImportPass, "function-import",
395 "Summary Based Function Import", false, false)
398 Pass *createFunctionImportPass(const FunctionInfoIndex *Index = nullptr) {
399 return new FunctionImportPass(Index);