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