1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the "backend" phase of LTO, i.e. it performs
10 // optimization and code generation on a loaded module. It is generally used
11 // internally by the LTO class but can also be used independently, for example
12 // to implement a standalone ThinLTO backend.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/LTO/LTOBackend.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/CGSCCPassManager.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Bitcode/BitcodeReader.h"
22 #include "llvm/Bitcode/BitcodeWriter.h"
23 #include "llvm/IR/LegacyPassManager.h"
24 #include "llvm/IR/PassManager.h"
25 #include "llvm/IR/RemarkStreamer.h"
26 #include "llvm/IR/Verifier.h"
27 #include "llvm/LTO/LTO.h"
28 #include "llvm/MC/SubtargetFeature.h"
29 #include "llvm/Object/ModuleSymbolTable.h"
30 #include "llvm/Passes/PassBuilder.h"
31 #include "llvm/Passes/StandardInstrumentations.h"
32 #include "llvm/Support/Error.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/Program.h"
37 #include "llvm/Support/SmallVectorMemoryBuffer.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/ThreadPool.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Transforms/IPO.h"
43 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
44 #include "llvm/Transforms/Scalar/LoopPassManager.h"
45 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
46 #include "llvm/Transforms/Utils/SplitModule.h"
47 
48 using namespace llvm;
49 using namespace lto;
50 
51 LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
52   errs() << "failed to open " << Path << ": " << Msg << '\n';
53   errs().flush();
54   exit(1);
55 }
56 
57 Error Config::addSaveTemps(std::string OutputFileName,
58                            bool UseInputModulePath) {
59   ShouldDiscardValueNames = false;
60 
61   std::error_code EC;
62   ResolutionFile = std::make_unique<raw_fd_ostream>(
63       OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::OF_Text);
64   if (EC)
65     return errorCodeToError(EC);
66 
67   auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
68     // Keep track of the hook provided by the linker, which also needs to run.
69     ModuleHookFn LinkerHook = Hook;
70     Hook = [=](unsigned Task, const Module &M) {
71       // If the linker's hook returned false, we need to pass that result
72       // through.
73       if (LinkerHook && !LinkerHook(Task, M))
74         return false;
75 
76       std::string PathPrefix;
77       // If this is the combined module (not a ThinLTO backend compile) or the
78       // user hasn't requested using the input module's path, emit to a file
79       // named from the provided OutputFileName with the Task ID appended.
80       if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
81         PathPrefix = OutputFileName;
82         if (Task != (unsigned)-1)
83           PathPrefix += utostr(Task) + ".";
84       } else
85         PathPrefix = M.getModuleIdentifier() + ".";
86       std::string Path = PathPrefix + PathSuffix + ".bc";
87       std::error_code EC;
88       raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
89       // Because -save-temps is a debugging feature, we report the error
90       // directly and exit.
91       if (EC)
92         reportOpenError(Path, EC.message());
93       WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
94       return true;
95     };
96   };
97 
98   setHook("0.preopt", PreOptModuleHook);
99   setHook("1.promote", PostPromoteModuleHook);
100   setHook("2.internalize", PostInternalizeModuleHook);
101   setHook("3.import", PostImportModuleHook);
102   setHook("4.opt", PostOptModuleHook);
103   setHook("5.precodegen", PreCodeGenModuleHook);
104 
105   CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
106     std::string Path = OutputFileName + "index.bc";
107     std::error_code EC;
108     raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
109     // Because -save-temps is a debugging feature, we report the error
110     // directly and exit.
111     if (EC)
112       reportOpenError(Path, EC.message());
113     WriteIndexToFile(Index, OS);
114 
115     Path = OutputFileName + "index.dot";
116     raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::OF_None);
117     if (EC)
118       reportOpenError(Path, EC.message());
119     Index.exportToDot(OSDot);
120     return true;
121   };
122 
123   return Error::success();
124 }
125 
126 namespace {
127 
128 std::unique_ptr<TargetMachine>
129 createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
130   StringRef TheTriple = M.getTargetTriple();
131   SubtargetFeatures Features;
132   Features.getDefaultSubtargetFeatures(Triple(TheTriple));
133   for (const std::string &A : Conf.MAttrs)
134     Features.AddFeature(A);
135 
136   Reloc::Model RelocModel;
137   if (Conf.RelocModel)
138     RelocModel = *Conf.RelocModel;
139   else
140     RelocModel =
141         M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
142 
143   Optional<CodeModel::Model> CodeModel;
144   if (Conf.CodeModel)
145     CodeModel = *Conf.CodeModel;
146   else
147     CodeModel = M.getCodeModel();
148 
149   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
150       TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
151       CodeModel, Conf.CGOptLevel));
152 }
153 
154 static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
155                            unsigned OptLevel, bool IsThinLTO,
156                            ModuleSummaryIndex *ExportSummary,
157                            const ModuleSummaryIndex *ImportSummary) {
158   Optional<PGOOptions> PGOOpt;
159   if (!Conf.SampleProfile.empty())
160     PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
161                         PGOOptions::SampleUse, PGOOptions::NoCSAction, true);
162   else if (Conf.RunCSIRInstr) {
163     PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
164                         PGOOptions::IRUse, PGOOptions::CSIRInstr);
165   } else if (!Conf.CSIRProfile.empty()) {
166     PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
167                         PGOOptions::IRUse, PGOOptions::CSIRUse);
168   }
169 
170   PassInstrumentationCallbacks PIC;
171   StandardInstrumentations SI;
172   SI.registerCallbacks(PIC);
173   PassBuilder PB(TM, PipelineTuningOptions(),PGOOpt, &PIC);
174   AAManager AA;
175 
176   // Parse a custom AA pipeline if asked to.
177   if (auto Err = PB.parseAAPipeline(AA, "default"))
178     report_fatal_error("Error parsing default AA pipeline");
179 
180   LoopAnalysisManager LAM(Conf.DebugPassManager);
181   FunctionAnalysisManager FAM(Conf.DebugPassManager);
182   CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
183   ModuleAnalysisManager MAM(Conf.DebugPassManager);
184 
185   // Register the AA manager first so that our version is the one used.
186   FAM.registerPass([&] { return std::move(AA); });
187 
188   // Register all the basic analyses with the managers.
189   PB.registerModuleAnalyses(MAM);
190   PB.registerCGSCCAnalyses(CGAM);
191   PB.registerFunctionAnalyses(FAM);
192   PB.registerLoopAnalyses(LAM);
193   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
194 
195   ModulePassManager MPM(Conf.DebugPassManager);
196   // FIXME (davide): verify the input.
197 
198   PassBuilder::OptimizationLevel OL;
199 
200   switch (OptLevel) {
201   default:
202     llvm_unreachable("Invalid optimization level");
203   case 0:
204     OL = PassBuilder::O0;
205     break;
206   case 1:
207     OL = PassBuilder::O1;
208     break;
209   case 2:
210     OL = PassBuilder::O2;
211     break;
212   case 3:
213     OL = PassBuilder::O3;
214     break;
215   }
216 
217   if (IsThinLTO)
218     MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager,
219                                          ImportSummary);
220   else
221     MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
222   MPM.run(Mod, MAM);
223 
224   // FIXME (davide): verify the output.
225 }
226 
227 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
228                                  std::string PipelineDesc,
229                                  std::string AAPipelineDesc,
230                                  bool DisableVerify) {
231   PassBuilder PB(TM);
232   AAManager AA;
233 
234   // Parse a custom AA pipeline if asked to.
235   if (!AAPipelineDesc.empty())
236     if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
237       report_fatal_error("unable to parse AA pipeline description '" +
238                          AAPipelineDesc + "': " + toString(std::move(Err)));
239 
240   LoopAnalysisManager LAM;
241   FunctionAnalysisManager FAM;
242   CGSCCAnalysisManager CGAM;
243   ModuleAnalysisManager MAM;
244 
245   // Register the AA manager first so that our version is the one used.
246   FAM.registerPass([&] { return std::move(AA); });
247 
248   // Register all the basic analyses with the managers.
249   PB.registerModuleAnalyses(MAM);
250   PB.registerCGSCCAnalyses(CGAM);
251   PB.registerFunctionAnalyses(FAM);
252   PB.registerLoopAnalyses(LAM);
253   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
254 
255   ModulePassManager MPM;
256 
257   // Always verify the input.
258   MPM.addPass(VerifierPass());
259 
260   // Now, add all the passes we've been requested to.
261   if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
262     report_fatal_error("unable to parse pass pipeline description '" +
263                        PipelineDesc + "': " + toString(std::move(Err)));
264 
265   if (!DisableVerify)
266     MPM.addPass(VerifierPass());
267   MPM.run(Mod, MAM);
268 }
269 
270 static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
271                            bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
272                            const ModuleSummaryIndex *ImportSummary) {
273   legacy::PassManager passes;
274   passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
275 
276   PassManagerBuilder PMB;
277   PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
278   PMB.Inliner = createFunctionInliningPass();
279   PMB.ExportSummary = ExportSummary;
280   PMB.ImportSummary = ImportSummary;
281   // Unconditionally verify input since it is not verified before this
282   // point and has unknown origin.
283   PMB.VerifyInput = true;
284   PMB.VerifyOutput = !Conf.DisableVerify;
285   PMB.LoopVectorize = true;
286   PMB.SLPVectorize = true;
287   PMB.OptLevel = Conf.OptLevel;
288   PMB.PGOSampleUse = Conf.SampleProfile;
289   PMB.EnablePGOCSInstrGen = Conf.RunCSIRInstr;
290   if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
291     PMB.EnablePGOCSInstrUse = true;
292     PMB.PGOInstrUse = Conf.CSIRProfile;
293   }
294   if (IsThinLTO)
295     PMB.populateThinLTOPassManager(passes);
296   else
297     PMB.populateLTOPassManager(passes);
298   passes.run(Mod);
299 }
300 
301 bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
302          bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
303          const ModuleSummaryIndex *ImportSummary) {
304   // FIXME: Plumb the combined index into the new pass manager.
305   if (!Conf.OptPipeline.empty())
306     runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
307                          Conf.DisableVerify);
308   else if (Conf.UseNewPM)
309     runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
310                    ImportSummary);
311   else
312     runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
313   return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
314 }
315 
316 static cl::opt<bool> EmbedBitcode(
317     "lto-embed-bitcode", cl::init(false),
318     cl::desc("Embed LLVM bitcode in object files produced by LTO"));
319 
320 static void EmitBitcodeSection(Module &M, Config &Conf) {
321   if (!EmbedBitcode)
322     return;
323   SmallVector<char, 0> Buffer;
324   raw_svector_ostream OS(Buffer);
325   WriteBitcodeToFile(M, OS);
326 
327   std::unique_ptr<MemoryBuffer> Buf(
328       new SmallVectorMemoryBuffer(std::move(Buffer)));
329   llvm::EmbedBitcodeInModule(M, Buf->getMemBufferRef(), /*EmbedBitcode*/ true,
330                              /*EmbedMarker*/ false, /*CmdArgs*/ nullptr);
331 }
332 
333 void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
334              unsigned Task, Module &Mod) {
335   if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
336     return;
337 
338   EmitBitcodeSection(Mod, Conf);
339 
340   std::unique_ptr<ToolOutputFile> DwoOut;
341   SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
342   if (!Conf.DwoDir.empty()) {
343     std::error_code EC;
344     if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
345       report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
346                          EC.message());
347 
348     DwoFile = Conf.DwoDir;
349     sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
350     TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
351   } else
352     TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
353 
354   if (!DwoFile.empty()) {
355     std::error_code EC;
356     DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
357     if (EC)
358       report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
359   }
360 
361   auto Stream = AddStream(Task);
362   legacy::PassManager CodeGenPasses;
363   if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
364                               DwoOut ? &DwoOut->os() : nullptr,
365                               Conf.CGFileType))
366     report_fatal_error("Failed to setup codegen");
367   CodeGenPasses.run(Mod);
368 
369   if (DwoOut)
370     DwoOut->keep();
371 }
372 
373 void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
374                   unsigned ParallelCodeGenParallelismLevel,
375                   std::unique_ptr<Module> Mod) {
376   ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
377   unsigned ThreadCount = 0;
378   const Target *T = &TM->getTarget();
379 
380   SplitModule(
381       std::move(Mod), ParallelCodeGenParallelismLevel,
382       [&](std::unique_ptr<Module> MPart) {
383         // We want to clone the module in a new context to multi-thread the
384         // codegen. We do it by serializing partition modules to bitcode
385         // (while still on the main thread, in order to avoid data races) and
386         // spinning up new threads which deserialize the partitions into
387         // separate contexts.
388         // FIXME: Provide a more direct way to do this in LLVM.
389         SmallString<0> BC;
390         raw_svector_ostream BCOS(BC);
391         WriteBitcodeToFile(*MPart, BCOS);
392 
393         // Enqueue the task
394         CodegenThreadPool.async(
395             [&](const SmallString<0> &BC, unsigned ThreadId) {
396               LTOLLVMContext Ctx(C);
397               Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
398                   MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
399                   Ctx);
400               if (!MOrErr)
401                 report_fatal_error("Failed to read bitcode");
402               std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
403 
404               std::unique_ptr<TargetMachine> TM =
405                   createTargetMachine(C, T, *MPartInCtx);
406 
407               codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
408             },
409             // Pass BC using std::move to ensure that it get moved rather than
410             // copied into the thread's context.
411             std::move(BC), ThreadCount++);
412       },
413       false);
414 
415   // Because the inner lambda (which runs in a worker thread) captures our local
416   // variables, we need to wait for the worker threads to terminate before we
417   // can leave the function scope.
418   CodegenThreadPool.wait();
419 }
420 
421 Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
422   if (!C.OverrideTriple.empty())
423     Mod.setTargetTriple(C.OverrideTriple);
424   else if (Mod.getTargetTriple().empty())
425     Mod.setTargetTriple(C.DefaultTriple);
426 
427   std::string Msg;
428   const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
429   if (!T)
430     return make_error<StringError>(Msg, inconvertibleErrorCode());
431   return T;
432 }
433 
434 }
435 
436 static Error
437 finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
438   // Make sure we flush the diagnostic remarks file in case the linker doesn't
439   // call the global destructors before exiting.
440   if (!DiagOutputFile)
441     return Error::success();
442   DiagOutputFile->keep();
443   DiagOutputFile->os().flush();
444   return Error::success();
445 }
446 
447 Error lto::backend(Config &C, AddStreamFn AddStream,
448                    unsigned ParallelCodeGenParallelismLevel,
449                    std::unique_ptr<Module> Mod,
450                    ModuleSummaryIndex &CombinedIndex) {
451   Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
452   if (!TOrErr)
453     return TOrErr.takeError();
454 
455   std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
456 
457   // Setup optimization remarks.
458   auto DiagFileOrErr = lto::setupOptimizationRemarks(
459       Mod->getContext(), C.RemarksFilename, C.RemarksPasses, C.RemarksFormat,
460       C.RemarksWithHotness);
461   if (!DiagFileOrErr)
462     return DiagFileOrErr.takeError();
463   auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
464 
465   if (!C.CodeGenOnly) {
466     if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
467              /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
468       return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
469   }
470 
471   if (ParallelCodeGenParallelismLevel == 1) {
472     codegen(C, TM.get(), AddStream, 0, *Mod);
473   } else {
474     splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
475                  std::move(Mod));
476   }
477   return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
478 }
479 
480 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
481                             const ModuleSummaryIndex &Index) {
482   std::vector<GlobalValue*> DeadGVs;
483   for (auto &GV : Mod.global_values())
484     if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
485       if (!Index.isGlobalValueLive(GVS)) {
486         DeadGVs.push_back(&GV);
487         convertToDeclaration(GV);
488       }
489 
490   // Now that all dead bodies have been dropped, delete the actual objects
491   // themselves when possible.
492   for (GlobalValue *GV : DeadGVs) {
493     GV->removeDeadConstantUsers();
494     // Might reference something defined in native object (i.e. dropped a
495     // non-prevailing IR def, but we need to keep the declaration).
496     if (GV->use_empty())
497       GV->eraseFromParent();
498   }
499 }
500 
501 Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
502                        Module &Mod, const ModuleSummaryIndex &CombinedIndex,
503                        const FunctionImporter::ImportMapTy &ImportList,
504                        const GVSummaryMapTy &DefinedGlobals,
505                        MapVector<StringRef, BitcodeModule> &ModuleMap) {
506   Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
507   if (!TOrErr)
508     return TOrErr.takeError();
509 
510   std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
511 
512   // Setup optimization remarks.
513   auto DiagFileOrErr = lto::setupOptimizationRemarks(
514       Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
515       Conf.RemarksFormat, Conf.RemarksWithHotness, Task);
516   if (!DiagFileOrErr)
517     return DiagFileOrErr.takeError();
518   auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
519 
520   if (Conf.CodeGenOnly) {
521     codegen(Conf, TM.get(), AddStream, Task, Mod);
522     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
523   }
524 
525   if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
526     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
527 
528   renameModuleForThinLTO(Mod, CombinedIndex);
529 
530   dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
531 
532   thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
533 
534   if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
535     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
536 
537   if (!DefinedGlobals.empty())
538     thinLTOInternalizeModule(Mod, DefinedGlobals);
539 
540   if (Conf.PostInternalizeModuleHook &&
541       !Conf.PostInternalizeModuleHook(Task, Mod))
542     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
543 
544   auto ModuleLoader = [&](StringRef Identifier) {
545     assert(Mod.getContext().isODRUniquingDebugTypes() &&
546            "ODR Type uniquing should be enabled on the context");
547     auto I = ModuleMap.find(Identifier);
548     assert(I != ModuleMap.end());
549     return I->second.getLazyModule(Mod.getContext(),
550                                    /*ShouldLazyLoadMetadata=*/true,
551                                    /*IsImporting*/ true);
552   };
553 
554   FunctionImporter Importer(CombinedIndex, ModuleLoader);
555   if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
556     return Err;
557 
558   if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
559     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
560 
561   if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
562            /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
563     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
564 
565   codegen(Conf, TM.get(), AddStream, Task, Mod);
566   return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
567 }
568