1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
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 #include "clang/CodeGen/BackendUtil.h"
10 #include "clang/Basic/CodeGenOptions.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/FrontendDiagnostic.h"
15 #include "clang/Frontend/Utils.h"
16 #include "clang/Lex/HeaderSearchOptions.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/StackSafetyAnalysis.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/Bitcode/BitcodeWriter.h"
26 #include "llvm/Bitcode/BitcodeWriterPass.h"
27 #include "llvm/CodeGen/RegAllocRegistry.h"
28 #include "llvm/CodeGen/SchedulerRegistry.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/IRPrintingPasses.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ModuleSummaryIndex.h"
35 #include "llvm/IR/PassManager.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/LTO/LTOBackend.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Passes/PassBuilder.h"
41 #include "llvm/Passes/PassPlugin.h"
42 #include "llvm/Passes/StandardInstrumentations.h"
43 #include "llvm/Support/BuryPointer.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/PrettyStackTrace.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TimeProfiler.h"
49 #include "llvm/Support/Timer.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Transforms/Coroutines.h"
55 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
56 #include "llvm/Transforms/Coroutines/CoroEarly.h"
57 #include "llvm/Transforms/Coroutines/CoroElide.h"
58 #include "llvm/Transforms/Coroutines/CoroSplit.h"
59 #include "llvm/Transforms/IPO.h"
60 #include "llvm/Transforms/IPO/AlwaysInliner.h"
61 #include "llvm/Transforms/IPO/LowerTypeTests.h"
62 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
63 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
64 #include "llvm/Transforms/InstCombine/InstCombine.h"
65 #include "llvm/Transforms/Instrumentation.h"
66 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
67 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
68 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
69 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
70 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
71 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
72 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
73 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
74 #include "llvm/Transforms/ObjCARC.h"
75 #include "llvm/Transforms/Scalar.h"
76 #include "llvm/Transforms/Scalar/GVN.h"
77 #include "llvm/Transforms/Utils.h"
78 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
79 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
80 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
81 #include "llvm/Transforms/Utils/SymbolRewriter.h"
82 #include "llvm/Transforms/Utils/UniqueInternalLinkageNames.h"
83 #include <memory>
84 using namespace clang;
85 using namespace llvm;
86 
87 #define HANDLE_EXTENSION(Ext)                                                  \
88   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
89 #include "llvm/Support/Extension.def"
90 
91 namespace {
92 
93 // Default filename used for profile generation.
94 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
95 
96 class EmitAssemblyHelper {
97   DiagnosticsEngine &Diags;
98   const HeaderSearchOptions &HSOpts;
99   const CodeGenOptions &CodeGenOpts;
100   const clang::TargetOptions &TargetOpts;
101   const LangOptions &LangOpts;
102   Module *TheModule;
103 
104   Timer CodeGenerationTime;
105 
106   std::unique_ptr<raw_pwrite_stream> OS;
107 
108   TargetIRAnalysis getTargetIRAnalysis() const {
109     if (TM)
110       return TM->getTargetIRAnalysis();
111 
112     return TargetIRAnalysis();
113   }
114 
115   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
116 
117   /// Generates the TargetMachine.
118   /// Leaves TM unchanged if it is unable to create the target machine.
119   /// Some of our clang tests specify triples which are not built
120   /// into clang. This is okay because these tests check the generated
121   /// IR, and they require DataLayout which depends on the triple.
122   /// In this case, we allow this method to fail and not report an error.
123   /// When MustCreateTM is used, we print an error if we are unable to load
124   /// the requested target.
125   void CreateTargetMachine(bool MustCreateTM);
126 
127   /// Add passes necessary to emit assembly or LLVM IR.
128   ///
129   /// \return True on success.
130   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
131                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
132 
133   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
134     std::error_code EC;
135     auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
136                                                      llvm::sys::fs::OF_None);
137     if (EC) {
138       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
139       F.reset();
140     }
141     return F;
142   }
143 
144 public:
145   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
146                      const HeaderSearchOptions &HeaderSearchOpts,
147                      const CodeGenOptions &CGOpts,
148                      const clang::TargetOptions &TOpts,
149                      const LangOptions &LOpts, Module *M)
150       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
151         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
152         CodeGenerationTime("codegen", "Code Generation Time") {}
153 
154   ~EmitAssemblyHelper() {
155     if (CodeGenOpts.DisableFree)
156       BuryPointer(std::move(TM));
157   }
158 
159   std::unique_ptr<TargetMachine> TM;
160 
161   void EmitAssembly(BackendAction Action,
162                     std::unique_ptr<raw_pwrite_stream> OS);
163 
164   void EmitAssemblyWithNewPassManager(BackendAction Action,
165                                       std::unique_ptr<raw_pwrite_stream> OS);
166 };
167 
168 // We need this wrapper to access LangOpts and CGOpts from extension functions
169 // that we add to the PassManagerBuilder.
170 class PassManagerBuilderWrapper : public PassManagerBuilder {
171 public:
172   PassManagerBuilderWrapper(const Triple &TargetTriple,
173                             const CodeGenOptions &CGOpts,
174                             const LangOptions &LangOpts)
175       : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
176         LangOpts(LangOpts) {}
177   const Triple &getTargetTriple() const { return TargetTriple; }
178   const CodeGenOptions &getCGOpts() const { return CGOpts; }
179   const LangOptions &getLangOpts() const { return LangOpts; }
180 
181 private:
182   const Triple &TargetTriple;
183   const CodeGenOptions &CGOpts;
184   const LangOptions &LangOpts;
185 };
186 }
187 
188 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
189   if (Builder.OptLevel > 0)
190     PM.add(createObjCARCAPElimPass());
191 }
192 
193 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
194   if (Builder.OptLevel > 0)
195     PM.add(createObjCARCExpandPass());
196 }
197 
198 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
199   if (Builder.OptLevel > 0)
200     PM.add(createObjCARCOptPass());
201 }
202 
203 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
204                                      legacy::PassManagerBase &PM) {
205   PM.add(createAddDiscriminatorsPass());
206 }
207 
208 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
209                                   legacy::PassManagerBase &PM) {
210   PM.add(createBoundsCheckingLegacyPass());
211 }
212 
213 static SanitizerCoverageOptions
214 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
215   SanitizerCoverageOptions Opts;
216   Opts.CoverageType =
217       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
218   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
219   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
220   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
221   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
222   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
223   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
224   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
225   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
226   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
227   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
228   Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
229   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
230   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
231   return Opts;
232 }
233 
234 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
235                                      legacy::PassManagerBase &PM) {
236   const PassManagerBuilderWrapper &BuilderWrapper =
237       static_cast<const PassManagerBuilderWrapper &>(Builder);
238   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
239   auto Opts = getSancovOptsFromCGOpts(CGOpts);
240   PM.add(createModuleSanitizerCoverageLegacyPassPass(
241       Opts, CGOpts.SanitizeCoverageWhitelistFiles,
242       CGOpts.SanitizeCoverageBlacklistFiles));
243 }
244 
245 // Check if ASan should use GC-friendly instrumentation for globals.
246 // First of all, there is no point if -fdata-sections is off (expect for MachO,
247 // where this is not a factor). Also, on ELF this feature requires an assembler
248 // extension that only works with -integrated-as at the moment.
249 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
250   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
251     return false;
252   switch (T.getObjectFormat()) {
253   case Triple::MachO:
254   case Triple::COFF:
255     return true;
256   case Triple::ELF:
257     return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
258   case Triple::XCOFF:
259     llvm::report_fatal_error("ASan not implemented for XCOFF.");
260   case Triple::Wasm:
261   case Triple::UnknownObjectFormat:
262     break;
263   }
264   return false;
265 }
266 
267 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
268                                       legacy::PassManagerBase &PM) {
269   const PassManagerBuilderWrapper &BuilderWrapper =
270       static_cast<const PassManagerBuilderWrapper&>(Builder);
271   const Triple &T = BuilderWrapper.getTargetTriple();
272   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
273   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
274   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
275   bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
276   bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
277   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
278                                             UseAfterScope));
279   PM.add(createModuleAddressSanitizerLegacyPassPass(
280       /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
281 }
282 
283 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
284                                             legacy::PassManagerBase &PM) {
285   PM.add(createAddressSanitizerFunctionPass(
286       /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
287   PM.add(createModuleAddressSanitizerLegacyPassPass(
288       /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
289       /*UseOdrIndicator*/ false));
290 }
291 
292 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
293                                             legacy::PassManagerBase &PM) {
294   const PassManagerBuilderWrapper &BuilderWrapper =
295       static_cast<const PassManagerBuilderWrapper &>(Builder);
296   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
297   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
298   PM.add(
299       createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
300 }
301 
302 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
303                                             legacy::PassManagerBase &PM) {
304   PM.add(createHWAddressSanitizerLegacyPassPass(
305       /*CompileKernel*/ true, /*Recover*/ true));
306 }
307 
308 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
309                                              legacy::PassManagerBase &PM,
310                                              bool CompileKernel) {
311   const PassManagerBuilderWrapper &BuilderWrapper =
312       static_cast<const PassManagerBuilderWrapper&>(Builder);
313   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
314   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
315   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
316   PM.add(createMemorySanitizerLegacyPassPass(
317       MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
318 
319   // MemorySanitizer inserts complex instrumentation that mostly follows
320   // the logic of the original code, but operates on "shadow" values.
321   // It can benefit from re-running some general purpose optimization passes.
322   if (Builder.OptLevel > 0) {
323     PM.add(createEarlyCSEPass());
324     PM.add(createReassociatePass());
325     PM.add(createLICMPass());
326     PM.add(createGVNPass());
327     PM.add(createInstructionCombiningPass());
328     PM.add(createDeadStoreEliminationPass());
329   }
330 }
331 
332 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
333                                    legacy::PassManagerBase &PM) {
334   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
335 }
336 
337 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
338                                          legacy::PassManagerBase &PM) {
339   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
340 }
341 
342 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
343                                    legacy::PassManagerBase &PM) {
344   PM.add(createThreadSanitizerLegacyPassPass());
345 }
346 
347 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
348                                      legacy::PassManagerBase &PM) {
349   const PassManagerBuilderWrapper &BuilderWrapper =
350       static_cast<const PassManagerBuilderWrapper&>(Builder);
351   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
352   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
353 }
354 
355 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
356                                          const CodeGenOptions &CodeGenOpts) {
357   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
358 
359   switch (CodeGenOpts.getVecLib()) {
360   case CodeGenOptions::Accelerate:
361     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
362     break;
363   case CodeGenOptions::MASSV:
364     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
365     break;
366   case CodeGenOptions::SVML:
367     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
368     break;
369   default:
370     break;
371   }
372   return TLII;
373 }
374 
375 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
376                                   legacy::PassManager *MPM) {
377   llvm::SymbolRewriter::RewriteDescriptorList DL;
378 
379   llvm::SymbolRewriter::RewriteMapParser MapParser;
380   for (const auto &MapFile : Opts.RewriteMapFiles)
381     MapParser.parse(MapFile, &DL);
382 
383   MPM->add(createRewriteSymbolsPass(DL));
384 }
385 
386 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
387   switch (CodeGenOpts.OptimizationLevel) {
388   default:
389     llvm_unreachable("Invalid optimization level!");
390   case 0:
391     return CodeGenOpt::None;
392   case 1:
393     return CodeGenOpt::Less;
394   case 2:
395     return CodeGenOpt::Default; // O2/Os/Oz
396   case 3:
397     return CodeGenOpt::Aggressive;
398   }
399 }
400 
401 static Optional<llvm::CodeModel::Model>
402 getCodeModel(const CodeGenOptions &CodeGenOpts) {
403   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
404                            .Case("tiny", llvm::CodeModel::Tiny)
405                            .Case("small", llvm::CodeModel::Small)
406                            .Case("kernel", llvm::CodeModel::Kernel)
407                            .Case("medium", llvm::CodeModel::Medium)
408                            .Case("large", llvm::CodeModel::Large)
409                            .Case("default", ~1u)
410                            .Default(~0u);
411   assert(CodeModel != ~0u && "invalid code model!");
412   if (CodeModel == ~1u)
413     return None;
414   return static_cast<llvm::CodeModel::Model>(CodeModel);
415 }
416 
417 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
418   if (Action == Backend_EmitObj)
419     return CGFT_ObjectFile;
420   else if (Action == Backend_EmitMCNull)
421     return CGFT_Null;
422   else {
423     assert(Action == Backend_EmitAssembly && "Invalid action!");
424     return CGFT_AssemblyFile;
425   }
426 }
427 
428 static void initTargetOptions(DiagnosticsEngine &Diags,
429                               llvm::TargetOptions &Options,
430                               const CodeGenOptions &CodeGenOpts,
431                               const clang::TargetOptions &TargetOpts,
432                               const LangOptions &LangOpts,
433                               const HeaderSearchOptions &HSOpts) {
434   Options.ThreadModel =
435       llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
436           .Case("posix", llvm::ThreadModel::POSIX)
437           .Case("single", llvm::ThreadModel::Single);
438 
439   // Set float ABI type.
440   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
441           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
442          "Invalid Floating Point ABI!");
443   Options.FloatABIType =
444       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
445           .Case("soft", llvm::FloatABI::Soft)
446           .Case("softfp", llvm::FloatABI::Soft)
447           .Case("hard", llvm::FloatABI::Hard)
448           .Default(llvm::FloatABI::Default);
449 
450   // Set FP fusion mode.
451   switch (LangOpts.getDefaultFPContractMode()) {
452   case LangOptions::FPM_Off:
453     // Preserve any contraction performed by the front-end.  (Strict performs
454     // splitting of the muladd intrinsic in the backend.)
455     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
456     break;
457   case LangOptions::FPM_On:
458     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
459     break;
460   case LangOptions::FPM_Fast:
461     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
462     break;
463   }
464 
465   Options.UseInitArray = CodeGenOpts.UseInitArray;
466   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
467   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
468   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
469 
470   // Set EABI version.
471   Options.EABIVersion = TargetOpts.EABIVersion;
472 
473   if (LangOpts.SjLjExceptions)
474     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
475   if (LangOpts.SEHExceptions)
476     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
477   if (LangOpts.DWARFExceptions)
478     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
479   if (LangOpts.WasmExceptions)
480     Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
481 
482   Options.NoInfsFPMath = LangOpts.NoHonorInfs;
483   Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
484   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
485   Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
486   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
487 
488   Options.BBSections =
489       llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
490           .Case("all", llvm::BasicBlockSection::All)
491           .Case("labels", llvm::BasicBlockSection::Labels)
492           .StartsWith("list=", llvm::BasicBlockSection::List)
493           .Case("none", llvm::BasicBlockSection::None)
494           .Default(llvm::BasicBlockSection::None);
495 
496   if (Options.BBSections == llvm::BasicBlockSection::List) {
497     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
498         MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
499     if (!MBOrErr)
500       Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
501           << MBOrErr.getError().message();
502     else
503       Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
504   }
505 
506   Options.FunctionSections = CodeGenOpts.FunctionSections;
507   Options.DataSections = CodeGenOpts.DataSections;
508   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
509   Options.UniqueBasicBlockSectionNames =
510       CodeGenOpts.UniqueBasicBlockSectionNames;
511   Options.TLSSize = CodeGenOpts.TLSSize;
512   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
513   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
514   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
515   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
516   Options.EmitAddrsig = CodeGenOpts.Addrsig;
517   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
518   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
519 
520   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
521   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
522   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
523   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
524   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
525   Options.MCOptions.MCIncrementalLinkerCompatible =
526       CodeGenOpts.IncrementalLinkerCompatible;
527   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
528   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
529   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
530   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
531   Options.MCOptions.ABIName = TargetOpts.ABI;
532   for (const auto &Entry : HSOpts.UserEntries)
533     if (!Entry.IsFramework &&
534         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
535          Entry.Group == frontend::IncludeDirGroup::Angled ||
536          Entry.Group == frontend::IncludeDirGroup::System))
537       Options.MCOptions.IASSearchPaths.push_back(
538           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
539 }
540 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
541   if (CodeGenOpts.DisableGCov)
542     return None;
543   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
544     return None;
545   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
546   // LLVM's -default-gcov-version flag is set to something invalid.
547   GCOVOptions Options;
548   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
549   Options.EmitData = CodeGenOpts.EmitGcovArcs;
550   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
551   Options.NoRedZone = CodeGenOpts.DisableRedZone;
552   Options.Filter = CodeGenOpts.ProfileFilterFiles;
553   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
554   return Options;
555 }
556 
557 static Optional<InstrProfOptions>
558 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
559                     const LangOptions &LangOpts) {
560   if (!CodeGenOpts.hasProfileClangInstr())
561     return None;
562   InstrProfOptions Options;
563   Options.NoRedZone = CodeGenOpts.DisableRedZone;
564   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
565 
566   // TODO: Surface the option to emit atomic profile counter increments at
567   // the driver level.
568   Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
569   return Options;
570 }
571 
572 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
573                                       legacy::FunctionPassManager &FPM) {
574   // Handle disabling of all LLVM passes, where we want to preserve the
575   // internal module before any optimization.
576   if (CodeGenOpts.DisableLLVMPasses)
577     return;
578 
579   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
580   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
581   // are inserted before PMBuilder ones - they'd get the default-constructed
582   // TLI with an unknown target otherwise.
583   Triple TargetTriple(TheModule->getTargetTriple());
584   std::unique_ptr<TargetLibraryInfoImpl> TLII(
585       createTLII(TargetTriple, CodeGenOpts));
586 
587   // If we reached here with a non-empty index file name, then the index file
588   // was empty and we are not performing ThinLTO backend compilation (used in
589   // testing in a distributed build environment). Drop any the type test
590   // assume sequences inserted for whole program vtables so that codegen doesn't
591   // complain.
592   if (!CodeGenOpts.ThinLTOIndexFile.empty())
593     MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
594                                      /*ImportSummary=*/nullptr,
595                                      /*DropTypeTests=*/true));
596 
597   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
598 
599   // At O0 and O1 we only run the always inliner which is more efficient. At
600   // higher optimization levels we run the normal inliner.
601   if (CodeGenOpts.OptimizationLevel <= 1) {
602     bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
603                                       !CodeGenOpts.DisableLifetimeMarkers) ||
604                                      LangOpts.Coroutines);
605     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
606   } else {
607     // We do not want to inline hot callsites for SamplePGO module-summary build
608     // because profile annotation will happen again in ThinLTO backend, and we
609     // want the IR of the hot path to match the profile.
610     PMBuilder.Inliner = createFunctionInliningPass(
611         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
612         (!CodeGenOpts.SampleProfileFile.empty() &&
613          CodeGenOpts.PrepareForThinLTO));
614   }
615 
616   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
617   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
618   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
619   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
620 
621   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
622   // Loop interleaving in the loop vectorizer has historically been set to be
623   // enabled when loop unrolling is enabled.
624   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
625   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
626   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
627   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
628   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
629 
630   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
631 
632   if (TM)
633     TM->adjustPassManager(PMBuilder);
634 
635   if (CodeGenOpts.DebugInfoForProfiling ||
636       !CodeGenOpts.SampleProfileFile.empty())
637     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
638                            addAddDiscriminatorsPass);
639 
640   // In ObjC ARC mode, add the main ARC optimization passes.
641   if (LangOpts.ObjCAutoRefCount) {
642     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
643                            addObjCARCExpandPass);
644     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
645                            addObjCARCAPElimPass);
646     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
647                            addObjCARCOptPass);
648   }
649 
650   if (LangOpts.Coroutines)
651     addCoroutinePassesToExtensionPoints(PMBuilder);
652 
653   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
654     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
655                            addBoundsCheckingPass);
656     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
657                            addBoundsCheckingPass);
658   }
659 
660   if (CodeGenOpts.SanitizeCoverageType ||
661       CodeGenOpts.SanitizeCoverageIndirectCalls ||
662       CodeGenOpts.SanitizeCoverageTraceCmp) {
663     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
664                            addSanitizerCoveragePass);
665     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
666                            addSanitizerCoveragePass);
667   }
668 
669   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
670     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
671                            addAddressSanitizerPasses);
672     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
673                            addAddressSanitizerPasses);
674   }
675 
676   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
677     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
678                            addKernelAddressSanitizerPasses);
679     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
680                            addKernelAddressSanitizerPasses);
681   }
682 
683   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
684     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
685                            addHWAddressSanitizerPasses);
686     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
687                            addHWAddressSanitizerPasses);
688   }
689 
690   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
691     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
692                            addKernelHWAddressSanitizerPasses);
693     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
694                            addKernelHWAddressSanitizerPasses);
695   }
696 
697   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
698     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
699                            addMemorySanitizerPass);
700     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
701                            addMemorySanitizerPass);
702   }
703 
704   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
705     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
706                            addKernelMemorySanitizerPass);
707     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
708                            addKernelMemorySanitizerPass);
709   }
710 
711   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
712     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
713                            addThreadSanitizerPass);
714     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
715                            addThreadSanitizerPass);
716   }
717 
718   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
719     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
720                            addDataFlowSanitizerPass);
721     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
722                            addDataFlowSanitizerPass);
723   }
724 
725   // Set up the per-function pass manager.
726   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
727   if (CodeGenOpts.VerifyModule)
728     FPM.add(createVerifierPass());
729 
730   // Set up the per-module pass manager.
731   if (!CodeGenOpts.RewriteMapFiles.empty())
732     addSymbolRewriterPass(CodeGenOpts, &MPM);
733 
734   // Add UniqueInternalLinkageNames Pass which renames internal linkage symbols
735   // with unique names.
736   if (CodeGenOpts.UniqueInternalLinkageNames) {
737     MPM.add(createUniqueInternalLinkageNamesPass());
738   }
739 
740   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
741     MPM.add(createGCOVProfilerPass(*Options));
742     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
743       MPM.add(createStripSymbolsPass(true));
744   }
745 
746   if (Optional<InstrProfOptions> Options =
747           getInstrProfOptions(CodeGenOpts, LangOpts))
748     MPM.add(createInstrProfilingLegacyPass(*Options, false));
749 
750   bool hasIRInstr = false;
751   if (CodeGenOpts.hasProfileIRInstr()) {
752     PMBuilder.EnablePGOInstrGen = true;
753     hasIRInstr = true;
754   }
755   if (CodeGenOpts.hasProfileCSIRInstr()) {
756     assert(!CodeGenOpts.hasProfileCSIRUse() &&
757            "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
758            "same time");
759     assert(!hasIRInstr &&
760            "Cannot have both ProfileGen pass and CSProfileGen pass at the "
761            "same time");
762     PMBuilder.EnablePGOCSInstrGen = true;
763     hasIRInstr = true;
764   }
765   if (hasIRInstr) {
766     if (!CodeGenOpts.InstrProfileOutput.empty())
767       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
768     else
769       PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
770   }
771   if (CodeGenOpts.hasProfileIRUse()) {
772     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
773     PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
774   }
775 
776   if (!CodeGenOpts.SampleProfileFile.empty())
777     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
778 
779   PMBuilder.populateFunctionPassManager(FPM);
780   PMBuilder.populateModulePassManager(MPM);
781 }
782 
783 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
784   SmallVector<const char *, 16> BackendArgs;
785   BackendArgs.push_back("clang"); // Fake program name.
786   if (!CodeGenOpts.DebugPass.empty()) {
787     BackendArgs.push_back("-debug-pass");
788     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
789   }
790   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
791     BackendArgs.push_back("-limit-float-precision");
792     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
793   }
794   BackendArgs.push_back(nullptr);
795   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
796                                     BackendArgs.data());
797 }
798 
799 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
800   // Create the TargetMachine for generating code.
801   std::string Error;
802   std::string Triple = TheModule->getTargetTriple();
803   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
804   if (!TheTarget) {
805     if (MustCreateTM)
806       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
807     return;
808   }
809 
810   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
811   std::string FeaturesStr =
812       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
813   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
814   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
815 
816   llvm::TargetOptions Options;
817   initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
818   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
819                                           Options, RM, CM, OptLevel));
820 }
821 
822 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
823                                        BackendAction Action,
824                                        raw_pwrite_stream &OS,
825                                        raw_pwrite_stream *DwoOS) {
826   // Add LibraryInfo.
827   llvm::Triple TargetTriple(TheModule->getTargetTriple());
828   std::unique_ptr<TargetLibraryInfoImpl> TLII(
829       createTLII(TargetTriple, CodeGenOpts));
830   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
831 
832   // Normal mode, emit a .s or .o file by running the code generator. Note,
833   // this also adds codegenerator level optimization passes.
834   CodeGenFileType CGFT = getCodeGenFileType(Action);
835 
836   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
837   // "codegen" passes so that it isn't run multiple times when there is
838   // inlining happening.
839   if (CodeGenOpts.OptimizationLevel > 0)
840     CodeGenPasses.add(createObjCARCContractPass());
841 
842   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
843                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
844     Diags.Report(diag::err_fe_unable_to_interface_with_target);
845     return false;
846   }
847 
848   return true;
849 }
850 
851 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
852                                       std::unique_ptr<raw_pwrite_stream> OS) {
853   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
854 
855   setCommandLineOpts(CodeGenOpts);
856 
857   bool UsesCodeGen = (Action != Backend_EmitNothing &&
858                       Action != Backend_EmitBC &&
859                       Action != Backend_EmitLL);
860   CreateTargetMachine(UsesCodeGen);
861 
862   if (UsesCodeGen && !TM)
863     return;
864   if (TM)
865     TheModule->setDataLayout(TM->createDataLayout());
866 
867   legacy::PassManager PerModulePasses;
868   PerModulePasses.add(
869       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
870 
871   legacy::FunctionPassManager PerFunctionPasses(TheModule);
872   PerFunctionPasses.add(
873       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
874 
875   CreatePasses(PerModulePasses, PerFunctionPasses);
876 
877   legacy::PassManager CodeGenPasses;
878   CodeGenPasses.add(
879       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
880 
881   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
882 
883   switch (Action) {
884   case Backend_EmitNothing:
885     break;
886 
887   case Backend_EmitBC:
888     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
889       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
890         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
891         if (!ThinLinkOS)
892           return;
893       }
894       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
895                                CodeGenOpts.EnableSplitLTOUnit);
896       PerModulePasses.add(createWriteThinLTOBitcodePass(
897           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
898     } else {
899       // Emit a module summary by default for Regular LTO except for ld64
900       // targets
901       bool EmitLTOSummary =
902           (CodeGenOpts.PrepareForLTO &&
903            !CodeGenOpts.DisableLLVMPasses &&
904            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
905                llvm::Triple::Apple);
906       if (EmitLTOSummary) {
907         if (!TheModule->getModuleFlag("ThinLTO"))
908           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
909         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
910                                  uint32_t(1));
911       }
912 
913       PerModulePasses.add(createBitcodeWriterPass(
914           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
915     }
916     break;
917 
918   case Backend_EmitLL:
919     PerModulePasses.add(
920         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
921     break;
922 
923   default:
924     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
925       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
926       if (!DwoOS)
927         return;
928     }
929     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
930                        DwoOS ? &DwoOS->os() : nullptr))
931       return;
932   }
933 
934   // Before executing passes, print the final values of the LLVM options.
935   cl::PrintOptionValues();
936 
937   // Run passes. For now we do all passes at once, but eventually we
938   // would like to have the option of streaming code generation.
939 
940   {
941     PrettyStackTraceString CrashInfo("Per-function optimization");
942     llvm::TimeTraceScope TimeScope("PerFunctionPasses");
943 
944     PerFunctionPasses.doInitialization();
945     for (Function &F : *TheModule)
946       if (!F.isDeclaration())
947         PerFunctionPasses.run(F);
948     PerFunctionPasses.doFinalization();
949   }
950 
951   {
952     PrettyStackTraceString CrashInfo("Per-module optimization passes");
953     llvm::TimeTraceScope TimeScope("PerModulePasses");
954     PerModulePasses.run(*TheModule);
955   }
956 
957   {
958     PrettyStackTraceString CrashInfo("Code generation");
959     llvm::TimeTraceScope TimeScope("CodeGenPasses");
960     CodeGenPasses.run(*TheModule);
961   }
962 
963   if (ThinLinkOS)
964     ThinLinkOS->keep();
965   if (DwoOS)
966     DwoOS->keep();
967 }
968 
969 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
970   switch (Opts.OptimizationLevel) {
971   default:
972     llvm_unreachable("Invalid optimization level!");
973 
974   case 1:
975     return PassBuilder::OptimizationLevel::O1;
976 
977   case 2:
978     switch (Opts.OptimizeSize) {
979     default:
980       llvm_unreachable("Invalid optimization level for size!");
981 
982     case 0:
983       return PassBuilder::OptimizationLevel::O2;
984 
985     case 1:
986       return PassBuilder::OptimizationLevel::Os;
987 
988     case 2:
989       return PassBuilder::OptimizationLevel::Oz;
990     }
991 
992   case 3:
993     return PassBuilder::OptimizationLevel::O3;
994   }
995 }
996 
997 static void addCoroutinePassesAtO0(ModulePassManager &MPM,
998                                    const LangOptions &LangOpts,
999                                    const CodeGenOptions &CodeGenOpts) {
1000   if (!LangOpts.Coroutines)
1001     return;
1002 
1003   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
1004 
1005   CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager);
1006   CGPM.addPass(CoroSplitPass());
1007   CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
1008   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1009 
1010   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
1011 }
1012 
1013 static void addSanitizersAtO0(ModulePassManager &MPM,
1014                               const Triple &TargetTriple,
1015                               const LangOptions &LangOpts,
1016                               const CodeGenOptions &CodeGenOpts) {
1017   if (CodeGenOpts.SanitizeCoverageType ||
1018       CodeGenOpts.SanitizeCoverageIndirectCalls ||
1019       CodeGenOpts.SanitizeCoverageTraceCmp) {
1020     auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1021     MPM.addPass(ModuleSanitizerCoveragePass(
1022         SancovOpts, CodeGenOpts.SanitizeCoverageWhitelistFiles,
1023         CodeGenOpts.SanitizeCoverageBlacklistFiles));
1024   }
1025 
1026   auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1027     MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1028     bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1029     MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1030         CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
1031     bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1032     MPM.addPass(
1033         ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
1034                                    CodeGenOpts.SanitizeAddressUseOdrIndicator));
1035   };
1036 
1037   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1038     ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
1039   }
1040 
1041   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
1042     ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
1043   }
1044 
1045   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1046     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1047     int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1048     MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1049     MPM.addPass(createModuleToFunctionPassAdaptor(
1050         MemorySanitizerPass({TrackOrigins, Recover, false})));
1051   }
1052 
1053   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
1054     MPM.addPass(createModuleToFunctionPassAdaptor(
1055         MemorySanitizerPass({0, false, /*Kernel=*/true})));
1056   }
1057 
1058   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1059     MPM.addPass(ThreadSanitizerPass());
1060     MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1061   }
1062 }
1063 
1064 /// A clean version of `EmitAssembly` that uses the new pass manager.
1065 ///
1066 /// Not all features are currently supported in this system, but where
1067 /// necessary it falls back to the legacy pass manager to at least provide
1068 /// basic functionality.
1069 ///
1070 /// This API is planned to have its functionality finished and then to replace
1071 /// `EmitAssembly` at some point in the future when the default switches.
1072 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1073     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1074   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
1075   setCommandLineOpts(CodeGenOpts);
1076 
1077   bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1078                           Action != Backend_EmitBC &&
1079                           Action != Backend_EmitLL);
1080   CreateTargetMachine(RequiresCodeGen);
1081 
1082   if (RequiresCodeGen && !TM)
1083     return;
1084   if (TM)
1085     TheModule->setDataLayout(TM->createDataLayout());
1086 
1087   Optional<PGOOptions> PGOOpt;
1088 
1089   if (CodeGenOpts.hasProfileIRInstr())
1090     // -fprofile-generate.
1091     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1092                             ? std::string(DefaultProfileGenName)
1093                             : CodeGenOpts.InstrProfileOutput,
1094                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1095                         CodeGenOpts.DebugInfoForProfiling);
1096   else if (CodeGenOpts.hasProfileIRUse()) {
1097     // -fprofile-use.
1098     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1099                                                     : PGOOptions::NoCSAction;
1100     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1101                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1102                         CSAction, CodeGenOpts.DebugInfoForProfiling);
1103   } else if (!CodeGenOpts.SampleProfileFile.empty())
1104     // -fprofile-sample-use
1105     PGOOpt =
1106         PGOOptions(CodeGenOpts.SampleProfileFile, "",
1107                    CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1108                    PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
1109   else if (CodeGenOpts.DebugInfoForProfiling)
1110     // -fdebug-info-for-profiling
1111     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1112                         PGOOptions::NoCSAction, true);
1113 
1114   // Check to see if we want to generate a CS profile.
1115   if (CodeGenOpts.hasProfileCSIRInstr()) {
1116     assert(!CodeGenOpts.hasProfileCSIRUse() &&
1117            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1118            "the same time");
1119     if (PGOOpt.hasValue()) {
1120       assert(PGOOpt->Action != PGOOptions::IRInstr &&
1121              PGOOpt->Action != PGOOptions::SampleUse &&
1122              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1123              " pass");
1124       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1125                                      ? std::string(DefaultProfileGenName)
1126                                      : CodeGenOpts.InstrProfileOutput;
1127       PGOOpt->CSAction = PGOOptions::CSIRInstr;
1128     } else
1129       PGOOpt = PGOOptions("",
1130                           CodeGenOpts.InstrProfileOutput.empty()
1131                               ? std::string(DefaultProfileGenName)
1132                               : CodeGenOpts.InstrProfileOutput,
1133                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1134                           CodeGenOpts.DebugInfoForProfiling);
1135   }
1136 
1137   PipelineTuningOptions PTO;
1138   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1139   // For historical reasons, loop interleaving is set to mirror setting for loop
1140   // unrolling.
1141   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1142   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1143   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1144   PTO.CallGraphProfile = CodeGenOpts.CallGraphProfile;
1145   PTO.Coroutines = LangOpts.Coroutines;
1146 
1147   PassInstrumentationCallbacks PIC;
1148   StandardInstrumentations SI;
1149   SI.registerCallbacks(PIC);
1150   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1151 
1152   // Attempt to load pass plugins and register their callbacks with PB.
1153   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1154     auto PassPlugin = PassPlugin::Load(PluginFN);
1155     if (PassPlugin) {
1156       PassPlugin->registerPassBuilderCallbacks(PB);
1157     } else {
1158       Diags.Report(diag::err_fe_unable_to_load_plugin)
1159           << PluginFN << toString(PassPlugin.takeError());
1160     }
1161   }
1162 #define HANDLE_EXTENSION(Ext)                                                  \
1163   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1164 #include "llvm/Support/Extension.def"
1165 
1166   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1167   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1168   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1169   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1170 
1171   // Register the AA manager first so that our version is the one used.
1172   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1173 
1174   // Register the target library analysis directly and give it a customized
1175   // preset TLI.
1176   Triple TargetTriple(TheModule->getTargetTriple());
1177   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1178       createTLII(TargetTriple, CodeGenOpts));
1179   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1180 
1181   // Register all the basic analyses with the managers.
1182   PB.registerModuleAnalyses(MAM);
1183   PB.registerCGSCCAnalyses(CGAM);
1184   PB.registerFunctionAnalyses(FAM);
1185   PB.registerLoopAnalyses(LAM);
1186   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1187 
1188   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1189 
1190   if (!CodeGenOpts.DisableLLVMPasses) {
1191     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1192     bool IsLTO = CodeGenOpts.PrepareForLTO;
1193 
1194     if (CodeGenOpts.OptimizationLevel == 0) {
1195       // If we reached here with a non-empty index file name, then the index
1196       // file was empty and we are not performing ThinLTO backend compilation
1197       // (used in testing in a distributed build environment). Drop any the type
1198       // test assume sequences inserted for whole program vtables so that
1199       // codegen doesn't complain.
1200       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1201         MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1202                                        /*ImportSummary=*/nullptr,
1203                                        /*DropTypeTests=*/true));
1204       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1205         MPM.addPass(GCOVProfilerPass(*Options));
1206       if (Optional<InstrProfOptions> Options =
1207               getInstrProfOptions(CodeGenOpts, LangOpts))
1208         MPM.addPass(InstrProfiling(*Options, false));
1209 
1210       // Build a minimal pipeline based on the semantics required by Clang,
1211       // which is just that always inlining occurs. Further, disable generating
1212       // lifetime intrinsics to avoid enabling further optimizations during
1213       // code generation.
1214       // However, we need to insert lifetime intrinsics to avoid invalid access
1215       // caused by multithreaded coroutines.
1216       MPM.addPass(
1217           AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
1218 
1219       // At -O0, we can still do PGO. Add all the requested passes for
1220       // instrumentation PGO, if requested.
1221       if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1222                      PGOOpt->Action == PGOOptions::IRUse))
1223         PB.addPGOInstrPassesForO0(
1224             MPM, CodeGenOpts.DebugPassManager,
1225             /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1226             /* IsCS */ false, PGOOpt->ProfileFile,
1227             PGOOpt->ProfileRemappingFile);
1228 
1229       // At -O0 we directly run necessary sanitizer passes.
1230       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1231         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1232 
1233       // Add UniqueInternalLinkageNames Pass which renames internal linkage
1234       // symbols with unique names.
1235       if (CodeGenOpts.UniqueInternalLinkageNames) {
1236         MPM.addPass(UniqueInternalLinkageNamesPass());
1237       }
1238 
1239       // Lastly, add semantically necessary passes for LTO.
1240       if (IsLTO || IsThinLTO) {
1241         MPM.addPass(CanonicalizeAliasesPass());
1242         MPM.addPass(NameAnonGlobalPass());
1243       }
1244     } else {
1245       // Map our optimization levels into one of the distinct levels used to
1246       // configure the pipeline.
1247       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1248 
1249       // If we reached here with a non-empty index file name, then the index
1250       // file was empty and we are not performing ThinLTO backend compilation
1251       // (used in testing in a distributed build environment). Drop any the type
1252       // test assume sequences inserted for whole program vtables so that
1253       // codegen doesn't complain.
1254       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1255         PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1256           MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1257                                          /*ImportSummary=*/nullptr,
1258                                          /*DropTypeTests=*/true));
1259         });
1260 
1261       PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1262         MPM.addPass(createModuleToFunctionPassAdaptor(
1263             EntryExitInstrumenterPass(/*PostInlining=*/false)));
1264       });
1265 
1266       // Register callbacks to schedule sanitizer passes at the appropriate part of
1267       // the pipeline.
1268       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1269         PB.registerScalarOptimizerLateEPCallback(
1270             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1271               FPM.addPass(BoundsCheckingPass());
1272             });
1273 
1274       if (CodeGenOpts.SanitizeCoverageType ||
1275           CodeGenOpts.SanitizeCoverageIndirectCalls ||
1276           CodeGenOpts.SanitizeCoverageTraceCmp) {
1277         PB.registerOptimizerLastEPCallback(
1278             [this](ModulePassManager &MPM,
1279                    PassBuilder::OptimizationLevel Level) {
1280               auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1281               MPM.addPass(ModuleSanitizerCoveragePass(
1282                   SancovOpts, CodeGenOpts.SanitizeCoverageWhitelistFiles,
1283                   CodeGenOpts.SanitizeCoverageBlacklistFiles));
1284             });
1285       }
1286 
1287       if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1288         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1289         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1290         PB.registerOptimizerLastEPCallback(
1291             [TrackOrigins, Recover](ModulePassManager &MPM,
1292                                     PassBuilder::OptimizationLevel Level) {
1293               MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1294               MPM.addPass(createModuleToFunctionPassAdaptor(
1295                   MemorySanitizerPass({TrackOrigins, Recover, false})));
1296             });
1297       }
1298       if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1299         PB.registerOptimizerLastEPCallback(
1300             [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1301               MPM.addPass(ThreadSanitizerPass());
1302               MPM.addPass(
1303                   createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1304             });
1305       }
1306       if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1307         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1308         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1309         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1310         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1311         PB.registerOptimizerLastEPCallback(
1312             [Recover, UseAfterScope, ModuleUseAfterScope, UseOdrIndicator](
1313                 ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1314               MPM.addPass(
1315                   RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1316               MPM.addPass(ModuleAddressSanitizerPass(
1317                   /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1318                   UseOdrIndicator));
1319               MPM.addPass(
1320                   createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1321                       /*CompileKernel=*/false, Recover, UseAfterScope)));
1322             });
1323       }
1324       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1325         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1326           MPM.addPass(GCOVProfilerPass(*Options));
1327         });
1328       if (Optional<InstrProfOptions> Options =
1329               getInstrProfOptions(CodeGenOpts, LangOpts))
1330         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1331           MPM.addPass(InstrProfiling(*Options, false));
1332         });
1333 
1334       // Add UniqueInternalLinkageNames Pass which renames internal linkage
1335       // symbols with unique names.
1336       if (CodeGenOpts.UniqueInternalLinkageNames) {
1337         MPM.addPass(UniqueInternalLinkageNamesPass());
1338       }
1339 
1340       if (IsThinLTO) {
1341         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1342             Level, CodeGenOpts.DebugPassManager);
1343         MPM.addPass(CanonicalizeAliasesPass());
1344         MPM.addPass(NameAnonGlobalPass());
1345       } else if (IsLTO) {
1346         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1347                                                 CodeGenOpts.DebugPassManager);
1348         MPM.addPass(CanonicalizeAliasesPass());
1349         MPM.addPass(NameAnonGlobalPass());
1350       } else {
1351         MPM = PB.buildPerModuleDefaultPipeline(Level,
1352                                                CodeGenOpts.DebugPassManager);
1353       }
1354     }
1355 
1356     if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1357       bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1358       MPM.addPass(HWAddressSanitizerPass(
1359           /*CompileKernel=*/false, Recover));
1360     }
1361     if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1362       MPM.addPass(HWAddressSanitizerPass(
1363           /*CompileKernel=*/true, /*Recover=*/true));
1364     }
1365 
1366     if (CodeGenOpts.OptimizationLevel == 0) {
1367       addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
1368       addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1369     }
1370   }
1371 
1372   // FIXME: We still use the legacy pass manager to do code generation. We
1373   // create that pass manager here and use it as needed below.
1374   legacy::PassManager CodeGenPasses;
1375   bool NeedCodeGen = false;
1376   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1377 
1378   // Append any output we need to the pass manager.
1379   switch (Action) {
1380   case Backend_EmitNothing:
1381     break;
1382 
1383   case Backend_EmitBC:
1384     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1385       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1386         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1387         if (!ThinLinkOS)
1388           return;
1389       }
1390       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1391                                CodeGenOpts.EnableSplitLTOUnit);
1392       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1393                                                            : nullptr));
1394     } else {
1395       // Emit a module summary by default for Regular LTO except for ld64
1396       // targets
1397       bool EmitLTOSummary =
1398           (CodeGenOpts.PrepareForLTO &&
1399            !CodeGenOpts.DisableLLVMPasses &&
1400            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1401                llvm::Triple::Apple);
1402       if (EmitLTOSummary) {
1403         if (!TheModule->getModuleFlag("ThinLTO"))
1404           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1405         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1406                                  uint32_t(1));
1407       }
1408       MPM.addPass(
1409           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1410     }
1411     break;
1412 
1413   case Backend_EmitLL:
1414     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1415     break;
1416 
1417   case Backend_EmitAssembly:
1418   case Backend_EmitMCNull:
1419   case Backend_EmitObj:
1420     NeedCodeGen = true;
1421     CodeGenPasses.add(
1422         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1423     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1424       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1425       if (!DwoOS)
1426         return;
1427     }
1428     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1429                        DwoOS ? &DwoOS->os() : nullptr))
1430       // FIXME: Should we handle this error differently?
1431       return;
1432     break;
1433   }
1434 
1435   // Before executing passes, print the final values of the LLVM options.
1436   cl::PrintOptionValues();
1437 
1438   // Now that we have all of the passes ready, run them.
1439   {
1440     PrettyStackTraceString CrashInfo("Optimizer");
1441     MPM.run(*TheModule, MAM);
1442   }
1443 
1444   // Now if needed, run the legacy PM for codegen.
1445   if (NeedCodeGen) {
1446     PrettyStackTraceString CrashInfo("Code generation");
1447     CodeGenPasses.run(*TheModule);
1448   }
1449 
1450   if (ThinLinkOS)
1451     ThinLinkOS->keep();
1452   if (DwoOS)
1453     DwoOS->keep();
1454 }
1455 
1456 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1457   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1458   if (!BMsOrErr)
1459     return BMsOrErr.takeError();
1460 
1461   // The bitcode file may contain multiple modules, we want the one that is
1462   // marked as being the ThinLTO module.
1463   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1464     return *Bm;
1465 
1466   return make_error<StringError>("Could not find module summary",
1467                                  inconvertibleErrorCode());
1468 }
1469 
1470 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1471   for (BitcodeModule &BM : BMs) {
1472     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1473     if (LTOInfo && LTOInfo->IsThinLTO)
1474       return &BM;
1475   }
1476   return nullptr;
1477 }
1478 
1479 static void runThinLTOBackend(
1480     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1481     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1482     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1483     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1484     std::string ProfileRemapping, BackendAction Action) {
1485   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1486       ModuleToDefinedGVSummaries;
1487   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1488 
1489   setCommandLineOpts(CGOpts);
1490 
1491   // We can simply import the values mentioned in the combined index, since
1492   // we should only invoke this using the individual indexes written out
1493   // via a WriteIndexesThinBackend.
1494   FunctionImporter::ImportMapTy ImportList;
1495   for (auto &GlobalList : *CombinedIndex) {
1496     // Ignore entries for undefined references.
1497     if (GlobalList.second.SummaryList.empty())
1498       continue;
1499 
1500     auto GUID = GlobalList.first;
1501     for (auto &Summary : GlobalList.second.SummaryList) {
1502       // Skip the summaries for the importing module. These are included to
1503       // e.g. record required linkage changes.
1504       if (Summary->modulePath() == M->getModuleIdentifier())
1505         continue;
1506       // Add an entry to provoke importing by thinBackend.
1507       ImportList[Summary->modulePath()].insert(GUID);
1508     }
1509   }
1510 
1511   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1512   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1513 
1514   for (auto &I : ImportList) {
1515     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1516         llvm::MemoryBuffer::getFile(I.first());
1517     if (!MBOrErr) {
1518       errs() << "Error loading imported file '" << I.first()
1519              << "': " << MBOrErr.getError().message() << "\n";
1520       return;
1521     }
1522 
1523     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1524     if (!BMOrErr) {
1525       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1526         errs() << "Error loading imported file '" << I.first()
1527                << "': " << EIB.message() << '\n';
1528       });
1529       return;
1530     }
1531     ModuleMap.insert({I.first(), *BMOrErr});
1532 
1533     OwnedImports.push_back(std::move(*MBOrErr));
1534   }
1535   auto AddStream = [&](size_t Task) {
1536     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1537   };
1538   lto::Config Conf;
1539   if (CGOpts.SaveTempsFilePrefix != "") {
1540     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1541                                     /* UseInputModulePath */ false)) {
1542       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1543         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1544                << '\n';
1545       });
1546     }
1547   }
1548   Conf.CPU = TOpts.CPU;
1549   Conf.CodeModel = getCodeModel(CGOpts);
1550   Conf.MAttrs = TOpts.Features;
1551   Conf.RelocModel = CGOpts.RelocationModel;
1552   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1553   Conf.OptLevel = CGOpts.OptimizationLevel;
1554   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1555   Conf.SampleProfile = std::move(SampleProfile);
1556   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1557   // For historical reasons, loop interleaving is set to mirror setting for loop
1558   // unrolling.
1559   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1560   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1561   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1562   Conf.PTO.CallGraphProfile = CGOpts.CallGraphProfile;
1563 
1564   // Context sensitive profile.
1565   if (CGOpts.hasProfileCSIRInstr()) {
1566     Conf.RunCSIRInstr = true;
1567     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1568   } else if (CGOpts.hasProfileCSIRUse()) {
1569     Conf.RunCSIRInstr = false;
1570     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1571   }
1572 
1573   Conf.ProfileRemapping = std::move(ProfileRemapping);
1574   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1575   Conf.DebugPassManager = CGOpts.DebugPassManager;
1576   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1577   Conf.RemarksFilename = CGOpts.OptRecordFile;
1578   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1579   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1580   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1581   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1582   switch (Action) {
1583   case Backend_EmitNothing:
1584     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1585       return false;
1586     };
1587     break;
1588   case Backend_EmitLL:
1589     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1590       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1591       return false;
1592     };
1593     break;
1594   case Backend_EmitBC:
1595     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1596       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1597       return false;
1598     };
1599     break;
1600   default:
1601     Conf.CGFileType = getCodeGenFileType(Action);
1602     break;
1603   }
1604   if (Error E = thinBackend(
1605           Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1606           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1607     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1608       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1609     });
1610   }
1611 }
1612 
1613 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1614                               const HeaderSearchOptions &HeaderOpts,
1615                               const CodeGenOptions &CGOpts,
1616                               const clang::TargetOptions &TOpts,
1617                               const LangOptions &LOpts,
1618                               const llvm::DataLayout &TDesc, Module *M,
1619                               BackendAction Action,
1620                               std::unique_ptr<raw_pwrite_stream> OS) {
1621 
1622   llvm::TimeTraceScope TimeScope("Backend");
1623 
1624   std::unique_ptr<llvm::Module> EmptyModule;
1625   if (!CGOpts.ThinLTOIndexFile.empty()) {
1626     // If we are performing a ThinLTO importing compile, load the function index
1627     // into memory and pass it into runThinLTOBackend, which will run the
1628     // function importer and invoke LTO passes.
1629     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1630         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1631                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1632     if (!IndexOrErr) {
1633       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1634                             "Error loading index file '" +
1635                             CGOpts.ThinLTOIndexFile + "': ");
1636       return;
1637     }
1638     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1639     // A null CombinedIndex means we should skip ThinLTO compilation
1640     // (LLVM will optionally ignore empty index files, returning null instead
1641     // of an error).
1642     if (CombinedIndex) {
1643       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1644         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1645                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1646                           CGOpts.ProfileRemappingFile, Action);
1647         return;
1648       }
1649       // Distributed indexing detected that nothing from the module is needed
1650       // for the final linking. So we can skip the compilation. We sill need to
1651       // output an empty object file to make sure that a linker does not fail
1652       // trying to read it. Also for some features, like CFI, we must skip
1653       // the compilation as CombinedIndex does not contain all required
1654       // information.
1655       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1656       EmptyModule->setTargetTriple(M->getTargetTriple());
1657       M = EmptyModule.get();
1658     }
1659   }
1660 
1661   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1662 
1663   if (CGOpts.ExperimentalNewPassManager)
1664     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1665   else
1666     AsmHelper.EmitAssembly(Action, std::move(OS));
1667 
1668   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1669   // DataLayout.
1670   if (AsmHelper.TM) {
1671     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1672     if (DLDesc != TDesc.getStringRepresentation()) {
1673       unsigned DiagID = Diags.getCustomDiagID(
1674           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1675                                     "expected target description '%1'");
1676       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1677     }
1678   }
1679 }
1680 
1681 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1682 // __LLVM,__bitcode section.
1683 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1684                          llvm::MemoryBufferRef Buf) {
1685   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1686     return;
1687   llvm::EmbedBitcodeInModule(
1688       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1689       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1690       &CGOpts.CmdArgs);
1691 }
1692